Not recognizing tie in Tic Tac Toe AI - python

I am building a Tic Tac Toe AI. Here are the rules for the AI:
If there is a winning move, play it.
If the opponent has a winning move, block it.
Otherwise, play randomly.
Here's the code:
# main.py
# Prorities:
# - If there is a winning move, play it
# - If the opponent has a winning move, block it.
# - If nothing to block, make a random move.
import random
import time
import copy
boxes = []
for i in range(3):
row = []
for j in range(3):
row.append(" ")
boxes.append(row)
def printBoard():
to_print = ""
to_print += " " + boxes[0][0] + " | " + boxes[0][1] + " | " + boxes[0][2] + " \n"
to_print += "---+---+---\n"
to_print += " " + boxes[1][0] + " | " + boxes[1][1] + " | " + boxes[1][2] + " \n"
to_print += "---+---+---\n"
to_print += " " + boxes[2][0] + " | " + boxes[2][1] + " | " + boxes[2][2] + " \n"
return to_print
turn = random.randint(1, 2)
if turn == 1:
coin = "you (X)"
else:
coin = "the AI (O)"
print("The coin flip shows", coin, "will go first!")
input("Press Enter to begin! ")
def checkWin(boxes):
win = False
who = " "
for i in range(3):
if boxes[i][0] == boxes[i][1] and boxes[i][1] == boxes[i][2]:
who = boxes[i][0]
if who != " ":
win = True
for i in range(3):
if boxes[0][i] == boxes[1][i] and boxes[2][i] == boxes[1][i]:
who = boxes[0][i]
if who != " ":
win = True
if boxes[0][0] == boxes[1][1] and boxes[1][1] == boxes[2][2]:
who = boxes[0][0]
if who != " ":
win = True
if boxes[0][2] == boxes[1][1] and boxes[1][1] == boxes[2][0]:
who = boxes[0][2]
if who != " ":
win = True
return win, who
def checkTie(boxes):
for row in boxes:
for box in boxes:
if box != "X" and box != "O":
return False
return True
def checkMove(boxes, player):
for i in range(3):
for j in range(3):
if boxes[i][j] != "X" and boxes[i][j] != "O":
boxCopy = copy.deepcopy(boxes)
boxCopy[i][j] = player
win, who = checkWin(boxCopy)
if win:
return True, i, j
return False, 0, 0
while True:
print("Check 1")
win, who = checkWin(boxes)
if win and who == "X":
print("Player X has won.")
print(" ")
print(printBoard())
break
elif win and who == "O":
print("Player O has won.")
print(" ")
print(printBoard())
break
elif checkTie(boxes) == True:
print("It has been concluded as a tie.")
break
print("Check 2")
if turn == 1:
print("")
print(printBoard())
row = (int(input("Pick a row to play: ")) -1)
col = (int(input("Pick a column to play: ")) -1)
if ((row < 4 and row > -1) and (col < 4 and col > -1)) and (boxes[row][col] == " "):
boxes[row][col] = "X"
turn = 2
else:
print("Sorry, that is not allowed.")
print(" ")
# Prorities:
# - If there is a winning move, play it
# - If the opponent has a winning move, block it.
# - If nothing to block, make a random move.
else:
print("")
print(printBoard())
print("[*] AI is choosing...")
time.sleep(1)
row = random.randint(0, 2)
col = random.randint(0, 2)
winMove, winRow, winCol = checkMove(boxes, "O")
lossMove, lossRow, lossCol = checkMove(boxes, "X")
if winMove and (boxes[winRow][winCol] != "X" and boxes[winRow][winCol] != "O"):
boxes[winRow][winCol] = "O"
turn = 1
print("Statement 1: Win play")
elif lossMove and (boxes[lossRow][lossCol] != "X" and boxes[lossRow][lossCol] != "O"):
boxes[lossRow][lossCol] = "O"
turn = 1
print("Statement 2: Block play")
elif boxes[row][col] != "X" and boxes[row][col] != "O":
boxes[row][col] = "O"
turn = 1
print("Statement 3: Random play")
else:
print("Statement 4: None")
print("Check 3")
The problem occurs when there is a tie. Either the function checkTie(), or the if statement isn't working. You might see a couple print('Check #') every once in a while. When you run the code and it's a tie, it shows all the checks going by. Which means it is passing through the check. When there is a tie, it just keeps doing the loop and repeating its turn but not making a move.
What is the mistake and how can I do this correctly?

