Python wont execute past any elif statements past the 1st one - python

I'm in the process of writing a rudimentary Connect 4 game, with the board built into the command line, etc. My problem is that I cant get the code to execute past the 2nd elif statement. I set it up so that if a certain cell in the grid does not have an underscore, it should proceed to place the piece in the next row. However, the following move always only replaces whatever piece is in the cell in row 2. I've tried starting from rows other than the bottom 2 rows, just to try to troubleshoot, but it never gets past the 1st elif statement. Can anyone tell me where I'm going wrong with my elifs?
board = []
for x in range(0, 6):
board.append(["_"] * 7)
def print_board(board):
for i in range(1,7):
print(i, end=" ")
print(7)
for row in board:
print("|".join(row))
print_board(board)
for turn in range(42):
print('Turn', turn+1)
if turn % 2 == 0:
player1 = int(input('Player 1, choose your column: '))
while player1 not in range(1,8):
player1 = int(input('You must enter a column number from 1-7: '))
if board[5][player1-1] == '_':
board[5][player1-1] = 'O'
elif board[5][player1-1] != '_':
board[4][player1-1] = 'O'
elif board[4][player1-1] != '_':
board[3][player1-1] = 'O'
elif board[3][player1-1] != '_':
board[2][player1-1] = 'O'
elif board[2][player1-1] != '_':
board[1][player1-1] = 'O'
elif board[1][player1-1] != '_':
board[0][player1-1] = 'O'
print_board(board)
elif turn % 2 != 0:
player2 = int(input('Player 2, choose your column: '))
while player2 not in range(1,8):
player2 = int(input('You must enter a column number from 1-7: '))
if board[5][player2-1] == '_':
board[5][player2-1] = 'X'
elif board[5][player2-1] != '_':
board[4][player2-1] = 'X'
elif board[4][player2-1] != '_':
board[3][player2-1] = 'X'
elif board[3][player2-1] != '_':
board[2][player2-1] = 'X'
elif board[2][player2-1] != '_':
board[1][player2-1] = 'X'
elif board[1][player2-1] != '_':
board[0][player2-1] = 'X'
print_board(board)

You should test the cells using ==, not !=. Also, you should change the same cell you test on, not the one below it:
board = []
for x in range(0, 6):
board.append(["_"] * 7)
def print_board(board):
for i in range(1,7):
print(i, end=" ")
print(7)
for row in board:
print("|".join(row))
print_board(board)
for turn in range(42):
print('Turn', turn+1)
if turn % 2 == 0:
player1 = int(input('Player 1, choose your column: '))
while player1 not in range(1,8):
player1 = int(input('You must enter a column number from 1-7: '))
if board[5][player1-1] == '_':
board[5][player1-1] = 'O'
elif board[4][player1-1] == '_':
board[4][player1-1] = 'O'
elif board[3][player1-1] == '_':
board[3][player1-1] = 'O'
elif board[2][player1-1] == '_':
board[2][player1-1] = 'O'
elif board[1][player1-1] == '_':
board[1][player1-1] = 'O'
elif board[0][player1-1] == '_':
board[0][player1-1] = 'O'
print_board(board)
elif turn % 2 != 0:
player2 = int(input('Player 2, choose your column: '))
while player2 not in range(1,8):
player2 = int(input('You must enter a column number from 1-7: '))
if board[5][player2-1] == '_':
board[5][player2-1] = 'X'
elif board[4][player2-1] == '_':
board[4][player2-1] = 'X'
elif board[3][player2-1] == '_':
board[3][player2-1] = 'X'
elif board[2][player2-1] == '_':
board[2][player2-1] = 'X'
elif board[1][player2-1] == '_':
board[1][player2-1] = 'X'
elif board[0][player2-1] == '_':
board[0][player2-1] = 'X'
print_board(board)

Related

How to copy, print list and store values in function each time the function is called (Tic tac toe game)

