В вашем коде есть несколько ошибок - см. Встроенные комментарии:
grid = [[' --- --- --- '], ['| 1 | 2 | 3 |'],
[' --- --- --- '], ['| 4 | 5 | 6 |'],
[' --- --- --- '], ['| 7 | 8 | 9 |'],
[' --- --- --- ']]
def player():
x = 0 # not used
y = 0 # not used
player1 = input("Enter Player1 move : ")
for i in grid: # each i is a list containing 1 string
for j in i: # each j is one string
if j == player1: # only ever true if playerinput is ' --- --- --- '
# or '| 1 | 2 | 3 |' or '| 4 | 5 | & |' or ....
grid[1][1] = 'X' # never hit.
Вы должны разбить свой код на более мелкие и понятные части:
def freeSpace(l,pos):
"""Returns True if l[pos] is inside the list and currently of type int - else False."""
return (0 <= pos < len(l)) and isinstance(l[pos],int)
def setPlayer(l,player,pos):
"""Checks if l[pos] is valid to be set to a players 'X' or 'O' string.
If, set it and return True, else return False."""
if freeSpace(l,pos):
l[pos] = player
return True
return False
def printList(l):
"""Pretty prints a list of 9 items in a grid with some decor around it."""
print("\n --- --- --- ")
for row in (l[i:i + 3] for i in range(0,9,3)):
print("|",end="")
for e in row:
print("{:^3}|".format(e),end="")
print("\n --- --- --- ")
def no_win(l):
# TODO - check for win, return False and a win message mayhap
return True
Основная игра:
# prepare field with integers - its easier to hold your 9 fields in a 1dim list
# and do the "comlicated" stuff in printList
tic_tac_toe = list(range(1,10))
# no players turn
player = ""
ok = True
# until all fields
while any(i in range(1,10) for i in tic_tac_toe) and no_win(tic_tac_toe):
printList(tic_tac_toe)
# last turn was ok, switch players (X starts if player = "")
if ok:
player = "X" if player != "X" else "O"
print("Your turn: ", player)
else:
# how hard can it be ...
print("Wrong move - try again: ", player)
# you could move this also in a method .. see
# https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until
try:
k = input("Which position? ")
k = int(k)-1
ok = setPlayer(tic_tac_toe, player, k)
except ValueError:
ok = False
Выход:
--- --- ---
| 1 | 2 | 3 |
--- --- ---
| 4 | 5 | 6 |
--- --- ---
| 7 | 8 | 9 |
--- --- ---
Your turn: X
Which position? Applepie
--- --- ---
| 1 | 2 | 3 |
--- --- ---
| 4 | 5 | 6 |
--- --- ---
| 7 | 8 | 9 |
--- --- ---
Wrong move - try again: X
Which position? 99
--- --- ---
| 1 | 2 | 3 |
--- --- ---
| 4 | 5 | 6 |
--- --- ---
| 7 | 8 | 9 |
--- --- ---
Wrong move - try again: X
Which position? 1
--- --- ---
| X | 2 | 3 |
--- --- ---
| 4 | 5 | 6 |
--- --- ---
| 7 | 8 | 9 |
--- --- ---
Your turn: O
Which position? 1
--- --- ---
| X | 2 | 3 |
--- --- ---
| 4 | 5 | 6 |
--- --- ---
| 7 | 8 | 9 |
--- --- ---
Wrong move - try again: O
Which position? 5
--- --- ---
| X | 2 | 3 |
--- --- ---
| 4 | O | 6 |
--- --- ---
| 7 | 8 | 9 |
--- --- ---
Your turn: X
Which position? # etc.