python Scopage of a function output within gameloop not evaluating - python

My problem is, after calling the function check_win in the gameloop,
even though the function evaluates false(I've checked so this is the
case), I assign this false value to gamePlaying inside the loop,
however the game loop gamePlaying conditional still evaluates true
and keeps going.
def check_win(): #function checks for three in a row across, down, and diagonals
for x in range (0, 3) :
y = x*3
if (board[y] == board[(y + 1)] and board[y] == board[(y + 2)]):
gamePlaying = False
else:
gamePlaying = True
if (board[x] == board[(x + 3)] and board[x] == board[(x + 6)]):
gamePlaying = False
else:
gamePlaying = True
if((board[0] == board[4] and board[0] == board[8]) or
(board[2] == board[4] and board[4] == board[6])):
gamePlaying = False
else:
gamePlaying = True
return(gamePlaying)
currentPlayer = [first_player,second_player] #creates list to iterate over turns
gamePlaying = True #bool for gameloop
while gamePlaying: #main game loop
for i in currentPlayer: #iterates over current player to switch turns
draw_board()
place_move = int(input(first_move + ' what is your move? ')) #inputs then places move for first_player
board[place_move] = first_player
gamePlaying = check_win() #should take bool output of check_win and store to cont or end gameloop
draw_board()
place_move = int(input(second_move + ' what is your move? ')) #inputs then places move for second_player
board[place_move] = second_player
gamePlaying = Check_win() #should take bool output of check_win and store to cont or end gameloop

The issue is that you are using if statements when you mean to use elif. See the docs.
However, what you probably want to do is return False at those points since that would allow the function to exit early and you would have to worry that gamePlaying gets set back to True by later if statements.

Related

When I run this function the returns and prints don't seem to be doing anything

def position_assign(position):
player = True
acceptable_values = range(1,9)
while player == True:
if position in acceptable_values:
for index in range(len(row1 or row2 or row3)):
if row1[index] == position:
row1[index] = 'X'
player = False
elif row2[index] == position:
row2[index] = 'X'
player = False
elif row3[index] == position:
row3[index] = 'X'
player = False
return "Now its Os turn."
while not player:
if position in acceptable_values:
for index in range(len(row1 or row2 or row3)):
if row1[index] == position:
row1[index] = 'O'
player = True
elif row2[index] == position:
row2[index] = 'O'
player = True
elif row3[index] == position:
row3[index] = 'O'
player = True
return "Now its Xs turn."
print('Test Complete')
I'd like to use the boolean variable to establish what input the user will use. X or O given that they've picked which one they'd like to use in another function that will assign player to True or False. I can get the replace to work fine in the posted function, but the returns and prints are not working.
Please call the function position_assign(pass the parameter) and call it outside the indentation of the functions also instead of return say print().

Make while loop inaccessible

I'm trying to make a simple game to practice what I've been learning in class. But I'm unable to fix a while loop that is doing something I don't want it to do.
If player_one_range_counter is identical to one of the spots (spot_1, spot_2, spot_3, etc.) the loop should be False and inaccessible. The same thing should happen if player_two_range_counter is identical to one of the spots.
If both are identical to one or any of the spots, that means their respective loops become False and the game is over. The problem is even when they're both identical to one or any of the spots the game continues. It shouldn't.
Could someone enlighten me on what I've done wrong?
continue_game = True
while continue_game:
player_one_play = True
player_two_play = True
while player_one_play:
print(user_1_name)
x = steps_to_move() # returns int from steps_to_move()
player_one_range_counter += x # updates the range for palyer one
user_1_turtle.fd(x) # turtle move x amount of pixels forward
if player_one_range_counter == spot_1 or player_one_range_counter == spot_2 or player_one_range_counter == spot_3 or player_one_range_counter == spot_4 or player_one_range_counter == spot_5:
print("\n" + user_1_name, "stepped on a mine! \n")
player_one_play = False
else:
break
while player_two_play:
print(user_2_name)
y = steps_to_move()
player_two_range_counter += y
user_2_turtle.fd(y)
if player_two_range_counter == spot_1 or player_two_range_counter == spot_2 or player_two_range_counter == spot_3 or player_two_range_counter == spot_4 or player_two_range_counter == spot_5:
print("\n" + user_2_name, "stepped on a mine! \n")
player_two_play = False
else:
break
if player_one_play == False and player_two_play == False:
continue_game = False
I believe the primary problem is that this is inside the while loop:
player_one_play = True
player_two_play = True
when it should be before the while loop. How I might approach your code logic:
spots = [spot_1, spot_2, spot_3, spot_4, spot_5]
player_one_playing = True
player_two_playing = True
while True:
if player_one_playing:
print(user_1_name)
steps = steps_to_move() # returns int from steps_to_move()
user_1_turtle.fd(steps) # turtle move x amount of pixels forward
player_one_range_counter += steps # updates the range for player one
if player_one_range_counter in spots:
print("\n" + user_1_name, "stepped on a mine!\n")
player_one_playing = False
if player_two_playing:
print(user_2_name)
steps = steps_to_move()
user_2_turtle.fd(steps)
player_two_range_counter += steps
if player_two_range_counter in spots:
print("\n" + user_2_name, "stepped on a mine! \n")
player_two_playing = False
if not (player_one_playing or player_two_playing):
break
The inner while loops in your original code are effectively if statements so I have made them such in my code.

