May-01-2020, 06:48 AM
I have tried to code Tic-Tac game.
I think my code needs lots of optimization but can't figure that out.
FYI: I haven't studied maths/matrix after schooling that is 15years ago.
That's why I used list and dict operations to create this game.
Thank you
I think my code needs lots of optimization but can't figure that out.
FYI: I haven't studied maths/matrix after schooling that is 15years ago.
That's why I used list and dict operations to create this game.
def status_print(game):
print(game[0])
print(game[1])
print(game[2])
new_game = [
[111, 222, 333],
[444, 555, 666],
[777, 888, 999]
]
game_dict = {111: (0, 0), 222: (0, 1), 333: (0, 2),
444: (1, 0), 555: (1, 1), 666: (1, 2),
777: (2, 0), 888: (2, 1), 999: (2, 2)}
status_print(new_game)
result_pending = True
game = new_game.copy()
entry_count = 0
while result_pending or entry_count < 5:
player_1 = int(input("Player 1, enter positional number of X: "))
entry_count += 1
x, y = game_dict.get(player_1)
game[x].pop(y)
game[x].insert(y, 'X')
status_print(game)
any_rowX = list((game[0].count('X'), game[1].count('X'), game[2].count('X')))
column1 = list((game[0][0], game[1][0], game[2][0]))
column2 = list((game[0][1], game[1][1], game[2][1]))
column3 = list((game[0][2], game[1][2], game[2][2]))
any_columnX = list((column1.count('X'), column2.count('X'), column3.count('X')))
diagonal1 = list((game[0][0], game[1][1], game[2][2]))
diagonal2 = list((game[2][0], game[1][1], game[0][2]))
any_diagonalX = list((diagonal1.count('X'), diagonal2.count('X')))
if 3 in any_rowX or 3 in any_columnX or 3 in any_diagonalX:
print("Player 1 won (X-X-X)!!")
print("Congratulations!!")
break
if entry_count == 5:
print("Drawn")
result_pending = False
break
player_2 = int(input("Player 2, enter positional number of O: "))
x, y = game_dict.get(player_2)
game[x].pop(y)
game[x].insert(y, 'O')
status_print(game)
any_rowO = list((game[0].count('O'), game[1].count('O'), game[2].count('O')))
column1 = list((game[0][0], game[1][0], game[2][0]))
column2 = list((game[0][1], game[1][1], game[2][1]))
column3 = list((game[0][2], game[1][2], game[2][2]))
any_columnO = list((column1.count('O'), column2.count('O'), column3.count('O')))
diagonal1 = list((game[0][0], game[1][1], game[2][2]))
diagonal2 = list((game[2][0], game[1][1], game[0][2]))
any_diagonalO = list((diagonal1.count('O'), diagonal2.count('O')))
if 3 in any_rowO or 3 in any_columnO or 3 in any_diagonalO:
print("Player 2 won (O-O-O)!!")
print("Congratulations!!")
break
print("Thank you for playing")Your even little bit tip/suggestion is appreciated.Thank you
Professional Dentist(32years) fell in love with Python during COVID-19 Lockdown.
"Nothing can stop you from learning new things except your own will"
"Nothing can stop you from learning new things except your own will"
