0

I created a Game in c of rock, paper & scissors. The problem is whenever i choose 1, my com never ever chooses anything other than 0 and 1. You can simply win the game everytime by choosing 1,2,1 or Rock,paper,rock

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

int com;

int rng(int com)
{

    srand(time(NULL));
    return rand() %com;
}

int Uscore = 0;

int Cscore = 0;

int main()
{

    int i;
    for (i = 1; i <=10; i++)
    {
        int user;
        printf("the computer chose %d\n", rng(2));
        printf("enter 0 for rock \nenter 1 paper \nenter 2 for scissors \n");
        scanf("%d", &user);

        if (com != user)
        {
            if (com == 0 && user == 1 || com == 1 && user == 2 || com == 2 && user == 0)
            {
                Uscore++;
            }
            else
                Cscore++;
        }
        else 
        printf("its a draw\n");
    }
    if (Uscore > Cscore)
    {
        printf("You won");
    }
        else 
        printf("you lost");
    }

strong text

kaylum
  • 13,833
  • 2
  • 22
  • 31
  • 4
    `srand` is only supposed to be called once for the entire program. [srand() — why call it only once?](https://stackoverflow.com/questions/7343833/srand-why-call-it-only-once) – kaylum Aug 12 '21 at 20:52
  • 1
    The `com` in `main` is the global variable `com`, which is always 0. – user3386109 Aug 12 '21 at 21:00
  • 1
    You need to save the choice the computer makes. Unrelated: Isn't it a bit like cheating that you show the computers choice _before_ asking what the user chooses? – Ted Lyngmo Aug 12 '21 at 21:03

2 Answers2

4
  • srand(time(NULL));: Seeding the pseudo-random number generator only needs to happen once, so only call srand(...) once at the start of the program. Otherwise, calling rng twice within a very short window will result in the same not-so-random number.
  • return rand() %com;: com needs to be 3 to generate a 0, 1, or 2. The modulo operator (%) is basically taking the remainder of a division.
  • The result of rng(2) (which should be rng(3)) is only used for printing. It is never actually written to com. It is better to rename the parameter of the rng function to avoid confusion, and declare com inside the main function.

E.g. modify this part like this:

int user;
int com = rng(3);
printf("the computer chose %d\n", com);
Yun
  • 3,056
  • 6
  • 9
  • 28
2

when call rng function, need to pass 3 as parameter not 2. The return value could be 0, 1, 2.

andrew68
  • 56
  • 4