Created
January 15, 2023 18:53
-
-
Save JosiasAurel/86af58673c6a72d0fd0478ea52d4332b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
board = [i for i in range(9)] | |
is_win = False # keeps track of whether there is a winner or not | |
def print_board(): | |
count = 0 | |
for i in board: | |
if count == 3 or count == 6: | |
print() | |
print(i, end=" ") | |
count += 1 | |
print() | |
# print_board(board) | |
players = {} | |
def init_game(): | |
player_1 = input("Player 1 name : ") | |
player_2 = input("Player 2 name : ") | |
players["O"] = player_1 if len(player_1) > 0 else "Player 1" | |
players["X"] = player_2 if len(player_2) > 0 else "Player 2" | |
return | |
def play(player, position): | |
if type(board[position]) == str: | |
next_pos = int(input(f"{players[player]} ({player}) : ")) | |
play(player, next_pos) | |
else: | |
board[position] = player | |
return | |
def all_lose(): | |
all_str = True | |
for i in board: | |
if not type(i) == str: | |
all_str = False | |
break | |
return all_str | |
def check_win_condition(player): | |
win_conditions = [ | |
[0,1,2], | |
[3,4,5], | |
[6,7,8], | |
[0,3,6], | |
[1,4,7], | |
[2,5,8], | |
[0,4,8], | |
[2,4,6], | |
] | |
result = True | |
for condition in win_conditions: | |
result = True | |
for idx in condition: | |
if not (board[idx] == player): | |
result = False | |
if result: break | |
return result | |
init_game() | |
print_board() | |
player_turn = "O" | |
# the game loop | |
while not is_win: | |
position = int(input(f"{players[player_turn]} ({player_turn}) : ")) | |
play(player_turn, position) | |
is_win = check_win_condition(player_turn) | |
print_board() | |
if all_lose(): | |
print("No Winner ;(") | |
break | |
if is_win: | |
print(f"{players[player_turn]} won") | |
if player_turn == "O": | |
player_turn = "X" | |
else: | |
player_turn = "O" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment