mercredi 19 avril 2017

while loop counting one to many times

Working on a school project, where we are making a simulated tennis game. I've made the following code to simulate a match. Something seems to be wrong with p1WinCount or p2WinCount. if they play three "sets" and player2 only wins one, it still writes as he won the game.

E.g. of the problem

E.g. of the problem

public static int GetScore()
{
    int score = rand.Next(7);
    return score;
}

public void Game(int SetWinCount)
{
    game = true;
    turn = true;
    while (game != false)
    {
        if (turn == true)
        {
            var result = GetScore();

            if (result == 6)
            {
                Console.WriteLine(result + " - " + player2LastRoll + "    Player 1 won this set");

                if (WinCount != SetWinCount)
                {
                    game = true;
                    p1WinCount++;
                    WinCount++;


                }
                else
                {
                    game = false;
                }
            }
            else
            {
                player1LastRoll = result;
                turn = false;
            }
        }

        if (turn == false)
        {
            var result = GetScore();

            if (result == 6)
            {
                Console.WriteLine(player1LastRoll + " - " + result + "    Player 2 won this set");
                if (WinCount != SetWinCount)
                {
                    game = true;
                    p2WinCount++;
                    WinCount++;
                }
                else
                {
                    game = false;
                }
            }
            else
            {
                player2LastRoll = result;
                turn = true;
            }
        }

    }
    if (p1WinCount > p2WinCount)
    {
        Console.WriteLine("Player 1 WINS");
    }
    else
    {
        Console.WriteLine("Player 2 WINS");
    }
}


static void Main(string[] args)
{
    TennisGame game = new TennisGame();
    game.Game(2);
}




Aucun commentaire:

Enregistrer un commentaire