WARNING: I am almost completely new to python, so the errors here may be obvious - I will apologise in advance. Also, please try and keep answers easy to understand for an idiot! Thanks :)
I am trying to create a Connect 4 game in python, and I have almost everything working except I can't get it to swap turns between Noughts and Crosses. My main code is below:
def main():
global Xor0
winCheck = True
while winCheck == True:
humanTile = enterHumanTile()
print("The", Xor0, "player shall go first")
mainBoard= getNewBoard()
if Xor0 == "Crosses":
drawBoard(mainBoard)
move = getHumanMove(mainBoard)
makeMove(mainBoard, humanTile, move)
Xor0 = "Noughts"
if isWinner(mainBoard, tile):
drawBoard(mainBoard)
print("Crosses win")
winCheck = False
Xor0 = "Noughts"
else:
drawBoard(mainBoard)
move = getHumanMove(mainBoard)
makeMove(mainBoard, humanTile, move)
if isWinner(mainBoard, tile):
drawBoard(mainBoard)
print("Noughts win")
winCheck=False
Xor0 ="Crosses"
Xor0 is essentially turn, but I allocate it earlier using:
firstHTurn = random.randint(1,2)
if firstHTurn == 1:
Xor0 = 'Crosses'
tile = 'X'
else:
Xor0 = 'Noughts'
tile = '0'
which works fine, but I don't understand why the turn doesn't alternate at the end of each 'if' statement within main()
Full code:
import random
import sys
import copy
import time
def s():
print("")
print(" _________ __ ___________ ")
print(" \_ ___ \ ____ ____ ____ ____ _____/ |_ \_ _____/___ __ _________ ")
print(" / \ \/ / _ \ / \ / \_/ __ \_/ ___\ __\ | __)/ _ \| | \_ __ \ ")
print(" \ \___( <_> ) | \ | \ ___/\ \___| | | \( <_> ) | /| | \/")
print(" \______ /\____/|___| /___| /\___ >\___ >__| \___ / \____/|____/ |__| ")
print(" \/ \/ \/ \/ \/ \/ ")
print("")
print("")
playerMethod = input("Would you like to player a computer or a friend (C for Computer, F for Friends)")
if playerMethod== "F":
s()
method = "pvp"
print("Choose who will be Noughts and who will be Crosses")
s()
#time.sleep(3)
#firstHTurn = random.randint(1,2)
firstHTurn = 2
if firstHTurn == 1:
Xor0 = 'Crosses'
tile = 'X'
else:
Xor0 = 'Noughts'
tile = '0'
print("The", Xor0, "will play first")
s()
print("-----------------------------")
s()
elif playerMethod == "C":
method = "pve"
firstHTurn = random.randint(1,2)
if firstHTurn == 1:
print("The computer shall go first")
else:
print("You shall go first")
print("-----------------------------")
a=0
board = []
while a==0:
boardwidth = input("How wide should the board be?")
try:
float(boardwidth)
break
except ValueError:
pass
print("")
print("======================")
print("Please enter a number")
print("======================")
print("")
print("=== Board width set to", boardwidth, "===")
b=0
while b==0:
boardheight = input("How tall should the board be?")
try:
float(boardheight)
break
except ValueError:
pass
print("")
print("======================")
print("Please enter a number")
print("======================")
print("")
print("=== Board height set to", boardheight, "===")
s()
if method == "pvp":
print("=======================================")
print(" ==The", Xor0, "player shall go first== ")
print("=======================================")
if method == "pve" and firstHTurn == 1:
print("=================================")
print("== The Computer shall go first ==")
print("=================================")
if method == "pve" and firstHTurn == 2:
print("==============================")
print("===== You Shall go first =====")
print("==============================")
BHeight = int(boardheight)
BWidth = int(boardwidth)
def getNewBoard():
board = []
for x in range(BWidth):
board.append([' '] * BHeight)
return board
def drawBoard(board):
print()
print(' ', end='')
for x in range(1, BWidth + 1):
print(' %s ' % x, end='')
print()
print('+---+' + ('---+' * (BWidth - 1)))
for y in range(BHeight):
print('| |' + (' |' * (BWidth - 1)))
print('|', end='')
for x in range(BWidth):
print(' %s |' % board[x][y], end='')
print()
print('| |' + (' |' * (BWidth - 1)))
print('+---+' + ('---+' * (BWidth - 1)))
def enterHumanTile():
if tile == 'X':
return ['X', '0']
else:
return ['0', 'X']
def isValidMove(board, move):
if move < 0 or move >= (BWidth):
return False
if board[move][0] != ' ':
return False
return True
def getHumanMove(board):
while True:
print("Which column do you want to move on? (1-%s, or 'quit' to quit the game)" % (BWidth))
move = input()
if move.lower().startswith('q'):
sys.exit()
if not move.isdigit():
continue
move = int(move) - 1
if isValidMove (board, move):
return move
def makeMove(board, player, column):
for y in range(BHeight-1, -1, -1):
if board[column][y] ==' ':
board[column][y] =tile
return
def playAgain():
# This function returns True if the player wants to play again, otherwise it returns False.
print('Do you want to play again? (yes or no)')
return input().lower().startswith('y')
def isWinner(board, tile):
# check horizontal spaces
for y in range(BHeight):
for x in range(BWidth - 3):
if board[x][y] == tile and board[x+1][y] == tile and board[x+2][y] == tile and board[x+3][y] == tile:
return True
# check vertical spaces
for x in range(BWidth):
for y in range(BHeight - 3):
if board[x][y] == tile and board[x][y+1] == tile and board[x][y+2] == tile and board[x][y+3] == tile:
return True
# check / diagonal spaces
for x in range(BWidth - 3):
for y in range(3, BHeight):
if board[x][y] == tile and board[x+1][y-1] == tile and board[x+2][y-2] == tile and board[x+3][y-3] == tile:
return True
# check \ diagonal spaces
for x in range(BWidth - 3):
for y in range(BHeight - 3):
if board[x][y] == tile and board[x+1][y+1] == tile and board[x+2][y+2] == tile and board[x+3][y+3] == tile:
return True
return False
def main():
global Xor0
winCheck = True
while winCheck == True:
humanTile = enterHumanTile()
print("The", Xor0, "player shall go first")
mainBoard= getNewBoard()
while winCheck == True:
if Xor0 == "Crosses":
drawBoard(mainBoard)
move = getHumanMove(mainBoard)
makeMove(mainBoard, humanTile, move)
Xor0 = "Noughts"
if isWinner(mainBoard, tile):
drawBoard(mainBoard)
print("YOU WIN")
winCheck = False
Xor0 = "Noughts"
else:
drawBoard(mainBoard)
move = getHumanMove(mainBoard)
makeMove(mainBoard, humanTile, move)
if isWinner(mainBoard, tile):
drawBoard(mainBoard)
print("Noughts win")
winCheck=False
Xor0 ="Crosses"
main()
Related
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.
I'm making a game of tic tac toe and at the start and end it asks if you "would like to play a game y/n?", if you press yes it works perfectly and if you press no it says "Goodbye" and closes the program like its suppose too, however if you press "yes" just after you've played your first game it doesn't reprint the board, only gives you the one you already filled in. Is there a way to clear the board that anyone can help me with?
board = [" " for x in range(10)]
#insert letter into the board
def insertLetter(letter, pos):
board[pos] = letter
# Is that space avalible?
def spaceIsFree(pos):
return board[pos] == " "
# Prints the board
def printBoard(board):
#Board set up
print(" | |")
print(" " + board[1] + " | " + board[2] + " | " + board[3])
print(" | |")
print("-----------")
print(" | |")
print(" " + board[4] + " | " + board[5] + " | " + board[6])
print(" | |")
print("-----------")
print(" | |")
print(" " + board[7] + " | " + board[8] + " | " + board[9])
print(" | |")
def isWinner(bo, le):
#Look for winner!
return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top
(bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle
(bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom
(bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side
(bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle
(bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side
(bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal
(bo[9] == le and bo[5] == le and bo[1] == le)) # diagonal
def playerMove():
#Grabs player move, cheak for valid input
run = True
while run:
move = input("Please select a position place an \"X\" (1-9): ")
try:
move = int(move)
if move > 0 and move < 10:
if spaceIsFree(move):
run = False
insertLetter("X", move)
else:
print ("Sorry, this space is already taken!")
else:
print ("Please type a number within the range!")
except:
print("Please type a number!")
def compMove():
# Computers move
possibleMoves = [x for x, letter in enumerate(board) if letter == " " and x != 0]
move = 0
#check for a possible win
for let in ["O", "X"]:
for i in possibleMoves:
boardCopy = board[:]
boardCopy[i] = let
if isWinner (boardCopy, let):
move = i
return move
#check for open corners
cornersOpen = []
for i in possibleMoves:
if i in [1,3,7,9]:
cornersOpen.append(i)
if len(cornersOpen) > 0:
move = selectRandom(cornersOpen)
return move
#check for center move
if 5 in possibleMoves:
move = 5
return move
#check for open edges
edgesOpen = []
for i in possibleMoves:
if i in [2,4,6,8]:
edgesOpen.append(i)
if len(edgesOpen) > 0:
move = selectRandom(edgesOpen)
return move
def selectRandom(li):
# Selects random numbers
import random
ln = len(li)
r = random.randrange(0,ln)
return li[r]
def isBoardFull(board):
#See if the board is full
if board.count(" ") > 1:
return False
else:
return True
def main():
print("Welcom to Tic Tac Toe!")
print ()
printBoard(board)
while not (isBoardFull(board)):
# Do a player move,
# Check if O wins
if not (isWinner(board, "O")):
playerMove()
printBoard(board)
else:
print("Sorry, O's won this time!")
break
# Check If X wins
if not (isWinner(board, "X")):
move = compMove()
if move == 0:
print("Tie Game!")
else:
insertLetter("O", move)
print("Computer placed an O in position", move ,":")
printBoard(board)
else:
print("X's won this time! Good Job")
break
# No one wins - it's a tie
if isBoardFull(board):
print ("Tie Game!")
while True:
# Start/Play again
replay = input ("Would you like to play a game? y/n: ")
if replay == "no":
print ("Goodbye")
break
else:
print()
main()
You only create the board once at the top, then never reset it.
The easiest way to reset the state is simply to not save it globally. Reconfigure your code so board only exists in main, and it manually passed to every function that needs it. Then, when main exits, the board is destroyed and recreated each time that main runs.
To patch your existing code so it works though, I'd just create a function that creates a new board:
def new_board():
return [" " for x in range(10)]
Then, at the top of main, reset it:
def main():
global board
board = new_board()
print("Welcom to Tic Tac Toe!")
print ()
printBoard(board)
I can't recommend this in the long-term, but it's a quick fix.
board is defined in the global scope, so calling main again won't affect it, and you'll remain with the previous data. One option is to explicitly reinitialize it:
else:
board = [" " for x in range(10)]
print()
main()
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()
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")
I need help figuring out how to calculate the record for wins, losses, and ties. Right now, the code returns the string "loss" when the player loses. I want it to return 1, for one loss. Can anyone help? Here is the code I have so far.
# Tic Tac Toe
import random
def score():
wins = 0
losses = 0
ties = 0
def result(wins, losses, ties):
if result =='win':
wins += 1
if result == 'loss':
losses += 1
else:
ties += 1
def drawBoard(board):
# This function prints out the board that it was passed.
# "board" is a list of 10 strings representing the board (ignore index 0)
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
def inputPlayerLetter():
# Let's the player type which letter they want to be.
# Returns a list with the player's letter as the first item, and the computer's letter as the second.
letter = ''
while not (letter == 'X' or letter == 'O'):
print('Do you want to be X or O?')
letter = input().upper()
# the first element in the tuple is the player's letter, the second is the computer's letter.
if letter == 'X':
return ['X', 'O']
else:
return ['O', 'X']
def whoGoesFirst():
# Randomly choose the player who goes first.
if random.randint(0, 1) == 0:
return 'computer'
else:
return 'player'
def playAgain():
# This function returns True if the player wants to play again, otherwise it returns False.
print('Do you want to play again? (yes or no)')
return input().lower().startswith('y')
def makeMove(board, letter, move):
board[move] = letter
def isWinner(bo, le):
# Given a board and a player's letter, this function returns True if that player has won.
# We use bo instead of board and le instead of letter so we don't have to type as much.
return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top
(bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle
(bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom
(bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side
(bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle
(bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side
(bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal
(bo[9] == le and bo[5] == le and bo[1] == le)) # diagonal
def getBoardCopy(board):
# Make a duplicate of the board list and return it the duplicate.
dupeBoard = []
for i in board:
dupeBoard.append(i)
return dupeBoard
def isSpaceFree(board, move):
# Return true if the passed move is free on the passed board.
return board[move] == ' '
def getPlayerMove(board):
# Let the player type in his move.
move = ' '
while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board, int(move)):
print('What is your next move? (1-9)')
move = input()
return int(move)
def chooseRandomMoveFromList(board, movesList):
# Returns a valid move from the passed list on the passed board.
# Returns None if there is no valid move.
possibleMoves = []
for i in movesList:
if isSpaceFree(board, i):
possibleMoves.append(i)
if len(possibleMoves) != 0:
return random.choice(possibleMoves)
else:
return None
def getComputerMove(board, computerLetter):
# Given a board and the computer's letter, determine where to move and return that move.
if computerLetter == 'X':
playerLetter = 'O'
else:
playerLetter = 'X'
# Here is our algorithm for our Tic Tac Toe AI:
# First, check if we can win in the next move
for i in range(1, 10):
copy = getBoardCopy(board)
if isSpaceFree(copy, i):
makeMove(copy, computerLetter, i)
if isWinner(copy, computerLetter):
return i
# Check if the player could win on his next move, and block them.
for i in range(1, 10):
copy = getBoardCopy(board)
if isSpaceFree(copy, i):
makeMove(copy, playerLetter, i)
if isWinner(copy, playerLetter):
return i
# Try to take one of the corners, if they are free.
move = chooseRandomMoveFromList(board, [1, 3, 7, 9])
if move != None:
return move
# Try to take the center, if it is free.
if isSpaceFree(board, 5):
return 5
# Move on one of the sides.
return chooseRandomMoveFromList(board, [2, 4, 6, 8])
def isBoardFull(board):
# Return True if every space on the board has been taken. Otherwise return False.
for i in range(1, 10):
if isSpaceFree(board, i):
return False
return True
print('Welcome to Tic Tac Toe!')
while True:
# Reset the board
theBoard = [' '] * 10
playerLetter, computerLetter = inputPlayerLetter()
turn = whoGoesFirst()
print('The ' + turn + ' will go first.')
gameIsPlaying = True
while gameIsPlaying:
if turn == 'player':
# Player's turn.
drawBoard(theBoard)
move = getPlayerMove(theBoard)
makeMove(theBoard, playerLetter, move)
if isWinner(theBoard, playerLetter):
drawBoard(theBoard)
result = 'win'
print('Hooray! You have won the game!')
isWinner = True
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
result = 'tie'
print('The game is a tie!')
break
else:
turn = 'computer'
else:
# Computer's turn.
move = getComputerMove(theBoard, computerLetter)
makeMove(theBoard, computerLetter, move)
if isWinner(theBoard, computerLetter):
drawBoard(theBoard)
print('The computer has beaten you! You lose.')
result = 'loss'
isWinner = False
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
result = 'tie'
print('The game is a tie!')
break
else:
turn = 'player'
if not playAgain():
print(result)
break
Instead of doing result = 'win' you could set wins = 0 at the start and when resetting, and when the player wins just do wins += 1. Do the same for ties and losses and then you can extract the complete record from a function which takes wins,losses and ties as arguments.
Your functions score() and result(wins, loses, ties) are definitely not working good.
All variables in function are local variables and because of that this code will print 10 instead of 11:
def make_bigger(x):
x += 1
X = 10
make_bigger(X)
print(x)
Instead of using that functions you may need some function like this:
def pr_score(win, lose, tie):
print('Score:')
print('\twin:', win)
print('\tlose:', lose)
print('\ttie:', tie)
For win / lose / tie counting you need to add:
win = 0
lose = 0
tie = 0
before while True:.
You should also add win += 1 in if isWinner(theBoard, playerLetter): statement and tie += 1 in if isBoardFull(theBoard): statement.
Also code about computer turns should look like this:
if isBoardFull(theBoard):
drawBoard(theBoard)
result = 'tie'
print('The game is a tie!')
else:
# Computer's turn.
move = getComputerMove(theBoard, computerLetter)
makeMove(theBoard, computerLetter, move)
turn = 'player'
if isWinner(theBoard, computerLetter):
drawBoard(theBoard)
print('The computer has beaten you! You lose.')
result = 'loss'
lose += 1
isWinner = False
gameIsPlaying = False
if isBoardFull(theBoard):
drawBoard(theBoard)
result = 'tie'
print('The game is a tie!')
break
For printing result you should add pr_score(win, lose, tie) in if not playAgain():.
If you want ability for another round last break should be more indented.
Also if you add these lines in getPlayerMove(board) after move = input():
if move not in '1 2 3 4 5 6 7 8 9'.split(): #input is incorrect
print('Input is incorrect.\nPlease write nuber!')
elif not isSpaceFree(board, int(move)): #that place isn't free
print('That place is already taken.\nPlease take free place!')
and these lines before while True:
exampleBoard = [' ']
for x in range(1, 10):
exampleBoard.append(str(x))
drawBoard(exampleBoard)
it would be helpful for user.