jeudi 16 juin 2016

Rand() in Rock, Paper, Scissors game

My code almost always portrays the correct result. However, sometimes in situations where the player may choose rock and the computer chooses scissors it prints out the wrong winner. I am not sure if it is because the Rand() function is round numbers in a weird way that is giving incorrect results. Any help or advice would be greatly appreciated!

#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <time.h>

using namespace std;

int chooseRPS()
{
    cout << "Please choose (1 = Rock, 2 = Paper, 3 = Scissors)\n";
    int choice;
    cin >> choice;
    return choice;
}

int playGame(int x, int y)
{
    if(x == 1 && y == 3, x == 2 && y == 1, x == 3 && y == 2)
        return x;
    else if(x == 1 && y == 2, x == 2 && y == 3, x == 3 && y == 1)
        return y;
    else 
        return x + y;
}

int main()
{
    cout << "Welcome to the game \"Rock, Paper, Scissors\"!\n";
    cout << "Player 1: ";
    int player1 = chooseRPS();

    while(player1 < 1 || player1 > 3)
    {
        cout << "Player 1, that was not a correct choice!\n";
        player1 = chooseRPS();
    }

    if(player1 == 1)
    cout << "You chose Rock!\nNow the computer will make a choice.\n";
    else if(player1 == 2)
    cout << "You chose Paper!\nNow the computer will make a choice.\n";
    else
    cout << "You chose Scissors!\nNow the computer will make a choice.\n";

    srand(time(NULL)); 
    //The computer will truly choose a random number in the rand() function

    int computer = rand() % 4 + 1; 

    if(computer == 1)
    cout << "The computer chose Rock!\n";
    else if(computer == 2)
    cout << "The computer chose Paper!\n";
    else
    cout << "The computer chose Scissors!\n";


    int result = playGame(player1, computer);

    if(result == player1)
    cout << "Player 1 is the winner!\n";
    else if (result == computer)
    cout << "The computer is the winner!\n";
    else
    cout << "The game was a tie! Please play again!\n";

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire