well you need to check if the user has typed
an int or something else, so that breaks your
program, also prevent the user from overwriting
existed cell input, also prevent the user from
typing a number out of range which you have
already taken care of that, so I have written
this small function to give you the correct
input and deals with wrong ones, you can use it
def isInt(strInt):
for c in strInt:
if c not in "0123456789": return False
return True
def getNextMove():
while True:
moveStr = input("Pick a number 1-9: ")
if not isInt(moveStr):
print("Pls write only a number")
continue
move = int(moveStr)
if move < 1 or move > 9:
print("Pls only 1-9 numbers are allowed")
continue
if board[move - 1] != "-":
print("Pls choose an empty cell")
continue
return move
Well, if that helped, I couldn't stop my self from writing the full code for the game, I couldn't sleep anyway, so here it is, you may get some ideas, happy coding!
board = [" "] * 9
winner = ""
def printBoard():
print("-" * 7)
for i in range(3):
print(f"|{board[i * 3]}|{board[i * 3 + 1]}|{board[i * 3 + 2]}|")
print("-" * 7)
def isInt(strInt):
for c in strInt:
if c not in "0123456789": return False
return True
def getNextMove():
while True:
moveStr = input("Pick a number 1-9: ")
if not isInt(moveStr):
print("Pls write only a number")
continue
move = int(moveStr)
if move < 1 or move > 9:
print("Pls only 1-9 numbers are allowed")
continue
if board[move - 1] != " ":
print("Pls choose an empty cell")
continue
return move
def checkHVD():
for i in range(3):
if board[i * 3] == board[i * 3 + 1] == board[i * 3 + 2] and board[i * 3] != " ":
return board[i * 3]
elif board[i] == board[i + 3] == board[i + 6] and board[i] != " ":
return board[i]
if (board[0] == board[4] == board[8] or board[2] == board[4] == board[6]) and board[4] != " ":
return board[4]
return False
for i in range(9):
board[getNextMove() - 1] = i % 2 == 0 and "X" or "O"
printBoard()
winner = checkHVD();
if winner:
identity = winner == "X" and "first" or "second"
print(f"The {identity} player({winner}) won")
break
if not winner:
print("It's a tie")
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…