where do i incorporate that no body has won, in my tic-tac-toe game

I am new to coding and has recently started learning python. My first challenge is to build a tic tac toe game. Below are my codes for the game, everything worked fine except that when there is no winner(i.e. game draw); i want to display no body has won the game. I've tried to incorporate an else in various places. but, they didn't help. Here is my code.
# a dictionary to display the grid
grid = {
'1':'1', '2':'2', '3':'3',
'4':'4', '5':'5', '6':'6',
'7':'7', '8':'8', '9':'9'
}
# a list to store the values that has already been entered
used_places = []
# players and their symbols
player_1 = 'x'
player_2 = 'o'
# to store result
result = None
def grid_display():
#this function displays the grid
print('\n\n')
print(grid['1'], '\t|\t', grid['2'], '\t|\t', grid['3'])
print(''.rjust(19,'*'))
print(grid['4'], '\t|\t', grid['5'], '\t|\t', grid['6'])
print(''.rjust(19, '*'))
print(grid['7'], '\t|\t', grid['8'], '\t|\t', grid['9'])
def win_the_game():
# this function checks for result and returns true or false
if(
(grid['1'] == grid['2'] == grid['3']) or (grid['4'] == grid['5'] == grid['6']) or
(grid['7'] == grid['8'] == grid['9']) or (grid['1'] == grid['4'] == grid['7']) or
(grid['2'] == grid['5'] == grid['8']) or (grid['3'] == grid['6'] == grid['9']) or
(grid['1'] == grid['5'] == grid['9']) or (grid['3'] == grid['5'] == grid['7'])
):
return True
else:
return False
def taking_turns(turn):
#this function asks user for input
print("its turn of ", turn)
choice = input("enter your choice")
while not (choice.isdecimal() and choice in grid and (choice not in used_places)):
# taking proper input by checkin it with already entered numbers
# and if it is a number
# and if number is in between 1 and 9
choice = input("\nenter your choice properly:")
player_move(choice, turn)
def player_move(move, assign):
# this function fills the entered numbers into used_places list
# and replaces numbers in grid with user input
used_places.append(move)
grid[move] = assign
print("player 1 : 'X'")
print("player 2 : 'O'")
for i in range(0,10): # loops 9 times to play the game
if i % 2 == 0: # giving turns. if i is even, player 1 gets turn and odd, player 2
grid_display() # displaying complete grid
turn = player_1 # to display whose turn it is; refer the function
taking_turns(turn)
if win_the_game() == True: # if the called function returns true in this 'if'
result = turn # player 1 wins
break
else:
grid_display() # same code as above
turn = player_2
taking_turns(turn)
if win_the_game() == True:
result = turn
break
print('\n\n',result, "won the game!!") # printing result
Instead of setting result = None, set result = 'Nobody'.
Looking at your logic, you only set result if somebody wins, this would leave the default of result to nobody.
-- edit --
Sorry, I kinda got carried away and re-wrote the logic of your game in proving my solution. Take it or leave it, but it works great now and maybe you can use it as an example to fix your own.
import os
# a dictionary to display the grid
grid = {
'1':'1', '2':'2', '3':'3',
'4':'4', '5':'5', '6':'6',
'7':'7', '8':'8', '9':'9'
}
# a list to store the values that are available
places = ['1','2','3','4','5','6','7','8','9']
# to store result
result = 'Nobody'
# starting player
turn = 'O'
# display a game grid
def grid_display():
os.system('cls' if os.name == 'nt' else 'clear')
#this function displays the grid
print
print(grid['1'], '|', grid['2'], '|', grid['3'])
print(''.rjust(25,'*'))
print(grid['4'], '|', grid['5'], '|', grid['6'])
print(''.rjust(25, '*'))
print(grid['7'], '|', grid['8'], '|', grid['9'])
# check to see if anyone has won or are we out of moves
def win_the_game():
# this function checks for result and returns true or false
if(
(grid['1'] == grid['2'] == grid['3']) or (grid['4'] == grid['5'] == grid['6']) or
(grid['7'] == grid['8'] == grid['9']) or (grid['1'] == grid['4'] == grid['7']) or
(grid['2'] == grid['5'] == grid['8']) or (grid['3'] == grid['6'] == grid['9']) or
(grid['1'] == grid['5'] == grid['9']) or (grid['3'] == grid['5'] == grid['7'])
):
return True
# checks if there are any moves left
elif not places:
return False
else:
return False
# input / grid update function
def taking_turns():
# this function asks user for input
# use RAW_INPUT to make it a string
print
print map(str, places)
choice = raw_input("\nEnter "+turn+"'s choice: ")
if choice in places:
# this removes the number from the available list
# and replaces numbers in grid with user input
places.remove(choice)
grid[choice] = turn
# Logic loop
while places:
grid_display() # always display the grid
if turn == "O": # giving turns.
turn = 'X'
taking_turns()
if win_the_game() == True: # if the called function returns true in this 'if'
result = turn # player 1 wins
grid_display() # Winners GRID
break
else:
turn = 'O'
taking_turns()
if win_the_game() == True:
result = turn
grid_display() # Winners GRID
break
# results
print
print(result, "won the game!!") # printing result
print

