Doubt old game loop (Python)

Asked

Viewed 82 times

-1

Good afternoon, people. This is a code I saw that plays an old game. Could someone please explain to me how the Loop function evaluate and play_game is working? Specifically that part for player in [1, 2]:. Thank you very much.

def create_board():
    board = np.zeros((3,3), dtype=int)
    return board

def place(board, player, position):
    if board[position] == 0:
        board[position] = player
        return (board)

def possibilities(board):     
    return list(zip(*np.where(board == 0)))

def random_place(board, player):
    escolhe = random.choice(possibilities(board))
    return place(board,player,escolhe)

def row_win(board, player):
    return np.any(np.all(board==player,axis=1))

def col_win(board, player):
    return np.any(np.all(board==player,axis=0))    

def diag_win(board, player):
     if np.any(np.all(np.diagonal(board)==player)) or np.any(np.all(np.fliplr(board).diagonal() == player)):
        return True
     else:
        return False    

def evaluate(board):
    winner = 0
    for player in [1, 2]:
        if row_win(board, player) or col_win(board, player) or diag_win(board, player):
            winner = player
    if np.all(board != 0) and winner == 0:
        winner = -1
    return winner

def play_game():
    board = create_board()
    winner = 0
    while winner == 0:
        for player in [1, 2]:
            random_place(board, player)
            winner = evaluate(board)
            if winner != 0:
                break
    return winner


    

1 answer

1


Good afternoon, Let’s start with the function play_game, Yeah, she’s our main function.

The function play_game has 2 loops:

while winner == 0: Responsible for making the game work as it will perform all functions until the game has a winner winner = player or the whole board is filled winner = -1.

for player in [1, 2]: Responsible for player iteration. This loop will run 2 times, one for each item contained in the array [1, 2]. In the first iteration player will receive the value 1 (first item contained in the array), in the second iteration it will receive 2 (second item contained in the array).

Note: The shape that the loop for player in [1, 2]: for functionality evaluate is executed is the same as the functionality play_game, the only thing that changes are the calls made inside the loop.

If you still have doubts, run some tests changing the following code in a new file:

for i in [1, 2]:
    print(i)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.