With the following code I implemented the mini-game "Tic-Tac-Toe" in Python. However, I am still a beginner in programming and I wanted to ask if someone could give me some tips on how to make the code more elegant and better. But please don't be too strict, because as already mentioned I am a beginner. So the code works but is not so nice/clean.
I would be very happy about answers.
from random import shuffle, seed
seed()
# Winning options are defined
WINNING_OPTIONS = [[0, 1, 2],[3, 4, 5],[6, 7, 8],[0, 3, 6],[1, 4, 7],[2, 5, 8],[0, 4, 8],[2, 4, 6]]
# Game board is created
board_fields = [box for box in range(1,10)]
def game_board():
for line in 0,3,6:
print(f"|{board_fields[line]}|{board_fields[line+1]}|{board_fields[line+2]}|")
# Start player is selected
def player_order():
liste = ["x","o"]
shuffle(liste)
return liste
# Input is checked for correctness
def input_verification():
while (user_input := "placeholder")not in board_fields:
try:
user_input = int(input(f"{xo} is now on the turn: "))
if user_input not in board_fields:
print("The input was invalid. Please try again.")
continue
board_fields[user_input-1] = xo
break
except:
print("The input was invalid. Please try again.")
continue
# Game process
game_end = False
occupied_boxes = 0
suggested_solution = []
sequence_player = player_order()
while not game_end:
for xo in sequence_player:
game_board()
input_verification()
occupied_boxes = occupied_boxes + 1
startpos = 0
while xo in board_fields[startpos:]:
pos = board_fields.index(xo, startpos)
if xo == "x":
suggested_solution.append(pos)
startpos = pos + 1
# The winner and the loser are recognized
for solution in WINNING_OPTIONS:
if set(solution) <= set(suggested_solution):
print(f"Great! You win, player {xo}")
game_end = True
if occupied_boxes == 9:
game_board()
print("Draw.")
game_end = True
break