I am a little confused on how parameters work and calling functions with return statements. I am trying to create a new graph from the old one so that if I play again it will start over. I have tried copying the list in the run function and printing it out but it seems as though the new values are being placed in the old list. I also believe that my check_win function could be simplified greatly although I am not sure how to do so.
graph = [[' ', '|', ' ', '|', ' '],
['-','+', '-', '+', '-'],
[' ', '|', ' ', '|', ' '],
['-', '+', '-', '+', '-'],
[' ', '|', ' ', '|', ' ']]
def draw_graph(new_graph):
for row in new_graph:
for col in row:
print(col, end = '')
print()
def play_game():
again = 'yes'
while again == 'yes':
new_graph = graph
draw_graph(new_graph)
won = False
current_player = 'player1'
while not won:
pos = input("Which spot do you want to place your piece (1-9)? ")
if current_player == 'player1':
symbol = 'X'
elif current_player == 'player2':
symbol = 'O'
place_spot(pos, symbol, new_graph)
draw_graph(new_graph)
won = check_win(new_graph)
current_player = flip_player(current_player)
print("Thank you for playing.")
again = input("Do you want to play again? (yes/no) ")
def place_spot(pos, symbol, new_graph):
answer = ''
while answer != 'good':
if pos == '1':
new_graph[0][0] = symbol
break
if pos == '2':
new_graph[0][2] = symbol
break
if pos == '3':
new_graph[0][4] = symbol
break
if pos == '4':
new_graph[2][0] = symbol
break
if pos == '5':
new_graph[2][2] = symbol
break
if pos == '6':
new_graph[2][4] = symbol
break
if pos == '7':
new_graph[4][0] = symbol
break
if pos == '8':
new_graph[4][2] = symbol
break
if pos == '9':
new_graph[4][4] = symbol
break
else:
print("Please enter a number (1-9).")
def check_win(new_graph):
#top row win
if new_graph[0][0] == 'X' and new_graph[0][2] == 'X' and new_graph[0][4] == 'X':
print(f"Player 1 wins!")
won = True
return won
#middle row win
elif new_graph[2][0] == 'X' and new_graph[2][2] == 'X' and new_graph[2][4] == 'X':
print(f"Player 1 wins!")
won = True
return won
#bottom row win
elif new_graph[4][0] == 'X' and new_graph[4][2] == 'X' and new_graph[4][4] == 'X':
print(f"Player 1 wins!")
won = True
return won
#left diagonal win
elif new_graph[0][0] == 'X' and new_graph[2][2] == 'X' and new_graph[4][4] == 'X':
print(f"Player 1 wins!")
won = True
return won
#right diagonal win
elif new_graph[0][4] == 'X' and new_graph[2][2] == 'X' and new_graph[4][0] == 'X':
print(f"Player 1 wins!")
won = True
return won
#Player 2
#top row win
elif new_graph[0][0] == 'O' and new_graph[0][2] == 'O' and new_graph[0][4] == 'O':
print(f"Player 2 wins!")
won = True
return won
#middle row win
elif new_graph[2][0] == 'O' and new_graph[2][2] == 'O' and new_graph[2][4] == 'O':
print(f"Player 2 wins!")
won = True
return won
#bottom row win
elif new_graph[4][0] == 'O' and new_graph[4][2] == 'O' and new_graph[4][4] == 'O':
print(f"Player 2 wins!")
won = True
return won
#left diagonal win
elif new_graph[0][0] == 'O' and new_graph[2][2] == 'O' and new_graph[4][4] == 'O':
print(f"Player 2 wins!")
won = True
return won
#right diagonal win
elif new_graph[0][4] == 'O' and new_graph[2][2] == 'O' and new_graph[4][0] == 'O':
print(f"Player 2 wins!")
won = True
return won
def flip_player(player):
if player == 'player1':
current_player = 'player2'
return current_player
elif player == 'player2':
current_player = 'player1'
return current_player
play_game()
You can recursively copy a list using copy.deepcopy:
>>> x = [[1], [2], [3]]
>>> y = copy.copy(x) # a shallow copy
>>> y[0][0] = 5 # this modifies 'x[0]' as well
>>> x
[[5], [2], [3]]
>>> z = copy.deepcopy(x)
>>> z[0][0] = 9
>>> x
[[5], [2], [3]]

Python, unexpected looping continuously when run the codes

