SkinnyBetas
SkinnyBetas

Reputation: 501

C# - trying to create a console board game but can't get game to iterate through loop indefinitely

So i've pretty much got up to 6 objects which are players, and they move depending on a dice roll. The game works although i'm struggling to get the game to iterate through each players turn while the game isn't over.

so far i'm pretty much saying:

foreach (player in players)
{
     while (player.finish == false)
     {
          play_turn();
     }
}

But with a while loop it will stay on player 1's turn until they finish the game, then go to player 2. Whereas if I use an if instead of a while it will only iterate for as many players are in the game...

Maybe i've been overthinking it, any help would be appreciated

Upvotes: 0

Views: 239

Answers (1)

Brandon Avant
Brandon Avant

Reputation: 689

You must wrap the while around the foreach. The while would check if the game is over on each iteration. Within the foreach, each player will take turns until the game is over.

Consider the example below:

using System;
using System.Collections.Generic;
using System.Threading;
using System.Timers;

namespace Sandbox
{
    public class Player
    {
        public string PlayerName { get; set; }
    }

    public class Program
    {
        public static Player _currentTurn;
        public static bool _isGameOver;
        public static System.Timers.Timer _gameTimer;

        static void Main(string[] args)
        {
            _gameTimer = new System.Timers.Timer(10000);
            _gameTimer.Elapsed += _gameTimer_Elapsed;

            var players = new List<Player>()
            {
                new Player() { PlayerName = "Player1" },
                new Player() { PlayerName = "Player2" },
                new Player() { PlayerName = "Player3" }
            };

            _gameTimer.Start();

            while (!_isGameOver)
            {
                foreach (var player in players)
                {
                    _currentTurn = player;

                    PlayTurn();
                }
            }

            Console.WriteLine("Game Over!");
        }

        private static void _gameTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            _isGameOver = true;
            _gameTimer.Stop();
        }

        public static void PlayTurn()
        {
            Console.WriteLine($"{_currentTurn.PlayerName} took their turn.");
            Thread.Sleep(1000);
        }
    }
}

A timer is created; once elapsed, the game ends. Within the confines of the timer's life, the players each take turns.

Upvotes: 2

Related Questions