I think your function should be
def checkTie(boxes):
for row in boxes:
for box in row:
if box != "X" and box != "O":
return False
return True
You mistyped ( I think) boxes for row in the second for statement.

def checkTie(boxes):
if any(" " in box for box in boxes):
return False
return True
Change your checkTie function to this
The rest is all good.

Related

How do I check if the board in tic tac toe doesn't have a number any more

for a school assignment I need to make tic tac toe, I've got pretty much everything ready, except for 1 issue, I don't know how to make the game know when it's a draw and then quit
in the function check_tie()
you can still see I have some attempts left over.
The spots in the tic tac toe board have to be numbers from 1-9 so I can't replace them with empty spaces. Meaning I can't do a check to see if there are no empty spots left
thanks in advance
Here's the full code
print ("*** Welcome to Tic Tac Teen ***")
gameboard = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
game_running = True
winner = None
player = 'X'
marker = ['X', 'O']
player_list = []
name1 = input("Fill in the name of player 1: ")
player_list.append(name1)
name2 = input("Fill in the name of player 2: ")
player_list.append(name2)
print("These are the players:", player_list)
print("These are their markers:", marker)
# Function to print gameboard
def print_gameboard(gameboard):
print(" -----------")
print(" | " + gameboard[0] + " | " + gameboard[1] + " | " + gameboard[2] + " | ")
print(" -----------")
print(" | " + gameboard[3] + " | " + gameboard[4] + " | " + gameboard[5] + " | ")
print(" -----------")
print(" | " + gameboard[6] + " | " + gameboard[7] + " | " + gameboard[8] + " | ")
print(" -----------")
print()
#Checks if the game is over by checking for a win or tie:
def check_if_game_over():
check_win()
check_tie()
def check_win():
global winner
winner_row = check_row()
winner_column = check_column()
winner_diagonal = check_diagonal()
#Gets the winer
if winner_row:
winner = winner_row
elif winner_column:
winner = winner_column
elif winner_diagonal:
winner = winner_diagonal
else: winner = None # / Tie?
#checks rows for a win, by comparing if the elements in the row are the same
def check_row():
global game_running
row1 = gameboard[0] == gameboard[1] == gameboard[2]
row2 = gameboard[3] == gameboard[4] == gameboard[5]
row3 = gameboard[6] == gameboard[7] == gameboard[8]
if row1 or row2 or row3:
game_running = False
if row1:
return gameboard[0]
elif row2:
return gameboard[3]
elif row3:
return gameboard[6]
def check_column():
global game_running
column1 = gameboard[0] == gameboard[3] == gameboard[6]
column2 = gameboard[1] == gameboard[4] == gameboard[7]
column3 = gameboard[2] == gameboard[5] == gameboard[8]
if column1 or column2 or column3:
game_running = False
if column1:
return gameboard[0]
elif column2:
return gameboard[1]
elif column3:
return gameboard[2]
def check_diagonal():
global game_running
diag1 = gameboard[0] == gameboard[4] == gameboard[8]
diag2 = gameboard[2] == gameboard[4] == gameboard[6]
if diag1 or diag2:
game_running = False
if diag1:
return gameboard[0]
elif diag2:
return gameboard[2]
def check_tie():
return
global game_running
if not position.isdigit():
game_running = False
# global game_running
# if moves == 9:
# game_running = False
def switch_player():
global player
#Switches player depending on who's turn it is.
if player =="X":
player = "O"
elif player == "O":
player = "X"
#function that runs the whole game
def play_game():
while game_running:
print("This is the current gameboard:")
moves = 0
print_gameboard(gameboard)
player_turn(player)
check_if_game_over()
switch_player()
if winner == "X":
print(player_list[0] + " won!")
elif winner == "O":
print(player_list[1] + " won!" )
elif winner == None:
print("It's a tie!")
def player_turn(player):
position = input("Choose a spot from 1-9: ")
while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
position = input("That's not a number between 1-9, try again: ")
position = int(position) - 1
# if gameboard[position] = taken (how do you do this?, )
#print(Position is already taken, please pick another spot)
gameboard[position] = player
print_gameboard(gameboard)
play_game()
Well the only way it can be a draw is when there is no winner after 9 moves right? After 9 moves just check if there is a winner; if there still isnt then it is a draw.
So in play_game() i would loop for 9 times, in each loop I would show the board like you did, make the move, check for winner, if winner then return, if not keep looping. If I happen to exit out of the loop then that means I've used up all of my moves and that there is no winner so it must be a tie.
Edit: Thats just how I would approach the problem. Your method works just as well. There is no right or wrong answer
Your code works okay as is, just replace the check_tie() function with this
def check_tie():
global game_running
game_running = any(tile.isdigit() for tile in gameboard)
You had the right idea, just didn't loop through the tiles.
For clarity, any() is a function that returns True if one of the evaluated values is True. Otherwise returns False. isdigit() is a method belonging to string which checks if all the characters included are digits or not.

