0

I'm trying to implement a simply poker game (pet project). Players can do two actions: fold or check. The basic scenario is quite simple: Two players start a game. First action do player1. He can fold or check. Afterwards player2 can fold or check. I want to write proper tests and juggle actions which can do players.

My prototype code which works looks like follow.

Player player1 = new Player(1);
Player player2 = new Player(2);
List<Player> players = new List<Player>() { player1, player2 };          

Game hand = new Game();
hand.Players = players;

Thread game = new Thread(hand.WaitForPlayersAnswer);
game.Start();
Thread p1 = new Thread(player1.Check);
p1.Start();   
Thread p2 = new Thread(player2.Fold);
p2.Start();

Player:

public class Player
{
    private SemaphoreSlim _sem;
    private int _i;

    public Player(int i)
    {
        _i = i;
    }

    public void Check()
    {
        while (_sem == null)
        { }
        Console.WriteLine(_i + ": Check");
        _sem.Release();

    }

    public void Fold()
    {
        while (_sem == null)
        { }
        Console.WriteLine(_i + ": Fold");
        _sem.Release();
    }

    public void DoAction(SemaphoreSlim sem)
    {
        _sem = sem;
        sem.Wait();
        _sem = null;
    }
}

Game:

public class Game
{
    public List<Player> Players { get; set; }

    public void WaitForPlayersAnswer()
    {
        var token = new SemaphoreSlim(0);
        foreach (var player in Players)
        {
            player.DoAction(token);
        }
    }
}

I believe that it is a better way of achieving my goal. How can I do it better?

Jaryn
  • 446
  • 4
  • 16
  • Possible duplicate of [Create multiple threads and wait all of them to complete](http://stackoverflow.com/questions/4190949/create-multiple-threads-and-wait-all-of-them-to-complete) – Eugene Podskal Jan 23 '16 at 18:52
  • What I meant was to have a right way in a program flow. Player2 can not make any action before player1 finished his move (in final version there will be much more players, excluding players from game if they fold and I'll add bet method for player class). As I said it works but I am not sure if while(_sem == null) is a right way of doing that. – Jaryn Jan 23 '16 at 21:16
  • `while(_sem == null)` is a wrong way to do it - https://en.wikipedia.org/wiki/Busy_waiting. In any case the provided duplicate will give you some ideas for sure - personally I would have used Tasks(async await) for this case, though using WaitForMultipleObjects is a more valuable implementation from educational point of view. You may also try to post your code on http://codereview.stackexchange.com/, but I'm not exactly certain that it would be completely on-topic there. – Eugene Podskal Jan 24 '16 at 09:06

0 Answers0