I have made the main-game mechanics for the TicTacToe game; however, I don't know a way to code the end-game win conditions, i.e. How to find when someone wins/ties.
I tried using the all()
function, but either this did not work, or I used it incorrectly (probably the latter).
Here is the full code, and the list of variables for the code (as there are no comments):
def get_grid():
r1 = ['-','-','-']
r2 = ['-','-','-']
r3 = ['-','-','-']
return r1, r2, r3
def get_coords():
x = 0
y = 0
while True:
try:
x = int(input("x coord : "))
y = int(input("y coord : "))
except ValueError:
print("Must be an integer")
if x < 0 or x > 3 or y < 0 or y > 3:
print('Both values must be in the grid!')
else:
break
return x, y
def pgrid(x, y, r1, r2, r3, player):
rdict = {1:r1, 2:r2, 3:r3}
if x != 0 and y != 0:
while True:
if rdict[y][x-1] == '-':
rdict[y][x-1] = player
break
else:
print("Invalid Space!")
x, y = get_coords()
print('\t1\t2\t3')
print(' 1 |', end = '\t')
for i in r1:
print(i, end = ' | ')
print()
print(' 2 |', end = '\t')
for i in r2:
print(i, end = ' | ')
print()
print(' 3 |', end = '\t')
for i in r3:
print(i, end = ' | ')
print()
def main():
r1, r2, r3 = get_grid()
players = ['X', 'O']
pgrid(0, 0, r1, r2, r3, None)
win = False
while win == False:
for i in players:
x, y = get_coords()
pgrid(x, y ,r1 ,r2 , r3, i)
Variables
r1, r2 and r3
are the first, second, and third rows for the board. List
x and y
are the coordinates where the 'X' or 'O' is placed. Integer
rdict
navigates between the y
value entered and the row of the board. Dictionary
player
is the player. String
players
is a List of the players ('X' and 'O'
)
win
is true when a player has won / the game has tied. Boolean
The win
variable is what needs to change in answers to this question, I just need the code or at least an idea on how to code it (because I don't have any!).
Thanks in advance!