I am currently learning python and trying to build a tic tac toe game. I wrote a program to prevent the user repeating the same input but when I repeat the same number two times, the program starts looping continuously without stopping. Could someone give me advice on how to rectify this issue? see below the code:
from tabulate import tabulate
# define the board
board = ["_", "_", "_",
"_", "_", "_",
"_", "_", "_"]
# Current player
current_player = "X"
winner = None
game_still_on = True
def play_game():
while game_still_on:
position()
board_display()
handle_player()
winner_check()
winner_check2()
def handle_player():
global current_player
if current_player == "X":
current_player = "O"
elif current_player == "O":
current_player = "X"
def board_display():
board_row1 = [board[0], board[1], board[2]]
board_row2 = [board[3], board[4], board[5]]
board_row3 = [board[6], board[7], board[8]]
com_board = [board_row1,
board_row2,
board_row3]
print(tabulate(com_board, tablefmt="grid"))
# position input
def position():
global board
print(current_player+"'s turn")
positions = input("enter 1-9")
valid = False
while not valid:
while int(positions) >= 10 or 0 >= int(positions):
positions = input("Choose a position from 1 -9")
positions = int(positions)
if board[positions-1] == "_":
valid = True
else:
print("Choose another")
board[positions - 1] = current_player
def winner_check():
if board[0] == board[1] == board[2] != "_":
return board[0]
elif board[3] == board[4] == board[5] != "_":
return board[3]
elif board[6] == board[7] == board[8] != "_":
return board[6]
elif board[0] == board[3] == board[6] != "_":
return board[0]
elif board[1] == board[4] == board[7] != "_":
return board[1]
elif board[2] == board[5] == board[8] != "_":
return board[2]
elif board[0] == board[4] == board[8] != "_":
return board[0]
elif board[2] == board[4] == board[6] != "_":
return board[1]
else:
return None
def winner_check2():
row_winner = winner_check()
if row_winner:
global game_still_on
global winner
winner = row_winner
print((winner+ " won"))
game_still_on = False
play_game()
Let's look at this function:
# position input
def position():
global board
print(current_player+"'s turn")
positions = input("enter 1-9")
valid = False
while not valid:
while int(positions) >= 10 or 0 >= int(positions):
positions = input("Choose a position from 1 -9")
positions = int(positions)
if board[positions-1] == "_":
valid = True
else:
print("Choose another")
board[positions - 1] = current_player
This has nested validation loops. The inner one checks the range of the input integer (if it is an integer -- otherwise it throws an exception) and requests input until it's in range. That's fine.
Then in the outer validation loop, it checks if the requested space is unoccupied. If so, fine. If not, it prompts the user to choose another. But the input call is before the outer loop, so it just tries again to validate the same input that already failed.
Try moving the input into the outer loop:
# position input
def position():
global board
print(current_player+"'s turn")
valid = False
while not valid:
positions = input("enter 1-9")
while int(positions) >= 10 or 0 >= int(positions):
positions = input("Choose a position from 1 -9")
positions = int(positions)
if board[positions-1] == "_":
valid = True
else:
print("Choose another")
board[positions - 1] = current_player
I'd probably also change the inner loop to be just an if with a continue and make the handling of non-integer input more robust.

Loop To Change Value In Matrix for Tic Tac Toe Game?

