I am doing a Tic Tac Toe in Python for a project. The program goes great until the second try in the while loop. My check win states that p1, p2 and p3 need to be filled with 'X or 'O' and then print, but the program prints even if only p1 is filled. You can see the output of the program below. Thank you!
p1 = ''
p2 = ''
p3 = ''
p4 = ''
p5 = ''
p6 = ''
p7 = ''
p8 = ''
p9 = ''
def tabla():
row1 = print([f'{p1}',f'{p2}',f'{p3}'])
row2 = print([f'{p4}',f'{p5}',f'{p6}'])
row3 = print([f'{p7}',f'{p8}',f'{p9}'])
#################
def check_win():
if (p1 and p2 and p3) == 'X' or 'O': # x x x (board[7] == board[8] == board[9] == marker)
print('X has won the game!')
# START OF GAME
print('Welcome to my simple game! ')
while True:
answerx = input('X goes first, where to place X (1-9)? ')
if answerx == '1':
p1 = 'X'
elif answerx == '2':
p2 = 'X'
elif answerx == '3':
p3 = 'X'
elif answerx == '4':
p4 = 'X'
elif answerx == '5':
p5 = 'X'
elif answerx == '6':
p6 = 'X'
elif answerx == '7':
p7 = 'X'
elif answerx == '8':
p8 = 'X'
elif answerx == '9':
p9 = 'X'
tabla()
check_win
answero = input('O goes now, where to place O (1-9)? ')
if answero == '1':
p1 = 'O'
elif answero == '2':
p2 = 'O'
elif answero == '3':
p3 = 'O'
elif answero == '4':
p4 = 'O'
elif answero == '5':
p5 = 'O'
elif answero == '6':
p6 = 'O'
elif answero == '7':
p7 = 'O'
elif answero == '8':
p8 = 'O'
elif answero == '9':
p9 = 'O'
tabla()
check_win()
GAME OUTPUT:
Welcome to my simple game!
X goes first, where to place X (1-9)? 1
" shows the board with p1 filled with 'X' "
O goes now, where to place O (1-9)? 2
" shows the board with p2 filled with 'O' "
X has won the game!
X goes first, where to place X (1-9)?
CodePudding user response:
try this:
def check_win():
if (p1 and p2 and p3) == 'X' or (p1 and p2 and p3) == 'O':
in your check function, you currently have "or =='O'", which is not evaluating the first part of the logic (all 3 conditions are met). it simply checks if it's equal to 'O', then every time it flags the win condition.
CodePudding user response:
First you are missing the function call parentheses on your first call to check_win().
Second, you cannot use and the way you are trying. and is doing a logical comparison of truth. As long as p1, p2, and p3 have any value it will be considered true. Because of the way the output of and is written for strings in Python it will output the last value that was processed. In other words
In [14]: 'X' and ''
Out[14]: ''
In [15]: '' and 'X'
Out[15]: ''
In [16]: 'O' and 'X'
Out[16]: 'X'
In [12]: 'X' and 'O' and 'X' == 'X'
Out[12]: True
What you really need to do is check the value at each variable
One way you could do this is:
def check_win():
if p1==p2==p3=='X':
print('X has won the game!')
You obviously need this for every possible winning combination for both X and O, so there are many better ways to write this.