Questions about a tic-tac-toe program I am writing

I am making a tic-tac-toe program in python.
I have two questions:
How to create a trick to terminate the move() when we have created a diagonal or a line(xxx or OOO) in the game.
In my program some error is occurring::in line 28::(UnboundLocalError: local variable 'stop' referenced before assignment)
My code is::
import random
board = {"top-l":" ","top-m":" ","top-r":" ","mid-l":" ","mid-m":" ","mid-r":" ","low-l":" ","low-m":" ","low-r":" "}
def print_board(board):
print( board["top-l"] + "|" + board["top-m"] + "|" + board["top-r"])
print("--------")
print( board["mid-l"] + "|" + board["mid-m"] + "|" + board["mid-r"])
print("--------")
print( board["low-l"] + "|" + board["low-m"] + "|" + board["low-r"])
if random.randint(0,1) == 1:
turn = "X"#user
else:
turn = "O"# computer
def instructions():
print("TYPE top FOR TOP ROW, mid FOR MIDDLE ROW AND low FOR LOWEST ROW")
print(" ")
print("TYPE -l FOR LEFT CORNER, -m FOR MIDDLE CORNER AND -r FOR RIGHT CORNER")
print(" ")
print("SO COMMAND FOR TOP RIGHT CORNER SHOULD BE top-r ")
print("AN EMPTY BOARD LOOKS LIKE::")
print_board(board)
def move():
for i in range(10):
print_board(board)
print("CHANCE NO. " + str(i))
if turn == "O":
if i == 1:
print("COMPUTER WILL TAKE THE FIRST TURN(FOR " + turn + ")")
else:
print("IT'S COMPUTER TURN NOW")
y = random.randint(0,9)
move = str(board_list[y])
elif turn == "x":
if i == 1:
print("USER WILL TAKE THE FIRST TURN(FOR " + turn + "). PLEASE ENTER YOUR MOVE")
else:
print("IT'S USERS TURN NOW. PLEASE ENTER YOUR MOVE")
move = input()
print("STEP TAKEN IS ::" + move)
board["move"] = turn
if turn == "x":
tu = 0
turn = "O"
elif turn == "O":
tu = 1
turn = "X"
if board["top-l"] == board["top-m"] == board["top-r"] or board["mid-l"] == board["mid-m"] == board["mid-r"] or board["low-l"] == board["low-m"] == board["low-r"] or board["mid-l"] == board["top-l"] == board["low-l"] or board["mid-m"] == board["top-m"] == board["low-m"] or board["mid-r"] == board["top-r"] == board["low-r"] or board["top-l"] == board["mid-m"] == board["low-r"] or board["top-r"] == board["mid-m"] == board["low-l"]:
stop = 1
else:
stop = 0
if __name__ == "__main__":
board_list = list(board.keys())
tu = int(0)# 0 for computer
# 1 for user
stop = int(0)# 0 = continue
print("PRESENTING YOU TIC-TAC-TOE GAME v1.0 BY DK SHARAMA")
print("PLEASE ENTER YOUR NAME::")
user = str(input())
print("WELCOME " + user)
instructions()
print("TO PLAY PRESS 1 ELSE 0")
play = int(input())
if play == 1:
move()
if stop == 1:
print("GAME OVER")
if tu == 0:
print("COMPUTER WON")
elif tu == 1:
print("USER WON")
elif stop == 0:
print("IT'S A TIE :: NO ONE WON")