Im making a Tic Tac Toe game and I do have working code and it does what I want it to do so far. I was just wondering if there was a way to shorten this function at all. My code is as follows...
def EnterMove(board):
move = input("Enter your move (number between 1 - 9): ")
if move == '1':
board[0][0] = 'O'
elif move == '2':
board[0][1] = 'O'
elif move == '3':
board[0][2] = 'O'
elif move == '4':
board[1][0] = 'O'
elif move == '5':
board[1][1] = 'O'
elif move == '6':
board[1][2] = 'O'
elif move == '7':
board[2][0] = 'O'
elif move == '8':
board[2][1] = 'O'
elif move == '9':
board[2][2] = 'O'
#Making the playing board
board = []
for i in range(3):
row = [Empty for i in range(3)]
board.append(row)
board[0][0] = '1'
board[0][1] = '2'
board[0][2] = '3'
board[1][0] = '4'
board[1][1] = '5'
board[1][2] = '6'
board[2][0] = '7'
board[2][1] = '8'
board[2][2] = '9'
So like I said this all works just fine for what I want it to do so far, I was just wondering if there was an easier way to build the board and build the EnterMove function. Thanks so much.
(Note: The player move is going to be "O's" while the computer's will be "X's" and I'm just going to us pretty much the same code for the player move function, but just use str(random.randint(1,9)) for it to decided the computer's move)
You can use division and modulo to obtain the rows and columns instead:
def EnterMove(board):
move = int(input("Enter your move (number between 1 - 9): ")) - 1
board[move // 3][move % 3] = 'O'
board = []
for i in range(3):
row = [Empty for i in range(3)]
board.append(row)
for i in range(9):
board[i // 3][i % 3] = str(i + 1)

Tic Tac Toe Game, I want to offer the user the option to save game during gameplay(after first move). Here's a portion of my current code

I am attempting to prompt the user the option to save the game, after the first move, during gameplay?
After the game is completed I want to prompt the user to reset the game(Y or N) then call the play game function(with a loop)?
However, I am unsure how to organize the code to accomplish these tasks. I am a beginner to python.
def play_game():
game = True
while game == True:
game_choice = menu()
if game_choice == 1:
choice_one()
elif game_choice ==2:
player1VSai()
elif game_choice ==3:
save_and_exit()
elif game_choice==4:
load_game()
#After the game is completed I want to reset the game and call the play game function(with a loop).
# reset_game()
# play_game()
def choice_one():
# Display initial board
display_board()
while game_still_playing:
# handle a single turn of a arbitrary player
handle_turn(current_player)
# check if win or tie
check_if_game_over()
# flip to other player
alternate_player()
# The game has ended
if winner == 'X' or winner == 'O':
print(winner + " won.")
elif winner == None:
print("Tie.")
# handle a single turn of a random player
def handle_turn(player):
print(player + "'s turn.")
position = input("Choose a position from 1 to 9: ")
# I can index into position with int instead of string
valid = False
while not valid:
while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"] or position ==0:
position = input("Choose a position from 1-9: ")
if position == 0:
save_and_exit()
pass
# convert from string to int
position = int(position) - 1
if board[position] == '':
valid = True
else:
print("Space filled. Go again.")
# Board at position equals X
board[position] = player
display_board()
print("Press 0 to save & exit game.")
#then if? or loop? prompt user to save game?
For saving code, your Game has things that you should save:
The state of the board, variable player
Whose turn it is, variable
board
This means you would have to write a function that takes these 2 variables as input argument and writes the content to a file.
#Remy this is what I have for the save function,
which I believe works properly as I've saved the data I need.
def save_and_exit():
global current_player
#save and end loop
turn=current_player
option = menu()
file=open("HW3game.txt", "w")
for x in board:
file.write(x)
file.write(turn)
file.write(str(option))
file.close()
print("You have saved the game and exited")
return
import random
# functions
# board
# display board
# ask if you want to be x or O
# menu
# play game
# take input & alternate turns
# check win
# check rows
# check columns
# check diagonals
# check tie
# is board full
# ---- Global Variables -----
# Game Board
board = [''] * 9
# If game is still going
game_still_playing = True
# Who won? Or Tie?
winner = None
# Prompt user to choose X's or O's
letter = input("Choose a letter X or O: ").upper()
current_player = letter
# Input validation
while current_player not in ('x', 'o', 'X', 'O'):
letter = input("Try again. Choose a letter X or O:").upper()
current_player = letter
if letter.upper() not in ('X', 'O'):
print("Not an appropriate choice.")
else:
break
print("Player 1 will be ", current_player + "'s.\n")
def display_board():
print(board[6], "\t|", board[7] + " | " + board[8])
print("--------------")
print(board[3], "\t|", board[4] + " | " + board[5])
print("--------------")
print(board[0], "\t|", board[1] + " | " + board[2])
# ("1) Player 1 vs Player 2\n2) Player 1 vs AI\n3) Load Game\n0) Save & Exit")
# play tic tac toe
def play_game():
begin = "Y"
while begin == "Y":
game_choice = menu()
if game_choice == 1:
choice_one()
elif game_choice ==2:
player1VSai()
elif game_choice ==3:
save_and_exit()
elif game_choice==4:
load_game()
def choice_one():
# Display initial board
display_board()
while game_still_playing:
# handle a single turn of a arbitrary player
handle_turn(current_player)
# check if win or tie
check_if_game_over()
# flip to other player
alternate_player()
# The game has ended
if winner == 'X' or winner == 'O':
print(winner + " won.")
clear_board = reset_game()
play_game()
elif winner == None:
print("Tie.")
reset_game()
play_game()
# handle a single turn of a random player
def handle_turn(player):
print(player + "'s turn.")
position = input("Choose a position from 1 to 9: ")
# I can index into position with int instead of string
valid = False
while not valid:
while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"] or position ==0:
position = input("Choose a position from 1-9: ")
if position == 0:
save_and_exit()
pass
# convert from string to int
position = int(position) - 1
if board[position] == '':
valid = True
else:
print("Space filled. Go again.")
# Board at position equals X
board[position] = player
display_board()
print("Press 0 to save & exit game.")
#then if? or loop? prompt user to save game?
def check_if_game_over():
# 3 in a row
check_for_winner()
# full board
check_if_tie()
def check_for_winner():
# Set up global variables
global winner
# check rows
row_winner = check_rows()
# check columns
column_winner = check_columns()
# check diagonals
diagonal_winner = check_diagonals()
if row_winner:
winner = row_winner
print("There was a ROW win!")
elif column_winner:
winner = column_winner
print("There was a COLUMN win!")
elif diagonal_winner:
winner = diagonal_winner
print("There was a DIAGONAL win!")
else:
winner = None
def check_rows():
# Set up global variables
global game_still_playing
# check rows for all the same values & is not an empty ''
row_1 = board[6] == board[7] == board[8] != ''
row_2 = board[3] == board[4] == board[5] != ''
row_3 = board[0] == board[1] == board[2] != ''
# if any row does have a match, flag that there is a win
if row_1 or row_2 or row_3:
game_still_playing = False
# Return the winner (X or O)
if row_1:
return board[6]
elif row_2:
return board[3]
elif row_3:
return board[0]
# return X or O if winner
# then flag game still playing to false to end loop
def check_columns():
# Set up global variables
global game_still_playing
# check columns for all the same values & is not an empty ''
column_1 = board[6] == board[3] == board[0] != ''
column_2 = board[7] == board[4] == board[1] != ''
column_3 = board[8] == board[5] == board[2] != ''
# if any column does have a match, flag that there is a win
if column_1 or column_2 or column_3:
game_still_playing = False
# Return the winner (X or O)
if column_1:
return board[6]
elif column_2:
return board[7]
elif column_3:
return board[8]
# return X or O if winner
# then flag game still playing to false to end loop
def check_diagonals():
# Set up global variables
global game_still_playing
# check columns for all the same values & is not an empty ''
diagonal_1 = board[0] == board[4] == board[8] != ''
diagonal_2 = board[6] == board[4] == board[2] != ''
# if any row does have a match, flag that there is a win
if diagonal_1 or diagonal_2:
game_still_playing = False
# Return the winner (X or O)
if diagonal_1:
return board[0]
elif diagonal_2:
return board[6]
# return X or O if winner
# then flag game still playing to false to end loop
def check_if_tie():
# declare global variable
global game_still_playing
# check if board full
if '' not in board:
game_still_playing = False
return
def alternate_player():
global current_player
# if current player is == to X then change it to O
if current_player == "X":
current_player = 'O'
# if current player is == to O then change it to X
elif current_player == "O":
current_player = 'X'
def player1VSai():
#random number
return
def save_and_exit():
global current_player
#save and end loop
turn=current_player
option = menu()
file=open("HW3game.txt", "w")
for x in board:
file.write(x)
file.write(turn)
file.write(str(option))
file.close()
print("You have saved the game and exited")
return
def menu():
print("Welcome to Tic Tac Toe")
print("1) Player 1 vs Player 2\n2) Player 1 vs AI\n3) Save & Exit\n4) Load Game")
game_choice = int(input("Choose an option, 0-4: "))
#
return game_choice
def load_game():
#setup global
global current_player
file = open("HW3game.txt", "r")
for i in range(0,8):
board[i]=file.read(1)
current_player=file.read(1)
#current choice of game.
game_choice=int(file.read(1))
file.close()
print("You have called the load function.")
return
def reset_game():
global board
#erase contents in current board
#replay game
clear_board = board.clear()
return clear_board
play_game()

Difficulties with my python tic-tac-toe

I am following Charles Dierbach's book, Introduction to Computer Science using Python.
I am on chapter 5. I am trying to do this exercise on tic-tac-toe automate play.
I am having difficulties creating a function for the pc to select an empty box ([]).
Here is my code
import re
import random
def template():
mylst = list()
for i in range(0, 3):
my_temp = []
for j in range(0, 3):
my_temp.append([])
mylst.append(my_temp)
return mylst
def template_2(alst):
print()
al = ("A", "B", "C")
for a in al:
if a == "A":
print (format(a, ">6"), end="")
if a == "B":
print (format(a, ">5"), end="")
if a == "C":
print (format(a, ">5"), end="")
print()
for j in range(len(alst)):
print(str(j + 1), format( " ", ">1"), end="")
print(alst[j])
print()
def print_template(alst):
print()
al = ("A", "B", "C")
for a in al:
if a == "A":
print (format(a, ">6"), end="")
if a == "B":
print (format(a, ">4"), end="")
if a == "C":
print (format(a, ">3"), end="")
print()
for j in range(len(alst)):
print(str(j + 1), format( " ", ">1"), end="")
print(alst[j])
print()
def first_player(lst):
print()
print ("Your symbol is 'X'. ")
alpha = ("A", "B", "C")
#check it was entered correctly
check = True
temp_lst1 = []
while check:
correct_entry = False
while not correct_entry:
coord = input("Please enter your coordinates ")
player_regex = re.compile(r'(\w)(\d)')
aSearch = player_regex.search(coord)
if aSearch == None:
correct_entry = False
if aSearch.group(1) != "A" or aSearch.group(1) != "B" or aSearch.group(1) != "C" or aSearch.group(2) != 1 or aSearch.group(2) == 2 or aSearch.group(3) != 3:
correct_entry = False
if aSearch.group(1) == "A" or aSearch.group(1) == "B" or aSearch.group(1) == "C" or aSearch.group(2) == 1 or aSearch.group(2) == 2 or aSearch.group(3) == 3:
correct_entry = True
else:
correct_entry = True
blank = False
while not blank:
if lst[(int(coord[-1])) - 1][alpha.index(coord[0])] == []:
lst[(int(coord[-1])) - 1][alpha.index(coord[0])] = "X"
temp_lst1.append((int(coord[-1])-1))
temp_lst1.append((alpha.index(coord[0])))
blank = True
else:
blank = True
correct_entry = False
if blank == True and correct_entry == True:
check = False
return True
def pc_player(lst):
print()
print ("PC symbol is 'O'. ")
alpha = ("A", "B", "C")
num_list = (0, 1, 2)
for i in range(0, len(lst)):
for j in range(0, len(lst[i])):
if lst[i][j] ==[]:
lst[i][j] = "O"
break
break
return True
def check_1st_player(lst):
if lst[0][0] == "X" and lst[0][1] == "X" and lst[0][2] == "X":
return True
elif lst[1][0] == "X" and lst[1][1] == "X" and lst[1][2] == "X":
return True
elif lst[2][0] == "X" and lst[2][1] == "X" and lst[2][2] == "X":
return True
elif lst[0][0] == "X" and lst[1][0] == "X" and lst[2][0] == "X":
return True
elif lst[0][1] == "X" and lst[1][1] == "X" and lst[2][1] == "X":
return True
elif lst[0][2] == "X" and lst[1][2] == "X" and lst[2][2] == "X":
return True
elif lst[0][0] == "X" and lst[1][1] == "X" and lst[2][2] == "X":
return True
elif lst[2][0] == "X" and lst[1][1] == "X" and lst[0][2] == "X":
return True
else:
return False
def check_pc_player(lst):
if lst[0][0] == "O" and lst[0][1] == "O" and lst[0][2] == "O":
return True
elif lst[1][0] == "O" and lst[1][1] == "O" and lst[1][2] == "O":
return True
elif lst[2][0] == "O" and lst[2][1] == "O" and lst[2][2] == "O":
return True
elif lst[0][0] == "O" and lst[1][0] == "O" and lst[2][0] == "O":
return True
elif lst[0][1] == "O" and lst[1][1] == "O" and lst[2][1] == "O":
return True
elif lst[0][2] == "O" and lst[1][2] == "O" and lst[2][2] == "O":
return True
elif lst[0][0] == "O" and lst[1][1] == "O" and lst[2][2] == "O":
return True
elif lst[2][0] == "O" and lst[1][1] == "O" and lst[0][2] == "O":
return True
else:
return False
def play_game():
ask = input("Do you want to play a two player game of Tic-Tac-Toe game? (y/n) ")
if ask in yes_response:
# contruct the template for tic-tac-toe
print()
print("How many rounds do you want to play? " )
print("Please enter only odd integers" )
print("Please enter your coordinates", end="")
print(" using format A1 or B2")
print("New Round")
return True
def play_again():
tell_me = input("Do you want you play a game ? (y/n)")
if tell_me == "Y" or "y":
return True
else:
return False
def is_full(lst):
count = 0
for i in lst:
for j in i:
if j != []:
count += 1
if count == 9:
return True
#
#-- main
print("Welcome to Awesome 2 Player Tic-Tac-Toe Game? ")
print()
answer = False
yes_response =("Y", "y")
no_response = ("N", "n")
while not answer:
print("Enter an even integer to exit")
ask = int(input("How many matches do you want to play? (odd integers only)? " ))
game = play_game()
structure = template()
print_template(structure)
if ask % 2 == 1:
score_player1 = 0
score_pc = 0
count = 0
while count < ask:
pc_lst = []
if count >= 1:
structure = template()
print_template(structure)
while game:
check_pc = True
while check_pc:
pc_player(structure)
template_2(structure)
check_pc = False
check_pc_winner = True
while check_pc_winner:
game_pc = check_pc_player(structure)
check_pc_winner = False
if game_pc == True:
print("Congratulations PC won")
score_pc += 1
game = False
break
check_player1 = True
while check_player1:
first_player(structure)
template_2(structure)
check_player1 = False
check_first_winner = True
while check_first_winner:
game_first = check_1st_player(structure)
check_first_winner = False
if game_first == True:
print("Congratulations Player 1 won")
score_player1 += 1
game = False
break
board_full = False
while not board_full:
check_board = is_full(structure)
board_full = True
if check_board == True:
print("This round was a tie.")
game = False
print("Player 1 : ", score_player1, " PC : ", score_pc)
count += 1
game = True
if score_player1 > score_pc:
print("Player 1 won")
elif score_player1 < score_pc:
print("PC won")
if play_again() == False:
answer = True
else:
answer = False
The problem I have is at def pc_player():
I would like to know how to loop the list and sublists so that AI can select an empty box as its choice to place an "O"
My current for loop does not work. AI only selects the first box.
My current for loop does not work. AI only selects the first box.
I suppose you refer to this part:
def pc_player(lst):
print()
print ("PC symbol is 'O'. ")
alpha = ("A", "B", "C")
num_list = (0, 1, 2)
for i in range(0, len(lst)):
for j in range(0, len(lst[i])):
if lst[i][j] ==[]:
lst[i][j] = "O"
break
break
return True
The break instructions together with the way you initialize the for loops will only attempt to set lst[0][0]. Other cells are not considered.
To make an evenly distributed random choice, it is essential to gather the possibilities first. For this, it is convenient to have all cells in a plain list first:
from itertools import chain
all_cells = list(chain.from_iterable(lst))
Then, you can filter out non-empty cells:
empty_cells = filter(lambda l: len(l) == 0, all_cells)
# empty_cells = filter(lambda l: not l, all_cells)
# empty_cells = [cell for cell in all_cells if not cell]
Based on this you can now trigger your random selection and symbol placement:
import random
cell_to_place = random.choice(empty_cells)
cell_to_place.append('O')
If you need the index of the cell being modified, you can do the following:
import itertools
indices = list(itertools.product(range(3), range(3)))
indexed_cells = zip(indices, map(lambda (i, j): lst[i][j], indices))
indexed_cells = filter(lambda (_, l): not l, indexed_cells) # filter non-empty
(i,j), cell_to_place = random.choice(indexed_cells)
# ...
These code samples do not take into account that there could be no empty cell left. Also, your code has some general design issues. For example:
Why do you use lists as cell items in the first place? You could simply use None, 'X' and 'O' as the elements of the 2-dimensional list.
check_pc_player and check_1st_player can be easily generalized by making the symbol to check for a parameter of the function.
Why is this a while-loop?
while check_first_winner:
game_first = check_1st_player(structure)
check_first_winner = False
Start by finding all empty boxes:
empty= [(i,j) for i in range(len(lst)) for j in range(len(lst[i])) if lst[i][j]==[]]
Then choose a random one:
import random
chosen_i, chosen_j= random.choice(empty)
And finally put an O there:
lst[chosen_i][chosen_j]= 'O'

Categories

Resources