python tic tac toe problems

I am new to coding and has recently started learning python. My first challenge is to build a tic tac toe game. Below are my codes for the game, everything worked fine except that when I want to restart the game or end the game, the loop won't break or the game cannot start.Could anyone figure out whats wrong with my codes. thank you!
Matrix = [[' ' for i in range(3)]for j in range(3)]
for i in Matrix:
print(i) #this is the 3x3 board
def check_done(value): #this is to check if the player has won the game
for a in range(0,3):
if Matrix[0][a]==Matrix[1][a]==Matrix[2][a]==value\
or Matrix[a][0]==Matrix[a][1]==Matrix[a][2]==value:
print ('won')
return True
#when the vertical column or horizontal row is equal, the
player won the game
if Matrix[0][0]==Matrix[1][1]==Matrix[2][2]==value\
or Matrix[2][0]==Matrix[1][1]==Matrix[0][2]==value:
print('won')
return True
#when the diagonal rows are equal, the player won the game
if ' ' not in Matrix[0] and ' ' not in Matrix[1] and ' ' not in
Matrix[2]:
print('draw')
return True
#when every grid is filled in the board and no win criteria is
fulfilled, it is a draw
return False
def replay(): #this is to determine if the player wants to restart or
end the game
command =input('Enter r to restart, or e to end game: ')
while True:
if command == 'r':
player1_input()
if command == 'e':
return
break
else:
print('Invalid command.')
def player1_input(): #this is an input function to allow players to
position their next move
print('Player 1 insert your name here')
name1=input()
print('player 2 insert your name here')
name2=input()
while True:
inputValid = False
while inputValid == False:
print(name1,'please place x coordinates')
xinput=int(input())
print(name1,'please place y coordinates')
yinput=int(input())
if yinput >= 0 & yinput <= 2 & xinput >=0 & xinput <= 2:
if Matrix[yinput][xinput] == ' ':
Matrix[yinput][xinput] = 'X'
for i in Matrix:
print(i)
if check_done('X'):
print(name1,'won')
replay()
inputValid = True
inputValid = False
while inputValid == False:
print(name2,'please place x coordinates')
xinput=int(input())
print(name2,'please place y coordinates')
yinput=int(input())
if yinput >= 0 & yinput <= 2 & xinput >=0 & xinput <= 2:
if Matrix[yinput][xinput] == ' ':
Matrix[yinput][xinput] = 'O'
for i in Matrix:
print(i)
if check_done('O'):
print(name2,'won')
replay()
inputValid = True
return True
The while loop for the main gameplay is running infinite.
To solve that, you can use a continue_game flag.
A simple example:
def player1_input():
# rest of the code
continue_game = True
while continue_game:
# logic for the game
continue_game = replay()
def replay():
# Returns true or false on user input.
while True:
command = raw_input('...')
if command == 'r':
return True
elif command == 'e':
return False
else:
print ('Invalid command')
The method replay can return a boolean as approriate based on user input.
Further, note that you have to re-initialize the matrix with empty values, if the game is supposed to be restarted.
It is difficult to read the code as it is posted. But it seems to me that your while True is an infinite cycle. I dont see any break that allows you to exit the while

Python: Trying to program a variant of connect four: Winning condition doesn't stop

