[Solved] How to create a player system?


First, you have an infinite loop there. If you plan to play the whole game in that function, you should rename it to something like PlayGame. I will assume you’ll call the function once per turn, and the only reason for the loop is in case the user entered illegal input and you’re retrying it.

Here’s a way to do what you’re doing above.

class Chessgame:
    white_turn = False
    def PlayerTurn(self):
        self.white_turn = not self.white_turn
        done = False
        while not done:
            if self.white_turn:
                print("White Player's turn")
            else
                print("Black Player's turn")
            ... logic to get and verify player's input here ...
            done = True

But that doesn’t do what you asked, which is a function to return 0 or 1 based on whose turn it is. Here’s code that allows you to call a function to tell you whose turn it is (but without 0 or 1), and you can call that function any number of times, with another function to advance to the next player:

class Chessgame:
    turn = 1
    def whiteTurn(self):
        return (self.turn & 1) == 1

    def endTurn(self):
        turn += 1

whiteTurn returns True if it’s white’s turn, or False if it’s black’s turn. Call endTurn() whenever the current player’s turn is over. (turn & 1 evaluates to 1 if turn is odd, zero otherwise. & is the bitwise AND operator.)

Another improvement would be to have Player objects, like this:

class Player:
    def __init__(self, color):
        self.color = color

    def __str__(self):
        return self.color

class Chessgame:
    players = (Player("white"), Player("black"))
    turn = 0

    def player(self):
        return self.players[self.turn & 1]

    def endTurn(self):
        print("Turn over for", self.player())
        self.turn += 1
        print("Turn starts for", self.player())

I wouldn’t actually put the print statements in endTurn() but provided them to show you how the player object can be used.

0

solved How to create a player system?