In the code below, the when check_result returns true, I want my program to terminate.
However, when check_result(p1) returns True
the print statement prints, but the program carries on.
BUT if check_result(p2) returns True
, the statement gets printed and program terminates. Please help me figure out why the first one doesn't work
Thanks!
while game_on:
p1_turn = int(input(f"Player 1, choose a number between 1 and 9\n"))
matrix[p1_turn - 1] = "X"
p1.append(p1_turn)
place_mark(matrix)
if check_result(p1):
print("Player 1 wins")
game_on = False
p2_turn = int(input(f"Player 2, choose a number between 1 and 9\n"))
matrix[p2_turn - 1] = "0"
p2.append(p2_turn)
place_mark(matrix)
if check_result(p2):
print("Player 2 wins")
game_on = False
CodePudding user response:
while game_on:
p1_turn = int(input(f"Player 1, choose a number between 1 and 9\n"))
matrix[p1_turn - 1] = "X"
p1.append(p1_turn)
place_mark(matrix)
if check_result(p1):
print("Player 1 wins")
game_on = False
break
p2_turn = int(input(f"Player 2, choose a number between 1 and 9\n"))
matrix[p2_turn - 1] = "0"
p2.append(p2_turn)
place_mark(matrix)
if check_result(p2):
print("Player 2 wins")
game_on = False
Just add the break statement, which will be implemented if Player 1 wins, which sets the game_on as false and terminates the loop.
Your code works for the case when Player 2 wins, so this is the only required change
CodePudding user response:
just put a break statement. and the game_on variable is uneccessary. just use while 1
that is slightly faster than while True
.
while 1:
p1_turn = int(input(f"Player 1, choose a number between 1 and 9\n"))
matrix[p1_turn - 1] = "X"
p1.append(p1_turn)
place_mark(matrix)
if check_result(p1):
print("Player 1 wins")
break
p2_turn = int(input(f"Player 2, choose a number between 1 and 9\n"))
matrix[p2_turn - 1] = "0"
p2.append(p2_turn)
place_mark(matrix)
if check_result(p2):
print("Player 2 wins")
break
CodePudding user response:
if check_result(p1):
print("Player 1 wins")
game_on = False
Do you see any break
statement here? The while
loop won't break by itself.
if check_result(p1):
print("Player 1 wins")
game_on = False
break
You can anyway completely replace this game_on
variable with a break
statement:
if check_result(p1):
print("Player 1 wins")
break
if check_result(p2):
print("Player 2 wins")
break
If you want to know better the usage of break
(and maybe of continue
) read this
.