Python 3 IndentationError

In spite of seeing a lot of posts about the python indentation error and trying out a lot of solutions, I still get this error:
import random
import copy
import sys
the_board = [" "]*10
def printboard(board):
print(board[7] + " " + "|" + board[8] + " " + "|" + board[9])
print("--------")
print(board[4] + " " + "|" + board[5] + " " + "|" + board[6])
print("--------")
print(board[1] + " " + "|" + board[2] + " " + "|" + board[3])
def choose_player():
while True:
player = input("What do you want to be; X or O?")
if player == "X":
print("You chose X")
comp = "O"
break
elif player == "O":
print("You chose O")
comp = "X"
break
else:
print("Invalid Selection")
continue
return [player, comp]
def virtual_toss():
print("Tossing to see who goes first.....")
x = random.randint(0,1)
if x== 0:
print("AI goes first")
move = "comp"
if x == 1:
print("Human goes first")
move = "hum"
return move
def win(board,le):
if (board[7] == le and board[8] == le and board[9]==le) or (board[4] == le and board[5]==le and board[6] == le)or (board[1] == le and board[2]==le and board[3] == le)or (board[7] == le and board[5]==le and board[3] == le)or (board[9] == le and board[5]==le and board[1] == le)or (board[7] == le and board[4]==le and board[1] == le)or (board[8] == le and board[5]==le and board[2] == le)or (board[9] == le and board[6]==le and board[3] == le):
return True
else:
return False
def make_move(board,number,symbol):
board[number] = symbol
def board_full(board):
count = 0
for item in board:
if item in ["X","O"]:
count+= 1
if count ==9 :
return True
else:
return False
def valid_move(board,num):
if board[num] == " ":
return True
else:
return False
def player_move(board):
number = int(input("Enter the number"))
return number
def copy_board(board):
copied_board = copy.copy(board)
return copied_board
def check_corner(board):
if (board[7] == " ") or (board[9] == " ") or (board[1] == " ") or (board[3] == " "):
return True
else:
return False
def check_center(board):
if (board[5] == " "):
return True
else:
return False
while True:
count = 0
loop_break = 0
print("welcome to TIC TAC TOE")
pla,comp = choose_player()
turn = virtual_toss()
while True:
printboard(the_board)
if turn == "hum":
if board_full() == True:
again = input ("Game is a tie. Want to try again? Y for yes and N for No")
if again == "Y":
loop_break = 6
break
else:
system.exit()
if loop_break == 6:
continue
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
else:
turn = "comp"
printboard(the_board)
continue
else:
if board_full() == True:
again = input ("Game is a tie. Want to try again? Y for yes and N for No")
if again == "Y":
loop_break = 6
break
else:
system.exit()
if loop_break = 6:
continue
copy_board(the_board)
for i in range(0,9):
make_move(copied_board,i,pla)
if(win(copied_board,pla) == True):
make_move(the_board,comp)
turn = "hum"
loop_break = 1
break
else:
continue
if loop_break = 1:
continue
if (check_corner(the_board) == True) or (check_center(the_board)==True):
for i in [7,9,1,3,5]:
if(valid_move(copied_board,i)==True):
make_move(copied_board,i,comp)
if(win(copied_board,comp)==True):
make_move(the_board,i,comp)
print("The AI beat you")
loop_break = 2
count = 1
break
else:
make_move(the_board,i,comp)
turn = "hum"
loop_break = 3
break
if loop_break == 2:
break
elif loop_break == 3:
continue
else:
for i in [8,4,6,2]:
if(valid_move(copied_board,i)==True):
make_move(copied_board,i,comp)
if(win(copied_board,comp)):
make_move(the_board,i,comp)
print("The AI beat you")
count = 1
loop_break = 4
break
else:
make_move(the_board,i,comp)
turn = "hum"
loop_break = 5
break
if loop_break == 4:
break
elif loop_break == 5:
continue
if count == 1:
again = input("Would you like to play again? y/n")
if again == "y":
continue
else:
system.exit()
I know that this is quite a long code, but I will point out the particular area where the error lies. You see, I am getting the following error message:
Traceback (most recent call last):
File "python", line 106
if (win(the_board,pla) == True):
^
IndentationError: unindent does not match any outer indentation level
More specifically, this part of the code:
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
Any help? I cannot get the code to work by any means!!
Try unindenting the previous seven lines of code by one level (the code in that while loop). This should make the indents work correctly. Also, it seems that there is an extra space before the if statement that is causing you errors. Remove this space as well. This would make that part of the code like this:
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
You need to indent the block under while (True): consistently. E.g.:
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
else:
turn = "comp"
printboard(the_board)
continue
The problem is, the if statement is one indentation back from the rest of the code. You want to align all the code and the error should go away.
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break

