My Tic tac toe code works fine except for a few issues. When marking a spot on the board the user can override and place their own mark in the same spot. Even though I have code that is supposed to fix this. Here is my code. Please fix any other errors as you see fit. I am almost failing a class on this.
board = [['-','-','-']
,['-','-','-']
,['-','-','-']]
player1 = 'X'
player2 = 'O'
win = False
turns = 0
player1= str(input("Whats ur name+"))
player2= str(input("Whats ur name"))
def checkwin(player):
for c in range(0,3):
if board[c][0] == player and board[c][1] == player and board[c][2] == player:
print "*********\n\n%s wins\n\n*********" % player
playerwin = True
return playerwin
elif board[0][c] == player and board[1][c] == player and board[2][c] == player:
print "*********\n\n%s wins\n\n*********" % player
playerwin = True
return playerwin
#check for diagonal win
elif board[0][0] == player and board[1][1] == player and board[2][2] == player:
print "*********\n\n%s wins\n\n*********" % player
playerwin = True
return playerwin
#check for diagonal win (right to left)
elif board[0][2] == player and board[1][1] == player and board[2][0] == player:
print "*********\n\n%s wins\n\n*********" % player
playerwin = True
return playerwin
else:
playerwin = False
return playerwin
def playerturn(player):
print "%s's turn" % player
turn = 1
while(turn):
print "Select column [1-3]: ",
col = int(raw_input()) - 1
print "Select row [1-3]: ",
row = int(raw_input()) - 1
if board[row][col] == "X" or board[row][col] == "O":
print "Already taken!"
else:
board[row][col] = player
turn = 0
def printboard():
print board[0]
print board[1]
print board[2]
printboard()
while(win == False):
playerturn(player1)
turns += 1
printboard()
if checkwin(player1) == True: break
if turns == 9:
print "This game is a draw!"
break
playerturn(player2)
turns += 1
printboard()
checkwin(player2)
if checkwin(player2) == True: break
Your problem is that you've put the player name in the array and checked whether there is an "X" or an "O" in the array. A simple solution would be changing the if condition to ... == player1 instead of "X".
If you do so, you also have to adjust the draw function.
board = [['-','-','-']
,['-','-','-']
, ['-','-','-']]
#player1 = 'X'
#player2 = 'O'
win = False
turns = 0
player1= raw_input("Whats ur name+")
player2= raw_input("Whats ur name")
def checkwin(player):
for c in range(0,3):
if board[c][0] == player and board[c][1] == player and board[c][2] == player:
print "*********\n\n%s wins\n\n*********" % player
playerwin = True
return playerwin
elif board[0][c] == player and board[1][c] == player and board[2][c] == player:
print "*********\n\n%s wins\n\n*********" % player
playerwin = True
return playerwin
#check for diagonal win
elif board[0][0] == player and board[1][1] == player and board[2][2] == player:
print "*********\n\n%s wins\n\n*********" % player
playerwin = True
return playerwin
#check for diagonal win (right to left)
elif board[0][2] == player and board[1][1] == player and board[2][0] == player:
print "*********\n\n%s wins\n\n*********" % player
playerwin = True
return playerwin
else:
playerwin = False
return playerwin
def playerturn(player):
print "%s's turn" % player
turn = 1
while(turn):
print "Select column [1-3]: ",
col = int(raw_input()) - 1
print "Select row [1-3]: ",
row = int(raw_input()) - 1
if board[row][col] == player1 or board[row][col] == player2:
print "Already taken!"
else:
board[row][col] = player
turn = 0
def printboard():
print ["X" if x == player1 else "O" if x == player2 else "-" for x in board[0]]
print ["X" if x == player1 else "O" if x == player2 else "-" for x in board[1]]
print ["X" if x == player1 else "O" if x == player2 else "-" for x in board[2]]
printboard()
while(win == False):
playerturn(player1)
turns += 1
printboard()
if checkwin(player1) == True: break
if turns == 9:
print "This game is a draw!"
break
playerturn(player2)
turns += 1
printboard()
checkwin(player2)
if checkwin(player2) == True: break
I also replaced the str(input()) to raw_input() to allow a string as name.
Related
So basically I am trying to build a Tic-Tac-Toe game with both single and multiplayer difficulty levels but I am stuck on what code should I write for player vs computer and I am stuck in a forever loop in the def play_game() function. I can't keep the previous stats of the game as well. I really need help with this.
# --------- Global Variables -----------
# Will hold our game board data
board = ["-", "-", "-",
"-", "-", "-",
"-", "-", "-"]
# Lets us know if the game is over yet
game_still_going = True
# Tells us who the winner is
winner = None
# Tells us who the current player is (X goes first)
current_player = "X"
# ------------- Functions ---------------
# Play a game of tic tac toe
def play_game():
# Show the initial game board
display_board()
game_on = True
while True:
print("1.Single Player")
print("2.Multiplayer")
print("3.Game Stats")
print("4.Quit")
input_1 = int(input("Please Select An Option"))
if input_1 == "3" :
print('reading database...')
read_log()
elif input_1 == "4" :
exit()
elif input_1 == "2" :
Player_1 = input("Enter First Player Name:")
Player_2 = input("Enter Second Player Name:")
display_board()
while game_on:
position = input("Choose a position from 1-9: ")
check_for_winner()
display_board()
# Loop until the game stops (winner or tie)
while game_still_going:
# Handle a turn
handle_turn(current_player)
# Check if the game is over
check_if_game_over()
# Flip to the other player
flip_player()
# Since the game is over, print the winner or tie
if winner == "X" or winner == "O":
print(winner + " won.")
elif winner == None:
print("Tie.")
# Display the game board to the screen
def display_board():
print("\n")
print(board[0] + " | " + board[1] + " | " + board[2] + " 1 | 2 | 3")
print(board[3] + " | " + board[4] + " | " + board[5] + " 4 | 5 | 6")
print(board[6] + " | " + board[7] + " | " + board[8] + " 7 | 8 | 9")
print("\n")
# Handle a turn for an arbitrary player
def handle_turn(player):
# Get position from player
print(player + "'s turn.")
position = input("Choose a position from 1-9: ")
# Whatever the user inputs, make sure it is a valid input, and the spot is open
valid = False
while not valid:
# Make sure the input is valid
while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
position = input("Choose a position from 1-9: ")
# Get correct index in our board list
position = int(position) - 1
# Then also make sure the spot is available on the board
if board[position] == "-":
valid = True
else:
print("You can't go there. Go again.")
# Put the game piece on the board
board[position] = player
# Show the game board
display_board()
# Check if the game is over
def check_if_game_over():
check_for_winner()
check_for_tie()
# Check to see if somebody has won
def check_for_winner():
# Set global variables
global winner
# Check if there was a winner anywhere
row_winner = check_rows()
column_winner = check_columns()
diagonal_winner = check_diagonals()
# Get the winner
if row_winner:
winner = row_winner
elif column_winner:
winner = column_winner
elif diagonal_winner:
winner = diagonal_winner
else:
winner = None
# Check the rows for a win
def check_rows():
# Set global variables
global game_still_going
# Check if any of the rows have all the same value (and is not empty)
row_1 = board[0] == board[1] == board[2] != "-"
row_2 = board[3] == board[4] == board[5] != "-"
row_3 = board[6] == board[7] == board[8] != "-"
# If any row does have a match, flag that there is a win
if row_1 or row_2 or row_3:
game_still_going = False
# Return the winner
if row_1:
return board[0]
elif row_2:
return board[3]
elif row_3:
return board[6]
# Or return None if there was no winner
else:
return None
# Check the columns for a win
def check_columns():
# Set global variables
global game_still_going
# Check if any of the columns have all the same value (and is not empty)
column_1 = board[0] == board[3] == board[6] != "-"
column_2 = board[1] == board[4] == board[7] != "-"
column_3 = board[2] == board[5] == board[8] != "-"
# If any row does have a match, flag that there is a win
if column_1 or column_2 or column_3:
game_still_going = False
# Return the winner
if column_1:
return board[0]
elif column_2:
return board[1]
elif column_3:
return board[2]
# Or return None if there was no winner
else:
return None
# Check the diagonals for a win
def check_diagonals():
# Set global variables
global game_still_going
# Check if any of the columns have all the same value (and is not empty)
diagonal_1 = board[0] == board[4] == board[8] != "-"
diagonal_2 = board[2] == board[4] == board[6] != "-"
# If any row does have a match, flag that there is a win
if diagonal_1 or diagonal_2:
game_still_going = False
# Return the winner
if diagonal_1:
return board[0]
elif diagonal_2:
return board[2]
# Or return None if there was no winner
else:
return None
# Check if there is a tie
def check_for_tie():
# Set global variables
global game_still_going
# If board is full
if "-" not in board:
game_still_going = False
return True
# Else there is no tie
else:
return False
# Flip the current player from X to O, or O to X
def flip_player():
# Global variables we need
global current_player
# If the current player was X, make it O
if current_player == "X":
current_player = "O"
# Or if the current player was O, make it X
elif current_player == "O":
current_player = "X"
def read_log():
log = open('log.txt', 'r')
log.seek(0)
print('\n\n')
print(log.read(),'\n\n')
# ------------ Start Execution -------------
# Play a game of tic tac toe
play_game()
If I understood correctly You can do it like this:
Define functions:
handle_player_move()
handle_computer_move()
as names suggests when you call the function either human player or computer will make a move (make sure that it's certain or add some Errorcodes/Exceptions when player do something unexpected and you want to end program)
Define function:
game_is_over() # returns True if it's the end of game False other wise
Then Your game is just:
Human vs Human:
whos_move = 0 # number of player ( 0 or 1 )
while not game_is_over():
if whos_move == 0:
handle_player_move(player1)
if whos_move == 1:
handle_player_move(player2)
whos_move = (whos_move + 1) % 2
Quite similarly Human vs Bot:
whos_move = 0 # number of player ( 0 or 1 )
while not game_is_over():
if whos_move == 0:
handle_player_move(player1)
if whos_move == 1:
handle_computer_move(player2)
whos_move = (whos_move + 1) % 2
Instead of this you can also check for end of game with your function, and do:
whos_move = 0 # number of player ( 0 or 1 )
while game_still_going:
if whos_move == 0:
handle_player_move(player1)
if whos_move == 1:
handle_computer_move(player2)
whos_move = (whos_move + 1) % 2
check_if_game_over()
if statement: # your ending statement here
game_is_still_going = False
Your method with flip_player() is also good I just put if statements to both so that they are familiar in truth if you would are able to distinguish in handle_turn() between bot and human player you can do it for both cases ;)
As implementing computer moves can be hard here are some tips:
Easiest way you can just randomly choose number between 1 and 9 check if it's unoccupied if it's free computer makes move there if it is not you pick again. Maybe it sounds like being potentially endless loop but statisticly computer shouldn't have any problems with making a move.
You can also create list of free squares and then randomly choose an index (probably better way)
You can also try to add some logic f.e. if there are two in a row block third square.
too choose random integer from given interval you can use:
import random
random.randint(1,9) # choose integer x such that: 1 <= x <= 9
Of course you can and even maybe should use your own function names (name them as you wish!)
Hope that helps, good luck!
I am new and I have created a tic tac toe game in python I worked out the logic but the code is not behaving as expected I have tried to debug it but can't find the bug.
I am new to python and taking course on udemy in the course I was asked to write a tic tac toe game by myself at first. I have figured out a not so good logic but it will do the job. I just can't figure out why win_check function is not working properly. Is it win_check function or something else? What are some suggestion for improving my code?
Sorry for not giving comments in code I just wanted to complete it first and run it successfully.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 27 20:11:38 2019
#author: sandeep
"""
from os import name,system
from time import sleep
from random import randint
def game_board(turns):
print(turns[6],"|",turns[7],"|",turns[8])
print("--|---|---")
print(turns[3],"|",turns[4],"|",turns[5])
print("--|---|---")
print(turns[0],"|",turns[1],"|",turns[2])
def check_input(player1,player2):
if (player1 == 'X' or player1 == 'O') and (player2 == 'X' or player2 == 'O'):
return True
else:
print("Please choose between X and O")
global initial_player_value
initial_player_value = take_input()
return False
def take_input():
player1 = input("Do you want 'X' or 'O'?\n")
if player1 == 'X':
player2 = 'O'
else:
player2 = 'X'
return (player1,player2)
def clear():
if name == 'nt':
_ = system('cls')
else:
_ = system('clear')
def player_turn(initial_player_value0,initial_player_value1):
clear()
global turns
game_board(turns)
print(f"Player {initial_player_value0} turn")
print("Enter position")
player1_input =input()
turns.pop(int(player1_input)-1)
turns.insert(int(player1_input)-1,initial_player_value0)
clear()
game_board(turns)
print(f"Player {initial_player_value1} turn")
print("Enter position")
player2_input = input()
turns.pop(int(player2_input)-1)
turns.insert(int(player2_input)-1,initial_player_value1)
clear()
game_board(turns)
def win_check(check,initial_player_value3,initial_player_value4):
# print(check)
global game_status
if initial_player_value3 == 'X':
if ((['X','X','X'] == check[:3]) or (['X','X','X'] == check[3:6]) or (['X','X','X'] == check[6:])):
game_status = "Player X wins"
elif ((['X','X','X'] == check[::3]) or (['X','X','X'] == check[1::3]) or (['X','X','X'] == check[2::3])):
game_status = "Player X wins"
elif ((['X','X','X'] == check[::4]) or (['X','X','X'] == check[2:7:2])):
game_status = "Player X wins"
else:
game_status = "_"
else:
if ((['O','O','O'] == check[:3]) or (['O','O','O'] == check[3:6]) or (['O','O','O'] == check[6:])):
game_status = "Player O wins"
elif ((['O','O','O'] == check[::3]) or (['O','O','O'] == check[1::3]) or (['O','O','O'] == check[2::3])):
game_status = "Player O wins"
elif ((['O','O','O'] == check[::4]) or (['O','O','O'] == check[2:7:2])):
game_status = "Player O wins"
else:
game_status = "_"
if initial_player_value4 == 'O':
if ((['O','O','O'] == check[:3]) or (['O','O','O'] == check[3:6]) or (['O','O','O'] == check[6:])):
game_status = "Player O wins"
elif ((['O','O','O'] == check[::3]) or (['O','O','O'] == check[1::3]) or (['O','O','O'] == check[2::3])):
game_status = "Player O wins"
elif ((['O','O','O'] == check[::4]) or (['O','O','O'] == check[2:7:2])):
game_status = "Player O wins"
else:
game_status = "_"
else :
if ((['X','X','X'] == check[:3]) or (['X','X','X'] == check[3:6]) or (['X','X','X'] == check[6:])):
game_status = "Player X wins"
elif ((['X','X','X'] == check[::3]) or (['X','X','X'] == check[1::3]) or (['X','X','X'] == check[2::3])):
game_status = "Player X wins"
elif ((['X','X','X'] == check[::4]) or (['X','X','X'] == check[2:7:2])):
game_status = "Player X wins"
else:
game_status = "_"
draw_check = ''.join(str(x) for x in check)
print(draw_check)
#sleep(5)
if draw_check.isalpha():
game_status ="Game draws"
else:
game_status= "_"
#def welcome():
print("Welcome to the tic tac toe game\n")
initial_player_value = take_input()
check = check_input(initial_player_value[0],initial_player_value[1])
while check is False:
check = check_input(initial_player_value[0],initial_player_value[1])
print(f"Player 1 is {initial_player_value[0]} and Player 2 is {initial_player_value[1]}\nLet's start the game" )
turns = [1,2,3,4,5,6,7,8,9]
sleep(2)
clear()
game_board(turns)
game_status = '_'
decide_first = randint(1,2)
replay = 'yes'
while replay == "yes":
#global game_status
if decide_first == 1:
player_turn(initial_player_value[0],initial_player_value[1])
game_board(turns)
win_check(turns,initial_player_value[0],initial_player_value[1])
else:
player_turn(initial_player_value[1],initial_player_value[0])
game_board(turns)
win_check(turns,initial_player_value[0],initial_player_value[1])
#win_check(turns,tuple(initial_player_value))
if game_status != '_':
print(game_status)
replay = input("Do you want to play again?\n")
turns = [1,2,3,4,5,6,7,8,9]
No error while running the code.
the problem you're facing is in win_check.
win_check does the following steps:
it checks if the first player wins, and sets the variable game_status to either "Player X wins", or "Player Y wins", or "_"
it checks if the second player wins, and sets the variable game_status to either "Player X wins", or "Player Y wins", or "_"
it checks if the a draw happens and sets the variable game_status to either "game draws" or "_"
after each step it deletes the result of the last step.
It would be more readable and functionally correct if you use a single if en elif chain to manage the control flow.
I would also move the checking whether a player has won to its own function called has_won, this would improve readability and reduce code duplication.
def win_check(board, player_1, player_2):
global game_status
if has_won(board, player_1):
game_status = "Player " + player_1 + " has won"
elif has_won(board, player_2):
game_status = "Player " + player_2 + " has won"
elif is_draw(board):
game_status = "Game draws"
else:
game_status = "_"
I want the computer playing with the player with until one of them scores 10 points:
from graphics import *
board=[[0,0,0],[0,0,0],[0,0,0]]#as bourd
window=GraphWin("Tic Tac Toe",700,700)
L0=Line(Point(250,50),Point(250,650)).draw(window)
L1=Line(Point(450,50),Point(450,650)).draw(window)
L2=Line(Point(50,250),Point(650,250))
L2.draw(window)
L3=Line(Point(50,450),Point(650,450))
L3.draw(window)
xTurn=True
num=0
while num<9:
b=window.getMouse()
pa,pb=int((b.x-50)/200)+1,int((b.y-50)/200)+1
if board[pb-1][pa-1]==0:
num+=1
if xTurn:
tex="X"
xTurn=False
else:
tex="O"
xTurn=True
h=Text(Point(pa*150+50*(pa-1),pb*150+50*(pb-1)),tex).draw(window)
h.setSize(36)
if xTurn:
h.setFill("blue")
board[pb-1][pa-1]=1
else:
h.setFill("red")
board[pb-1][pa-1]=2
if num>4:
if (board[0][0]==1 and board[0][1]==1 and board[0][2]==1) or(board[1][0]==1 and board[1][1]==1 and board[1][2]==1) or(board[2][0]==1 and board[2][1]==1 and board[2][2]==1):
print(" O is winner")
break
elif (board[0][0]==2 and board[0][1]==2 and board[0][2]==2) or(board[1][0]==2 and board[1][1]==2 and board[1][2]==2) or (board[2][0]==2 and board[2][1]==2 and board[2][2]==2):
print(" X is winner")
break
elif (board[0][0]==2 and board[1][0]==2 and board[2][0]==2) or(board[0][1]==2 and board[1][1]==2 and board[2][1]==2) or (board[0][2]==2 and board[1][2]==2 and board[2][2]==2):
print(" X is winner")
break
elif (board[0][0]==1 and board[1][0]==1 and board[2][0]==1) or(board[0][1]==1 and board[1][1]==1 and board[2][1]==1) or (board[0][2]==1 and board[1][2]==1 and board[2][2]==1):
print(" O is winner")
break
elif (board[0][0]==1 and board[1][1]==1 and board[2][2]==1) or(board[0][2]==1 and board[1][1]==1 and board[2][0]==1):
print(" O is winner")
break
elif (board[0][0]==2 and board[1][1]==2 and board[2][2]==2) or(board[0][2]==2 and board[1][1]==2 and board[2][0]==2):
print(" X is winner")
break
if num>=9:
print("There is no winner!")
I took your program apart and put it back together again to streamline it and allow it to play ten games before quitting. It prints the results of the ten games as it exits. This isn't exactly what you are after, but I believe gives you the tools you need to do what you want:
from graphics import *
from time import sleep
PLAYERS = ['Draw', 'O', 'X']
DRAW = PLAYERS.index('Draw')
COLORS = ['black', 'blue', 'red']
EMPTY = 0
window = GraphWin("Tic Tac Toe", 700, 700)
Line(Point(250, 50), Point(250, 650)).draw(window)
Line(Point(450, 50), Point(450, 650)).draw(window)
Line(Point(50, 250), Point(650, 250)).draw(window)
Line(Point(50, 450), Point(650, 450)).draw(window)
turn = PLAYERS.index('X')
scores = [0] * len(PLAYERS)
tokens = []
while sum(scores) < 10:
for token in tokens:
token.undraw()
board = [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]]
squares_played = 0
while squares_played < 9:
point = window.getMouse()
x, y = int((point.x - 50) / 200), int((point.y - 50) / 200)
if board[y][x] == EMPTY:
squares_played += 1
board[y][x] = turn
text = PLAYERS[turn]
token = Text(Point(200 * x + 150, 200 * y + 150), text)
token.setSize(36)
token.setFill(COLORS[turn])
token.draw(window)
tokens.append(token)
turn = len(PLAYERS) - turn
if squares_played > 4:
if EMPTY != board[0][0] == board[0][1] == board[0][2]:
print("{} is winner".format(PLAYERS[board[0][0]]))
scores[turn] += 1
break
elif EMPTY != board[1][0] == board[1][1] == board[1][2]:
print("{} is winner".format(PLAYERS[board[1][1]]))
scores[turn] += 1
break
elif EMPTY != board[2][0] == board[2][1] == board[2][2]:
print("{} is winner".format(PLAYERS[board[2][2]]))
scores[turn] += 1
break
elif EMPTY != board[0][0] == board[1][0] == board[2][0]:
print("{} is winner".format(PLAYERS[board[0][0]]))
scores[turn] += 1
break
elif EMPTY != board[0][1] == board[1][1] == board[2][1]:
print("{} is winner".format(PLAYERS[board[1][1]]))
scores[turn] += 1
break
elif EMPTY != board[0][2] == board[1][2] == board[2][2]:
print("{} is winner".format(PLAYERS[board[2][2]]))
scores[turn] += 1
break
elif EMPTY != board[0][0] == board[1][1] == board[2][2]:
print("{} is winner".format(PLAYERS[board[1][1]]))
scores[turn] += 1
break
elif EMPTY != board[0][2] == board[1][1] == board[2][0]:
print("{} is winner".format(PLAYERS[board[1][1]]))
scores[turn] += 1
break
if squares_played >= 9:
print("There is no winner!")
scores[DRAW] += 1
sleep(2)
for index, player in enumerate(PLAYERS):
print("{}: {}".format(player, scores[index]))
My rework relies on some parallel arrays, which is better than no arrays, but should evolve to a real data structure.
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 building a ticTacToe game and I have everything figured out but how to check for three in a row or three down a column. I think there is something simple missing, but I could have it wrong entirely. Here is the code:
def isWin(gameBoard):
#check for row matches
for row in range(0, 3):
if gameBoard[row][0] == gameBoard[row][1] and gameBoard[row][0] == gameBoard[row][2]:
return True
Maybe you can consider to use set? Something like:
def isWin(gameBoard):
for row in gameBoard:
if len(set(row)) == 1:
return true
I think I figured it out!
def isWin(gameBoard):
#check for row and column matches
for row in range(0, 3):
if gameBoard[row][0] == "X" and gameBoard[row][1] == "X" and gameBoard[row][2] == "X":
return True
if gameBoard[row][0] == "O" and gameBoard[row][1] == "O" and gameBoard[row][2] == "O":
return True
if gameBoard[0][row] == "X" and gameBoard[1][row] == "X" and gameBoard[2][row] == "X":
return True
if gameBoard[0][row] == "O" and gameBoard[1][row] == "O" and gameBoard[2][row] == "O":
return True
So I figured it out and am super excited! I am new to coding so thank you all for the support! Please let me know if you think it could be more efficient. :)
Here is the full code:
import sys
def main():
gameBoard = [[" ", " ", " "],
[" ", " ", " "],
[" ", " ", " "]]
printBoard(gameBoard)
while True:
#
playerXturn(gameBoard)
printBoard(gameBoard)
if isWin(gameBoard):
print("Player X wins!")
sys.exit()
elif boardFull(gameBoard):
print("Draw. No more plays left.")
sys.exit()
playerOturn(gameBoard)
printBoard(gameBoard)
if isWin(gameBoard):
print("Player O wins!")
sys.exit()
elif boardFull(gameBoard):
print("Draw. No more plays left.")
sys.exit()
def printBoard(gameBoard):
print("---------")
print(gameBoard[0][0], "|", gameBoard[0][1], "|", gameBoard[0][2])
print("---------")
print(gameBoard[1][0], "|", gameBoard[1][1], "|", gameBoard[1][2])
print("---------")
print(gameBoard[2][0], "|", gameBoard[2][1], "|", gameBoard[2][2])
print("---------")
def playerXturn(gameBoard):
playerXrow = int(input("Enter a row (0, 1, or 2) for player X: "))
playerXcolumn = int(input("Enter a column (0, 1, or 2) for player X: "))
while gameBoard[playerXrow][playerXcolumn] == "X" or gameBoard[playerXrow][playerXcolumn] == "O":
print("This spot is already taken. Try again:")
playerXrow = int(input("Enter a row (0, 1, or 2) for player X: "))
playerXcolumn = int(input("Enter a column (0, 1, or 2) for player X: "))
gameBoard[playerXrow][playerXcolumn] = "X"
return gameBoard
def playerOturn(gameBoard):
playerOrow = int(input("Enter a row (0, 1, or 2) for player O: "))
playerOcolumn = int(input("Enter a column (0, 1, or 2) for player O: "))
while gameBoard[playerOrow][playerOcolumn] == "X" or gameBoard[playerOrow][playerOcolumn] == "O":
print("This spot is already taken. Try again:")
playerOrow = int(input("Enter a row (0, 1, or 2) for player O: "))
playerOcolumn = int(input("Enter a column (0, 1, or 2) for player O: "))
gameBoard[playerOrow][playerOcolumn] = "O"
return gameBoard
#check for empty spaces on the board
def boardFull(gameBoard):
for i in range(3):
for j in range(3):
if gameBoard[i][j] == " ":
return False
return True
#check for 3 in a row
def isWin(gameBoard):
#check for row matches
for row in range(0, 3):
if gameBoard[row][0] == "X" and gameBoard[row][1] == "X" and gameBoard[row][2] == "X":
return True
if gameBoard[row][0] == "O" and gameBoard[row][1] == "O" and gameBoard[row][2] == "O":
return True
if gameBoard[0][row] == "X" and gameBoard[1][row] == "X" and gameBoard[2][row] == "X":
return True
if gameBoard[0][row] == "O" and gameBoard[1][row] == "O" and gameBoard[2][row] == "O":
return True
#check for diagonal matches
if gameBoard[1][1] != " " and gameBoard[0][0] == gameBoard [1][1] and gameBoard[0][0] == gameBoard [2][2]:
return True
if gameBoard[1][1] != " " and gameBoard[0][2] == gameBoard [1][1] and gameBoard[0][2] == gameBoard [2][0]:
return True
return False
main()