rock paper scissors game
Sat Jun 11 2022 13:57:21 GMT+0000 (Coordinated Universal Time)
Saved by @KanishqJ8
#include <stdio.h> #include <stdlib.h> #include <time.h> //Create Rock, Paper & Scissors Game // Player 1: rock // Player 2 (computer): scissors -->player 1 gets 1 point // rock vs scissors - rock wins // paper vs scissors - scissors wins // paper vs rock - paper wins // Write a C program to allow user to play this game three times with computer. Log the scores of computer and the player. Display the name of the winner at the end // Notes: You have to display name of the player during the game. Take users name as an input from the user. int generateRandomNumber(int n) { srand(time(NULL)); //srand takes seed as an input and is defined inside stdlib.h return rand() % n; } int greater(char c1, char c2){ //for game returns 1 if c1>c2 and 0 otherwise. if c1==c2 then it will return -1 if(c1==c2){ return -1; } if((c1=='r') && (c2=='s')){ return 1; } else{ return 0; } if((c1=='p') && (c2=='r')){ return 1; } else{ return 0; } if((c1=='s') && (c2=='p')){ return 1; } else{ return 0; } } int main() { int playerScore=0, compScore=0, temp; char playerChar, compChar; char dict[]={'r','p','s'}; printf("welcome to the rock, paper, scissors game.\n"); for(int i=0; i<3; i++){ //generating player's input printf("Player 1's turn\n"); printf("Choose 1 for rock\nChoose 2 for paper\nChoose 3 for scissors\n"); scanf("%d",&temp); getchar(); playerChar=dict[temp-1]; printf("you chose %c\n\n",playerChar); //computer's input printf("Computer's turn\n"); printf("Choose 1 for rock\nChoose 2 for paper\nChoose 3 for scissors\n"); temp=generateRandomNumber(3)+1; compChar=dict[temp-1]; printf("computer chose %c\n\n",compChar); //comparing the scores if(greater(compChar,playerChar)==1){ compScore+=1; } else if(greater(compChar,playerChar)==-1){ printf("draw\n"); } else{ playerScore+=1; } } if(playerScore> compScore){ printf("you win\n"); } else if(playerScore< compScore){ printf("you loose\n"); } else{ printf("draw\n"); } return 0; }
Comments