How to resolve the algorithm Rock-paper-scissors step by step in the C programming language

Published on 7 June 2024 03:52 AM
#C

How to resolve the algorithm Rock-paper-scissors step by step in the C programming language

Table of Contents

Problem Statement

Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules:

If both players choose the same thing, there is no winner for that round. For this task, the computer will be one of the players. The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.

Support additional choices   additional weapons.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Rock-paper-scissors step by step in the C programming language

This C program simulates a game of rock-paper-scissors between the user and the computer. Let's break down the code step by step:

  1. Header Includes:

    • The code includes necessary header files:
      • <stdio.h>: For standard input/output functions.
      • <stdlib.h>: For rand() and srand() functions for generating random numbers.
  2. Constants and Variables:

    • LEN is a constant set to 3, which represents the number of possible actions in the game (Rock, Paper, Scissors).
    • user_action and my_action are variables to store the user's and the computer's chosen actions, respectively.
    • user_rec is an array to keep track of the user's choices (rock, paper, scissors).
    • names is an array of strings representing the names of the actions (Rock, Paper, Scissors).
    • winner is an array of strings representing possible game outcomes ("We tied.", "Meself winned.", "You win.").
    • p is an array of probabilities for each action (1/3 for each action).
  3. rand_idx Function:

    • This function generates a random index from 0 to n-1 based on the probabilities specified in the p array. It uses a cumulative probability method.
  4. main Function:

    • Game Loop:
      • The main function enters an infinite loop to continuously play rounds of rock-paper-scissors.
    • User Input:
      • The program prompts the user to choose an action (1-3) and reads the input into user_action.
    • Computer Action:
      • The computer uses the rand_idx function to randomly select an action from the list of probabilities in the p array and stores it in my_action.
    • Game Logic:
      • The program calculates the outcome of the round based on the user's and computer's actions using modular arithmetic ((my_action - user_action + 3) % 3).
      • The result is printed to the console (i.e., "We tied.", "Meself winned.", or "You win.").
    • Updating User Choice Statistics:
      • The program increments the corresponding element in the user_rec array to track the user's choices.
  5. Additional Code:

    • The second version of the code includes:
      • rand_i Function: Generates a random integer between 0 and n-1.
      • weighed_rand Function: Generates a random index from 0 to len-1 based on weighted probabilities provided in the tbl array.
      • A modified main function that uses the weighted random function and tracks the user's choices in the tbl array.

Source code in the c programming language

#include <stdio.h>
#include <stdlib.h>
#define LEN 3 

/* pick a random index from 0 to n-1, according to probablities listed
   in p[] which is assumed to have a sum of 1. The values in the probablity
   list matters up to the point where the sum goes over 1 */
int rand_idx(double *p, int n)
{
	double s = rand() / (RAND_MAX + 1.0);
	int i;
	for (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++);
	return i;
}

int main()
{
	int user_action, my_action;
	int user_rec[] = {0, 0, 0};
	const char *names[] = { "Rock", "Paper", "Scissors" };
	char str[2];
	const char *winner[] = { "We tied.", "Meself winned.", "You win." };
	double  p[LEN] = { 1./3, 1./3, 1./3 };
 
	while (1) {
		my_action = rand_idx(p,LEN);
 
		printf("\nYour choice [1-3]:\n"
			"  1. Rock\n  2. Paper\n  3. Scissors\n> ");
 
		/* scanf is a terrible way to do input.  should use stty and keystrokes */
		if (!scanf("%d", &user_action)) {
			scanf("%1s", str);
			if (*str == 'q') {
				printf("Your choices [rock : %d , paper :  %d , scissors %d] ",user_rec[0],user_rec[1], user_rec[2]); 
				return 0;
			}
			continue;
		}
		user_action --;
		if (user_action > 2 || user_action < 0) {
			printf("invalid choice; again\n");
			continue;
		}
		printf("You chose %s; I chose %s. %s\n",
			names[user_action], names[my_action],
			winner[(my_action - user_action + 3) % 3]);
 
		user_rec[user_action]++;
	}
}


#include <stdio.h> // Standard IO
#include <stdlib.h> // other stuff
#include <time.h>
#include <string.h>

//This should add weighted random function to "The Elite Noob"'s code, stolen from above code because it does calculation so well
//closest I could make it to original but without pointless attempt to make code look smaller than above code by putting code on the same lines
 
int rand_i(int n)
{
	int rand_max = RAND_MAX - (RAND_MAX % n);
	int ret;
	while ((ret = rand()) >= rand_max);
	return ret/(rand_max / n);
}
 
int weighed_rand(int *tbl, int len)
{
	int i, sum, r;
	for (i = 0, sum = 0; i < len; sum += tbl[i++]);
	if (!sum) return rand_i(len);
 
	r = rand_i(sum) + 1;
	for (i = 0; i < len && (r -= tbl[i]) > 0; i++);
	return i;
}



int main(int argc, const char *argv[])
{
	char umove[10], cmove[10], line[255];
	int user, comp;
	int tbl[]={0,0,0};
	int tbllen=3;
	printf("Hello, Welcome to rock-paper-scissors\nBy The Elite Noob\n");
mainloop:
	while(1)
	{ // infinite loop :)
		printf("\n\nPlease type in 1 for Rock, 2 For Paper, 3 for Scissors, 4 to quit\n");
		srand(time(NULL));
		comp = (weighed_rand(tbl, tbllen) + 1) % 3;
		fgets(line, sizeof(line), stdin);	
		while(sscanf(line, "%d", &user) != 1) //1 match of defined specifier on input line
		{ 
  			printf("You have not entered an integer.\n");
			fgets(line, sizeof(line), stdin);
		}				
		if( (user > 4) || (user < 1) )
		{
			printf("Please enter a valid number!\n");
			continue;
		}
		switch (comp)
		{
			case 1 :
				strcpy(cmove, "Rock");
				break;
			case 2 :
				strcpy(cmove, "Paper");
				break;
			case 3 :
				strcpy(cmove, "Scissors");
				break;
			default :
				printf("Computer Error, set comp=1\n");
				comp=1;
				strcpy(cmove, "Rock");
				break;
		}
		switch (user)
		{
			case 1 :
				strcpy(umove, "Rock");
				break;
			case 2 :
				strcpy(umove, "Paper");
				break;
			case 3 :
				strcpy(umove, "Scissors");
				break;
			case 4 :
				printf("Goodbye! Thanks for playing!\n");
				return 0;
			default :
				printf("Error, user number not between 1-4 exiting...");
				goto mainloop;
		}
		if( (user+1)%3 == comp )
		{
			printf("Comp Played: %s\nYou Played: %s\nSorry, You Lost!\n", cmove, umove);
		}	
		else if(comp == user)
		{
			printf("Comp Played: %s\nYou Played: %s\nYou Tied :p\n", cmove, umove);
		}
		else
		{
			printf("Comp Played: %s\nYou Played: %s\nYay, You Won!\n", cmove, umove);
		}
		tbl[user-1]++;
	}
}


  

You may also check:How to resolve the algorithm Chinese remainder theorem step by step in the OCaml programming language
You may also check:How to resolve the algorithm Sorting algorithms/Quicksort step by step in the Action! programming language
You may also check:How to resolve the algorithm Function frequency step by step in the Nim programming language
You may also check:How to resolve the algorithm Animation step by step in the R programming language
You may also check:How to resolve the algorithm Bell numbers step by step in the AutoHotkey programming language