File size: 2,090 Bytes
25ff40c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b0e879
25ff40c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import streamlit as st

def multiplayer_game():
    st.title("Tic Tac Toe")

    game_state = [[' ' for i in range(3)] for j in range(3)]
    player = "X"
    winner = None

    def check_winner():
        # Check rows
        for row in game_state:
            if row == ["X", "X", "X"]:
                return "X"
            elif row == ["O", "O", "O"]:
                return "O"
        
        # Check columns
        for col in range(3):
            if game_state[0][col] == game_state[1][col] == game_state[2][col] == "X":
                return "X"
            elif game_state[0][col] == game_state[1][col] == game_state[2][col] == "O":
                return "O"
        
        # Check diagonals
        if (game_state[0][0] == game_state[1][1] == game_state[2][2] == "X" or
            game_state[0][2] == game_state[1][1] == game_state[2][0] == "X"):
            return "X"
        elif (game_state[0][0] == game_state[1][1] == game_state[2][2] == "O" or
              game_state[0][2] == game_state[1][1] == game_state[2][0] == "O"):
            return "O"
        
        return None

    def render_game_state():
        for row_num, row in enumerate(game_state):
            row_string = "|".join(row)
            st.write(row_string)
            if row_num != 2:
                st.write("-+-+-")

    for i in range(9):
        render_game_state()
        st.write("Player ", player, " turn. Choose a square (1-9).")
        chosen_square = st.number_input("", min_value=1, max_value=9, key=f"number_input_{i}")
        row = (chosen_square - 1) // 3
        col = (chosen_square - 1) % 3
        if game_state[row][col] != " ":
            st.write("Square already taken. Please choose another.")
            continue
        game_state[row][col] = player
        winner = check_winner()
        if winner:
            st.write("Player ", winner, " wins!")
            break
        if player == "X":
            player = "O"
        else:
            player = "X"
    if not winner:
        st.write("It's a draw!")

if __name__ == "__main__":
    multiplayer_game()