Im getting an error in the shell whenever enter is pressed when I'm changing the board size

Have a look at ChangeBoardSize()
It'll be part of the while loop that I have to change but I'm not sure what to change or what to change it to.
I would appreciate any help for this to be done in anyway.
Ignore this but now because I am just trying to get the character count up so that I can post this.
import random
def SetUpGameBoard(Board, Boardsize, PlayerInitials, ComputerInitials):
for Row in range(1, BoardSize + 1):
for Column in range(1, BoardSize + 1):
if (Row == (BoardSize + 1) // 2 and Column == (BoardSize + 1) // 2 + 1) or (Column == (BoardSize + 1) // 2 and Row == (BoardSize + 1) // 2 + 1):
Board[Row][Column] = ComputerInitials
elif (Row == (BoardSize + 1) // 2 + 1 and Column == (BoardSize + 1) // 2 + 1) or (Column == (BoardSize + 1) // 2 and Row == (BoardSize + 1) // 2):
Board[Row][Column] = PlayerInitials
else:
Board[Row][Column] = " "
def ChangeInitials(PlayerName):
print("Enter the initials for", PlayerName, "'s piece")
PlayerInitials = input()
PlayerInitials = PlayerInitials.upper()
print("Enter the initials for the computer's piece")
ComputerInitials = input()
ComputerInitials = ComputerInitials.upper()
return ComputerInitials, PlayerInitials
def ChangeBoardSize():
BoardSize = int(input("Enter a board size (between 4 and 9): "))
while not(BoardSize >= 4 and BoardSize <= 9):
BoardSize = int(input("Enter a board size (between 4 and 9): "))
if BoardSize != [4, 5, 6, 7, 8, 9]:
ChangeBoardSize()
elif BoardSize == " ":
ChangeBoardSize()
return BoardSize
def GetHumanPlayerMove(PlayerName):
print(PlayerName, "enter the coodinates of the square where you want to place your piece: ", end="")
Coordinates = input()
if Coordinates.isdigit():
MoveValid = True
return int(Coordinates)
def GetComputerPlayerMove(BoardSize):
return random.randint(1, BoardSize) * 10 + random.randint(1, BoardSize)
def GameOver(Board, BoardSize):
for Row in range(1 , BoardSize + 1):
for Column in range(1, BoardSize + 1):
if Board[Row][Column] == " ":
return False
return True
def GetPlayersName():
PlayerName = input("What is your name? ")
return PlayerName
def CheckIfMoveIsValid(Board, Move):
Row = Move % 10
Column = Move // 10
MoveIsValid = False
if Board[Row][Column] == " ":
MoveIsValid = True
return MoveIsValid
def GetPlayerScore(Board, BoardSize, Piece):
Score = 0
for Row in range(1, BoardSize + 1):
for Column in range(1, BoardSize + 1):
if Board[Row][Column] == Piece:
Score = Score + 1
return Score
def CheckIfThereArePiecesToFlip(Board, BoardSize, StartRow, StartColumn, RowDirection, ColumnDirection):
RowCount = StartRow + RowDirection
ColumnCount = StartColumn + ColumnDirection
FlipStillPossible = True
FlipFound = False
OpponentPieceFound = False
while RowCount <= BoardSize and RowCount >= 1 and ColumnCount >= 1 and ColumnCount <= BoardSize and FlipStillPossible and not FlipFound:
if Board[RowCount][ColumnCount] == " ":
FlipStillPossible = False
elif Board[RowCount][ColumnCount] != Board[StartRow][StartColumn]:
OpponentPieceFound = True
elif Board[RowCount][ColumnCount] == Board[StartRow][StartColumn] and not OpponentPieceFound:
FlipStillPossible = False
else:
FlipFound = True
RowCount = RowCount + RowDirection
ColumnCount = ColumnCount + ColumnDirection
return FlipFound
def FlipOpponentPiecesInOneDirection(Board, BoardSize, StartRow, StartColumn, RowDirection, ColumnDirection):
FlipFound = CheckIfThereArePiecesToFlip(Board, BoardSize, StartRow, StartColumn, RowDirection, ColumnDirection)
if FlipFound:
RowCount = StartRow + RowDirection
ColumnCount = StartColumn + ColumnDirection
while Board[RowCount][ColumnCount] != " " and Board[RowCount][ColumnCount] != Board[StartRow][StartColumn]:
if Board[RowCount][ColumnCount] == "H":
Board[RowCount][ColumnCount] = "C"
else:
Board[RowCount][ColumnCount] = "H"
RowCount = RowCount + RowDirection
ColumnCount = ColumnCount + ColumnDirection
def MakeMove(Board, BoardSize, Move, HumanPlayersTurn):
Row = Move % 10
Column = Move // 10
if HumanPlayersTurn:
Board[Row][Column] = "H"
else:
Board[Row][Column] = "C"
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 1, 0)
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, -1, 0)
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, 1)
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, -1)
def PrintLine(BoardSize):
print(" ", end="")
for Count in range(1, BoardSize * 2):
print("_", end="")
print()
def DisplayGameBoard(Board, BoardSize):
print()
print(" ", end="")
for Column in range(1, BoardSize + 1):
print(" ", end="")
print(Column, end="")
print()
PrintLine(BoardSize)
for Row in range(1, BoardSize + 1):
print(Row, end="")
print(" ", end="")
for Column in range(1, BoardSize + 1):
print("|", end="")
print(Board[Row][Column], end="")
print("|")
PrintLine(BoardSize)
print()
def DisplayMenu():
print("(p)lay game")
print("(e)nter name")
print("(c)hange board size")
print("(i)initials change")
print("(a)lter piece name")
print("(q)uit")
print()
def GetMenuChoice(PlayerName):
print(PlayerName, "enter the letter of your chosen option: ", end="")
Choice = input()
return Choice
def CreateBoard():
Board = []
for Count in range(BoardSize + 1):
Board.append([])
for Count2 in range(BoardSize + 1):
Board[Count].append("")
return Board
def PlayGame(PlayerName, BoardSize, PlayerInitials, ComputerInitials):
Board = CreateBoard()
SetUpGameBoard(Board, BoardSize, PlayerInitials, ComputerInitials)
HumanPlayersTurn = False
while not GameOver(Board, BoardSize):
HumanPlayersTurn = not HumanPlayersTurn
DisplayGameBoard(Board, BoardSize)
MoveIsValid = False
while not MoveIsValid:
if HumanPlayersTurn:
Move = GetHumanPlayerMove(PlayerName)
else:
Move = GetComputerPlayerMove(BoardSize)
MoveIsValid = CheckIfMoveIsValid(Board, Move)
if not HumanPlayersTurn:
print("Press the Enter key and the computer will make its move")
input()
MakeMove(Board, BoardSize, Move, HumanPlayersTurn)
DisplayGameBoard(Board, BoardSize)
HumanPlayerScore = GetPlayerScore(Board, BoardSize, "H")
ComputerPlayerScore = GetPlayerScore(Board, BoardSize, "C")
if HumanPlayerScore > ComputerPlayerScore:
print("Well done", PlayerName, ", you have won the game!")
elif HumanPlayerScore == ComputerPlayerScore:
print("That was a draw!")
else:
print("The computer has won the game!")
print()
random.seed()
BoardSize = 6
PlayerName = ""
Choice = ""
PlayerInitials = 'H'
ComputerInitials = 'C'
while Choice.lower() != "q": #.lower() makes any allows uppercase input
DisplayMenu()
Choice = GetMenuChoice(PlayerName)
if Choice.lower() == "p":
PlayGame(PlayerName, BoardSize, ComputerInitials, PlayerInitials)
elif Choice.lower() == "e":
PlayerName = GetPlayersName()
elif Choice.lower() == 'a':
ChangePieceName()
elif Choice.lower() == 'i':
ChangeInitials(PlayerName)
elif Choice.lower() == "c":
BoardSize = ChangeBoardSize()
There is a problem because you don't handle entering characters other than numbers so it fails on line 39
return int(Coordinates) # if Coordinates is not str convertable to int it fails
So you need to do something like
def GetHumanPlayerMove(PlayerName):
print(PlayerName, "enter the coodinates of the square where you want to place your piece: ", end="")
Coordinates = input()
if Coordinates.isdigit():
MoveValid = True
try:
return int(Coordinates)
except ValueError:
print("Please enter number")
print(PlayerName, "enter the coodinates of the square where you want to place your piece: ", end="")
return GetHumanPlayerMove(PlayerName)
Or create a while loop like you did below. So
while not isinstance(Coordinates, int): ...
The function will look like this
def GetHumanPlayerMove(PlayerName):
MoveValid = False
while not MoveValid:
print(PlayerName, "enter the coodinates of the square where you want to place your piece: ", end="")
Coordinates = input()
if Coordinates.isdigit():
MoveValid = True
return int(Coordinates)