I have been trying to program a variant of connect four for my programming class. The board is 6x8 in size. In the variant I'm trying to program, the winning condition is to essentially build an L.
This means any construction of the form
X
X
X X
is a winning condition.
I have been trying to make a function that checks every single column for the same symbol consecutively to build a pair. And a function to do the same for every row. With these two functions I would then check if 2 pairs are consecutive, because no matter how you combine a vertical and horizontal pair, it will always build an 'L'.
To make a clear board I'm using
def ClearBoardSingle():
global Board
Board = [['0' for i in range(8)] for i in range(6)]
BoardPrint()
PlayerMoveSingle()
And for my interface I'm using
def BoardPrint():
global Board
global GameMoves
global PlayerTurn
global Player1Symbol
global Player2Symbol
print('\n\nMoves done: ' + str(GameMoves))
print('To Restart: R | To Quit: Q')
print('Valid choices: 1, 2, 3, 4, 5, 6, 7, 8')
if PlayerTurn == 0:
print('It\'s ' +str(Player1Symbol) + '\'s Turn')
if PlayerTurn == 1:
print('It\'s ' +str(Player2Symbol) + '\'s Turn')
print(Board[0])
print(Board[1])
print(Board[2])
print(Board[3])
print(Board[4])
print(Board[5])
I already figured out how to change Variables inside the Board, and I'm pretty much done. The only thing I don't know how to implement is the winning condition. I tried this function for the Rows:
def VerticalList(Column):
global Board
global Choice
global Row0
Column = int(Column)
Choice = int(Choice)
print(Column,' C')
while Column > 0:
for Board[Column][Choice] in range(Column):
Row0.append(Board[Column][Choice])
if Column ==6 or Column == -1:
break
else:
VerticalList(Column-1)
if Column ==0:
break
else:
continue
if Column == 0:
Column += 1
while Column < 5:
Column +=1
if Row0[Column] == Row0[Column-1]:
print('Pair')
else:
print('No Pair')
pass
else:
pass
But it enters an endless Loop.
I have no ideas anymore on how to implement the winning condition. I'd appreciate any kind of help or ideas. If you want me to post the whole code or other kinds of snippets, ask for them.
Thank you in anticipation!
Cool problem, below looks like a lot of code, but it's not really. I haven't checked this extensively, so I'm not confident that it doesn't find false positives, but it seems to find L's that it should be finding. The main thing I did was use itertools.combinations to take all 4-sized groups of the positions of X's and then check if they looked like patterns I was expecting for L's. In check_four_group I look at the differences within the row and columns.
from itertools import combinations
def disp_board(board):
for row in board:
print(row)
def check_winning(board):
winning = False
#Find all row,col positions of the X's
x_poses = [(i,j) for i in range(6) for j in range(8) if board[i][j] == 'X']
#Loop through every combination of four X's since it takes four to make the 'L'
for group in combinations(x_poses,4):
if(check_four_group(group)):
winning = True
break
return winning
def check_four_group(group):
rows,cols = zip(*[(r,c) for r,c in group])
row_diffs = [rows[i+1]-rows[i] for i in range(len(rows)-1)]
col_diffs = [cols[i+1]-cols[i] for i in range(len(cols)-1)]
#Uncomment this to print the row and col diffs
#print(row_diffs)
#print(col_diffs)
# Finds:
# X
# X
# X X
if row_diffs == [1,1,0] and col_diffs == [0,0,1]:
return True
# Finds:
# X
# X
# X X
elif row_diffs == [1,1,0] and col_diffs == [0,-1,1]:
return True
# Finds:
# X X
# X
# X
elif row_diffs == [0,1,1] and col_diffs == [1,0,0]:
return True
# Finds:
# X X
# X
# X
elif row_diffs == [0,1,1] and col_diffs == [1,-1,0]:
return True
# Otherwise it's not there at all (not thinking about horizontal L's but could add that)
else:
return False
#Test case 1
def test_case_1():
board = [['0' for i in range(8)] for i in range(6)]
board[2][1] = 'X'
board[2][2] = 'X'
board[3][1] = 'X'
board[4][1] = 'X'
return board
#Test case 2
def test_case_2():
board = [['0' for i in range(8)] for i in range(6)]
board[2][1] = 'X'
board[2][0] = 'X'
board[3][1] = 'X'
board[4][1] = 'X'
return board
#Test case 3
def test_case_3():
board = [['0' for i in range(8)] for i in range(6)]
board[1][0] = 'X'
board[2][0] = 'X'
board[3][0] = 'X'
board[3][1] = 'X'
return board
#Test case 4
def test_case_4():
board = [['0' for i in range(8)] for i in range(6)]
board[1][2] = 'X'
board[2][2] = 'X'
board[3][2] = 'X'
board[3][1] = 'X'
return board
##################
#Start of program#
##################
board = test_case_1()
#board = test_case_2()
#board = test_case_3()
#board = test_case_4()
disp_board(board)
if check_winning(board):
print('Victory')
else:
print('Keep playing')

Categories

Resources