connect four: asking for inputs without printing

I am making a connect four type game. I am trying to set up the simple playability of the game. I don't get an error, but it does keep sending me into a input when I want it to print out the board. When I type in a number for the column, it doesn't print anything, it just gives me another input I should fill, this continues until i exit the program.. I am trying to stay away from classes, given that I am not very good at programming these yet. I would like to know why this is happening, and what to do to fix it, or if I just need to reprogram the whole thing.
a = [" ", " ", " ", " ", " ", " ", " "]
b = [" ", " ", " ", " ", " ", " ", " "]
c = [" ", " ", " ", " ", " ", " ", " "]
d = [" ", " ", " ", " ", " ", " ", " "]
e = [" ", " ", " ", " ", " ", " ", " "]
f = [" ", " ", " ", " ", " ", " ", " "]
board = [a, b, c, d, e, f] # sets up the board
print("What is player 1's name?")
player1 = input()
print("What is player 2's name?")
player2 = input()
plays = 0
def print_board(): # prints the board
p = 0
for x in board:
for i in x:
print(i, end=" | ")
print()
p += 1
if p != 6:
print("- "*15)
else:
print()
def win(): # defines a boolean if one player has won
i = 0
k = 0
while i != 5:
while k != 6:
if board[i][k] == "o" or board[i][k] == "x":
if board[i+1][k] == board[i][k] == board[i+2][k] == board[i+3][k]:
return False
elif board[i][k] == board[i][k+1] == board[i][k+2] == board[i][k+3]:
return False
elif board[i][k] == board[i+1][k+1] == board[i+2][k+2] == board[i+3][k+3]:
return False
elif board[i][k] == board[i-1][k-1] == board[i-2][k-2] == board[i-3][k-3]:
return False
else:
return True
def play(): # defines the part you play.
if plays % 2 == 0:
player = "o"
else:
player = "x"
print_board()
x = int(input("Where would you like to put your chip?"))
i = 0
while i < 5:
if board[i][x] == " ":
if board[i+1][x] == "x" or board[i+1][x] == "o":
board[i][x] = player
print_board()
if win():
print(player+" won!")
play()
play() # runs the script
try this for your play loop - hopefully it will help you fix the win check also:
def play(): # defines the part you play.
plays = 0
while True:
if plays % 2 == 0:
player = "o"
else:
player = "x"
x = int(input("Where would you like to put your chip?"))
i = 0
for i in range(5):
if board[i][x] == " ":
if board[i+1][x] == "x" or board[i+1][x] == "o":
board[i][x] = player
else:
board[5][x] = player
print_board()
#if win():
# print(player+" won!")
# break
plays += 1
print_board()
play() # runs the script
i commented out the win check because it doesn't work yet

Categories

Resources