def check_over(mark):
######################################
#This checks for a win################
######################################
if board[1] == mark and board[2] == mark and board[3] == mark
or board[4] == mark and board[5] == mark and board[6] == mark
or board[7] == mark and board[8] == mark and board[9] == mark
or board[1] == mark and board[4] == mark and board[7] == mark
or board[2] == mark and board[5] == mark and board[8] == mark
or board[3] == mark and board[6] == mark and board[9] == mark
or board[1] == mark and board[5] == mark and board[9] == mark
or board[3] == mark and board[5] == mark and board[7] == mark:
print(f'{mark} won!')
This code yields the following error when I try to call it:
if board[1] == mark and board[2] == mark and board[3] == mark
^
SyntaxError: invalid syntax
This function is meant to check for a win in a tic-tac-toe game based on a python list named board.
Where is my problem?
EDIT: While trying to fix the code I got another error, still need help!
def check_over(mark):
######################################
#This checks for a win################
######################################
if board[1] == mark and board[2] == mark and board[3] == mark or board[4] == mark and board[5] == mark and board[6] == mark or board[7] == mark and board[8] == mark and board[9] == mark or board[1] == mark and board[4] == mark and board[7] == mark or board[2] == mark and board[5] == mark and board[8] == mark or board[3] == mark and board[6] == mark and board[9] == mark or board[1] == mark and board[5] == mark and board[9] == mark or board[3] == mark and board[5] == mark and board[7] == mark:
print(f'{mark} won!')
return True
elif " " not in board:
###############################
#This checks for tie###########
###############################
print('The game ended in a tie!')
return True
It gives me the following error:
def check_over(mark):
^
IndentationError: expected an indented block
Your SyntaxError is occuring because you're not using \ characters to break across multiple lines
def check_over(mark):
######################################
#This checks for a win################
######################################
if board[1] == mark and board[2] == mark and board[3] == mark \
or board[4] == mark and board[5] == mark and board[6] == mark \
or board[7] == mark and board[8] == mark and board[9] == mark \
or board[1] == mark and board[4] == mark and board[7] == mark \
or board[2] == mark and board[5] == mark and board[8] == mark \
or board[3] == mark and board[6] == mark and board[9] == mark \
or board[1] == mark and board[5] == mark and board[9] == mark \
or board[3] == mark and board[5] == mark and board[7] == mark:
print(f'{mark} won!')
You can not have have new lines in the middle of your line in python.
Try the following:
if board[1] == mark and board[2] == mark and board[3] == mark or board[4] == mark and board[5] == mark and board[6] == mark or board[7] == mark and board[8] == mark and board[9] == mark or board[1] == mark and board[4] == mark and board[7] == mark or board[2] == mark and board[5] == mark and board[8] == mark or board[3] == mark and board[6] == mark and board[9] == mark or board[1] == mark and board[5] == mark and board[9] == mark or board[3] == mark and board[5] == mark and board[7] == mark:
print(f'{mark} won!')
Related
I recently tried creating a simple Tic Tac Toe AI with minimax (with help from YouTube), but I can't get it to work. The algorithm just spits out the first value it checks instead of going through all of them and giving the best one.
I tried copying the code from the YouTube video but it still doesn't work, can someone tell me what's wrong?
import math
import random
print()
board = {1: ' ', 2: ' ', 3: ' ',
4: ' ', 5: ' ', 6: ' ',
7: ' ', 8: ' ', 9: ' '}
computerLetter = 'X'
playerLetter = 'O'
def print_board(board=board):
for i in range(1, 8, 3):
print('|' + board[i] + '|' + board[i + 1] + '|' + board[i + 2] + '|')
if i < 7:
print('-' * 13)
print()
def space_is_free(position):
if board[position] == ' ':
return True
else:
return False
def free_spaces(board=board):
freeSpaces = 0
for key in board.keys():
if key == ' ':
freeSpaces += 1
return freeSpaces
def make_move(letter, position):
if space_is_free(position):
board[position] = ' ' + letter + ' '
print_board(board)
if check_for_win(board):
if letter == 'O':
print("You win!!")
exit()
else:
print("The computer wins. Better luck next time!")
exit()
elif check_for_tie(board):
print("It's a tie! Well played.")
exit()
else:
print("Invalid choice.")
position = int(input("Enter new position: "))
make_move(letter, position)
def check_for_win(board=board):
if board[1] == board[2] == board[3] != ' ' or board[4] == board[5] == board[6] != ' ' or board[7] == board[8] \
== board[9] != ' ' or board[1] == board[4] == board[7] != ' ' or board[2] == board[5] == board[6] != \
' ' or board[3] == board[6] == board[9] != ' ' or board[1] == board[5] == board[9] != ' ' or board[3]\
== board[5] == board[7] != ' ':
return True
else:
return False
def check_for_win_letter(letter):
if board[1] == board[2] == board[3] == ' ' + letter + ' ' or board[4] == board[5] == board[6] == ' ' + letter + ' '\
or board[7] == board[8] == board[9] == ' ' + letter + ' ' or board[1] == board[4] or board[7] == ' ' +\
letter + ' ' or board[2] == board[5] or board[6] == ' ' + letter + ' ' or board[3] == board[6] or board[9]\
== ' ' + letter + ' ' or board[1] == board[5] == board[9] == ' ' + letter + ' ' or board[3] == board[5] ==\
board[7] == ' ' + letter + ' ':
return True
else:
return False
def check_for_tie(board=board):
for key in board.keys():
if board[key] == ' ':
return False
else:
return True
def player_move(playerLetter='O'):
if free_spaces(board) >= 9:
print_board(board)
position = int(input("Enter position (1-9): "))
make_move(playerLetter, position)
def computer_move(computerLetter='X'):
if free_spaces(board) == 9:
make_move(computerLetter, 5)
else:
bestScore = -math.inf
bestPosition = 0
for key in board.keys():
if space_is_free(key):
board[key] = ' ' + computerLetter + ' '
score = minimax(board, 0, False)
board[key] = ' '
if score > bestScore:
bestScore = score
bestPosition = key
make_move(computerLetter, bestPosition)
print(f"Computer moves to {bestPosition}.")
def minimax(board, depth, isMaximising):
if check_for_win_letter('X'):
return 1 * (free_spaces(board) + 1)
elif check_for_win_letter('O'):
return -1 * (free_spaces(board) + 1)
elif check_for_tie(board):
return 0
if isMaximising:
bestScore = -math.inf
for key in board.keys():
if space_is_free(key):
board[key] = ' ' + computerLetter + ' '
score = minimax(board, depth + 1, False)
board[key] = ' '
bestScore = max(score, bestScore)
return bestScore
else:
bestScore = math.inf
for key in board.keys():
if space_is_free(key):
board[key] = ' ' + playerLetter + ' '
score = minimax(board, depth + 1, True)
board[key] = ' '
bestScore = min(score, bestScore)
return bestScore
while not check_for_win(board):
computer_move('X')
player_move('O')
# gameState = input("Would you like to play again? (y/n)")
#
# if gameState.lower() == 'y':
# main()
# elif gameState.lower() == 'n':
# exit()
# else:
# print("Invalid choice.")
I tried changing the computer and player letters, and whether the computer was maximising or minimising but it didn't work.
I think I have found what is wrong with your code, in the minmax function the first if, elif, else statement always ends with a return statement.
def minimax(board, depth, isMaximising):
if check_for_win_letter('X'):
return 1 * (free_spaces(board) + 1)
elif check_for_win_letter('O'):
return -1 * (free_spaces(board) + 1)
elif check_for_tie(board):
return 0
The else statement is the reason it is failing.
When a return statement is called, it ends the function returning the variable stated, in this case it will always be a number between -9 and 9, and does not run the next block of code, ruining the computer's process to find the best/worst place to play. the else statement means that even if the previous statements are false, it will always return zero, ending the function and halting the process of the next block of code.
I hope this helps! :)
Okay I figured out the problem, it was actually a bunch of logical errors in the functions which were checking for a winner and the winner letter, a few typos per say.
Error 1:
def check_for_win(board=board):
if board[1] == board[2] == board[3] != ' ' or board[4] == board[5] == board[6] != ' ' or board[7] == board[8] \
== board[9] != ' ' or board[1] == board[4] == board[7] != ' ' or ****board[2] == board[5] == board[6]**** != \ # board[6] should be board[8]
' ' or board[3] == board[6] == board[9] != ' ' or board[1] == board[5] == board[9] != ' ' or board[3]\
== board[5] == board[7] != ' ':
return True
Error 2:
def check_for_win_letter(letter):
if board[1] == board[2] == board[3] == ' ' + letter + ' ' or board[4] == board[5] == board[6] == ' ' + letter + ' '\
or board[7] == board[8] == board[9] == ' ' + letter + ' ' or board[1] == board[4] ****or board[7]**** == ' ' +\
letter + ' ' or board[2] == board[5] ****or board[6]**** == ' ' + letter + ' ' or board[3] == board[6] ****or board[9]****\
== ' ' + letter + ' ' or board[1] == board[5] == board[9] == ' ' + letter + ' ' or board[3] == board[5] ==\
board[7] == ' ' + letter + ' ':
return True
The statements within asterisks (*) are the errors, the or statements should be == and the board[6] should again be board[8].
I recently took it upon myself to try and code a TicTacToe board in order to test my understanding of the concepts I learned online. However, I encountered a few problems within my code and do not understand why it doesn't work as intended.
While attempting to get the code to print a winner, my code does not work as intended and does not choose a winner based on the values I have inputted. Sometimes the code runs and a winner is detected two turns after someone has already won, and sometimes it exits the code without a 5th move having even been played.
Below is the code I worked on. It includes insurance that you cannot input an X or an O in a position that has already been taken up and prints the Xs and Os where the players choose. I believe that the errors take place somewhere in the row(), column(), and diagonal() parts of the code.
player = 0
player_add = 1
winner = None
already_taken = []
turns_taken = 0
board = [
"-", "-", "-",
"-", "-", "-",
"-", "-", "-"
]
def handle_turn(turn, turn_add):
while turn % 2 == 0:
position = int(input("Choose a position from 1-9 to add an \"X\": ")) - 1
already_taken.append(position)
board[position] = "X"
turn += turn_add
display_board()
while already_taken.count(position) > 1:
print("Position already taken.")
board[position] = "O"
display_board()
already_taken.remove(position)
turn += turn_add
while turn % 2 == 1:
position = int(input("Choose a position from 1-9 to add an \"O\": ")) - 1
already_taken.append(position)
board[position] = "O"
turn += turn_add
display_board()
while already_taken.count(position) > 1:
print("Position already taken.")
board[position] = "X"
display_board()
already_taken.remove(position)
turn += turn_add
def display_board():
print(board[0] + "|" + board[1] + "|" + board[2])
print(board[3] + "|" + board[4] + "|" + board[5])
print(board[6] + "|" + board[7] + "|" + board[8])
def play_game():
display_board()
handle_turn(player, player_add)
def rows():
global running
if board[0] and board[1] and board[2] == board[0] and board[0] != "-":
running = False
return board[0]
if board[3] and board[4] and board[5] == board[3] and board[3] != "-":
running = False
return board[3]
if board[6] and board[7] and board[8] == board[6] and board[6] != "-":
running = False
return board[6]
return
def columns():
global running
if board[0] and board[3] and board[6] == board[0] and board[0] != "-":
running = False
return board[0]
if board[1] and board[4] and board[7] == board[1] and board[1] != "-":
running = False
return board[3]
if board[2] and board[5] and board[8] == board[2] and board[2] != "-":
running = False
return board[6]
return
def diagonals():
global running
if board[0] and board[4] and board[8] == board[0] and board[0] != "-":
running = False
return board[0]
if board[2] and board[4] and board[6] == board[2] and board[2] != "-":
running = False
return board[3]
return
def check_if_win():
global winner
# Rows
row_winner = rows()
# Columns
column_winner = columns()
# Diagonals
diagonal_winner = diagonals()
if row_winner:
winner = row_winner
elif column_winner:
winner = column_winner
elif diagonal_winner:
winner = diagonal_winner
else:
winner = None
def check_if_game_over():
check_if_win()
running = True
while running:
play_game()
check_if_game_over()
if winner == "X":
print("Player " + str(winner) + " has won!")
elif winner == "O":
print("Player " + str(winner) + " has won!")
elif winner is None:
print("Whoops! Looks like you both loose.")
'''
You almost got it right, but you made a typo:
if board[0] and board[3] and board[6] == board[0] and board[0] != "-":
This should be:
if board[0] == board[3] and board[6] == board[0] and board[0] != "-":
I would say, if you fix all of those. It may work - at least a little bit better.
Hope this taught you not to copy-paste code too much, as you can easily copy the same mistake over and over again.
So, what happened? Well, if you have if(board[0] and board[3]) like you did, it checks if board[0] evaluates to true and the same for board[3]. The way true and false is implemented is that false = 0, and true is just the opposite of false: true = !false. So, what you were checking for was pretty much, "is board[0] zero?" No, so that is true. So, no wonder that you were confused.
I am currently learning python and trying to build a tic tac toe game. I wrote a program to prevent the user repeating the same input but when I repeat the same number two times, the program starts looping continuously without stopping. Could someone give me advice on how to rectify this issue? see below the code:
from tabulate import tabulate
# define the board
board = ["_", "_", "_",
"_", "_", "_",
"_", "_", "_"]
# Current player
current_player = "X"
winner = None
game_still_on = True
def play_game():
while game_still_on:
position()
board_display()
handle_player()
winner_check()
winner_check2()
def handle_player():
global current_player
if current_player == "X":
current_player = "O"
elif current_player == "O":
current_player = "X"
def board_display():
board_row1 = [board[0], board[1], board[2]]
board_row2 = [board[3], board[4], board[5]]
board_row3 = [board[6], board[7], board[8]]
com_board = [board_row1,
board_row2,
board_row3]
print(tabulate(com_board, tablefmt="grid"))
# position input
def position():
global board
print(current_player+"'s turn")
positions = input("enter 1-9")
valid = False
while not valid:
while int(positions) >= 10 or 0 >= int(positions):
positions = input("Choose a position from 1 -9")
positions = int(positions)
if board[positions-1] == "_":
valid = True
else:
print("Choose another")
board[positions - 1] = current_player
def winner_check():
if board[0] == board[1] == board[2] != "_":
return board[0]
elif board[3] == board[4] == board[5] != "_":
return board[3]
elif board[6] == board[7] == board[8] != "_":
return board[6]
elif board[0] == board[3] == board[6] != "_":
return board[0]
elif board[1] == board[4] == board[7] != "_":
return board[1]
elif board[2] == board[5] == board[8] != "_":
return board[2]
elif board[0] == board[4] == board[8] != "_":
return board[0]
elif board[2] == board[4] == board[6] != "_":
return board[1]
else:
return None
def winner_check2():
row_winner = winner_check()
if row_winner:
global game_still_on
global winner
winner = row_winner
print((winner+ " won"))
game_still_on = False
play_game()
Let's look at this function:
# position input
def position():
global board
print(current_player+"'s turn")
positions = input("enter 1-9")
valid = False
while not valid:
while int(positions) >= 10 or 0 >= int(positions):
positions = input("Choose a position from 1 -9")
positions = int(positions)
if board[positions-1] == "_":
valid = True
else:
print("Choose another")
board[positions - 1] = current_player
This has nested validation loops. The inner one checks the range of the input integer (if it is an integer -- otherwise it throws an exception) and requests input until it's in range. That's fine.
Then in the outer validation loop, it checks if the requested space is unoccupied. If so, fine. If not, it prompts the user to choose another. But the input call is before the outer loop, so it just tries again to validate the same input that already failed.
Try moving the input into the outer loop:
# position input
def position():
global board
print(current_player+"'s turn")
valid = False
while not valid:
positions = input("enter 1-9")
while int(positions) >= 10 or 0 >= int(positions):
positions = input("Choose a position from 1 -9")
positions = int(positions)
if board[positions-1] == "_":
valid = True
else:
print("Choose another")
board[positions - 1] = current_player
I'd probably also change the inner loop to be just an if with a continue and make the handling of non-integer input more robust.
This is my first ever post on here, as usually I just follow tutorials on Youtube or whatever, but I really wanted to do a project mainly by myself. I made a little Tic Tac Toe game I was pretty proud of today in Python, but there is one thing that doesn't work. The win conditions. I put in the winLoseCondition() in different spots before, but it doesn't work. Once it gets to there, it either says I lose or win. I don't know how it decides before there is enough information. One other thing, sometimes the computer overwrites one of the places the player has gone, and I don't know why. I know I probably did 100 things wrong programming this and there is a way easier way of doing it, but there are many like it but this one is mine. So, the question I really am asking here is: How do I fix my code so that my win conditions, when fulfilled correctly, actually end the game at the correct time, and not at a random time when I place the function somewhere. Also, as a bonus, why is my computer/random O placing bot overwriting some of where the player places their X's? I know I could improve the thing that places the O's, but that is for another night.
import random
import sys
winCondition = False
def winLoseCondition():
if board[1] and board[2] and board[3] == 'X':
print('You win!')
sys.exit()
if board[1] and board[2] and board[3] == 'O':
print('You lose...')
sys.exit()
if board[1] and board[5] and board[9] == 'X':
print('You win!')
sys.exit()
if board[1] and board[5] and board[9] == 'O':
print('You lose...')
sys.exit()
if board[3] and board[5] and board[7] == 'X':
print('You win!')
sys.exit()
if board[3] and board[5] and board[7] == 'O':
print('You lose...')
sys.exit()
if board[1] and board[4] and board[7] == 'X':
print('You win!')
sys.exit()
if board[1] and board[4] and board[7] == 'O':
print('You lose...')
sys.exit()
if board[2] and board[5] and board[8] == 'X':
print('You win!')
sys.exit()
if board[2] and board[5] and board[8] == 'O':
print('You lose...')
sys.exit()
if board[3] and board[6] and board[9] == 'O':
print('You lose...')
sys.exit()
if board[3] and board[6] and board[9] == 'X':
print('You win!')
sys.exit()
if board[4] and board[5] and board[6] == 'O':
print('You lose...')
sys.exit()
if board[4] and board[5] and board[6] == 'X':
print('You win!')
sys.exit()
if board[7] and board[8] and board[9] == 'X':
print('You win!')
sys.exit()
if board[7] and board[8] and board[9] == 'O':
print('You lose...')
sys.exit()
while winCondition == False:
board = {1: ' ',2: ' ',3: ' ',
4: ' ',5: ' ', 6: ' ',
7: ' ', 8: ' ', 9: ' '}
print('We are going to play Tic Tac Toe')
firstPlayerMove = input('What is your first move? (Input a number 1:9. 1 is the top left box. 9 is the bottom right box.)')
#Player's First Move
if int(firstPlayerMove) == 1:
board[1] = 'X'
if int(firstPlayerMove) == 2:
board[2] = 'X'
if int(firstPlayerMove) == 3:
board[3] = 'X'
if int(firstPlayerMove) == 4:
board[4] = 'X'
if int(firstPlayerMove) == 5:
board[5] = 'X'
if int(firstPlayerMove) == 6:
board[6] = 'X'
if int(firstPlayerMove) == 7:
board[7] = 'X'
if int(firstPlayerMove) == 8:
board[8] = 'X'
if int(firstPlayerMove) == 9:
board[9] = 'X'
#Computer's First Move:
firstComputerMove = random.randint(1,9)
while firstComputerMove == int(firstPlayerMove):
firstComputerMove = random.randint(1,9)
while firstComputerMove != int(firstPlayerMove):
if firstComputerMove == 1:
board[1] = 'O'
break
if firstComputerMove == 2:
board[2] = 'O'
break
if firstComputerMove == 3:
board[3] = 'O'
break
if firstComputerMove == 4:
board[4] = 'O'
break
if firstComputerMove == 5:
board[5] = 'O'
break
if firstComputerMove == 6:
board[6] = 'O'
break
if firstComputerMove == 7:
board[7] = 'O'
break
if firstComputerMove == 8:
board[8] = 'O'
break
if firstComputerMove == 9:
board[9] = 'O'
break
#Player's Second Move
print('This is what the board looks like:')
print(board[1] + '|' + board[2] + '|' + board[3])
print('_ _ _')
print(board[4] + '|' + board[5] + '|' + board[6])
print('_ _ _')
print(board[7] + '|' + board[8] + '|' + board[9])
secondPlayerMove = input('What is your second move? ')
while int(secondPlayerMove) == int(firstPlayerMove):
secondPlayerMove = input('That space is already occupied. Please input a different number ')
while int(secondPlayerMove) == firstComputerMove:
secondPlayerMove = input('That space is already occupied. Please input a different number ')
while int(secondPlayerMove) != int(firstPlayerMove) or firstComputerMove:
if int(secondPlayerMove) == 1:
board[1] = 'X'
break
if int(secondPlayerMove) == 2:
board[2] = 'X'
break
if int(secondPlayerMove) == 3:
board[3] = 'X'
break
if int(secondPlayerMove) == 4:
board[4] = 'X'
break
if int(secondPlayerMove) == 5:
board[5] = 'X'
break
if int(secondPlayerMove) == 6:
board[6] = 'X'
break
if int(secondPlayerMove) == 7:
board[7] = 'X'
break
if int(secondPlayerMove) == 8:
board[8] = 'X'
break
if int(secondPlayerMove) == 9:
board[9] = 'X'
break
#Computer's Second Move
secondComputerMove = random.randint(1,9)
while int(secondComputerMove) == int(firstPlayerMove):
secondComputerMove = random.randint(1,9)
while int(secondComputerMove) == firstComputerMove:
secondComputerMove = random.randint(1,9)
while int(secondComputerMove) == int(secondPlayerMove):
secondComputerMove = random.randint(1,9)
while int(secondComputerMove) != int(firstPlayerMove) or firstComputerMove or int(secondPlayerMove):
if int(secondComputerMove) == 1:
board[1] = 'O'
break
if int(secondComputerMove) == 2:
board[2] = 'O'
break
if int(secondComputerMove) == 3:
board[3] = 'O'
break
if int(secondComputerMove) == 4:
board[4] = 'O'
break
if int(secondComputerMove) == 5:
board[5] = 'O'
break
if int(secondComputerMove) == 6:
board[6] = 'O'
break
if int(secondComputerMove) == 7:
board[7] = 'O'
break
if int(secondComputerMove) == 8:
board[8] = 'O'
break
if int(secondComputerMove) == 9:
board[9] = 'O'
break
#Player's Third Move
print('This is what the board looks like:')
print(board[1] + '|' + board[2] + '|' + board[3])
print('_ _ _')
print(board[4] + '|' + board[5] + '|' + board[6])
print('_ _ _')
print(board[7] + '|' + board[8] + '|' + board[9])
thirdPlayerMove = input('Please say where you want to move.')
while int(thirdPlayerMove) == int(firstPlayerMove):
thirdPlayerMove = input('Sorry, that space is taken, please try again.')
while int(thirdPlayerMove) == firstComputerMove:
thirdPlayerMove = input('Sorry, that space is taken, please try again.')
while int(thirdPlayerMove) == int(secondPlayerMove):
thirdPlayerMove = input('Sorry, that space is taken, please try again.')
while int(thirdPlayerMove) == secondComputerMove:
thirdPlayerMove = input('Sorry, that space is taken, please try again.')
while int(thirdPlayerMove) != int(firstPlayerMove) or firstComputerMove or int(secondPlayerMove) or secondComputerMove:
if int(thirdPlayerMove) == 1:
board[1] = 'X'
break
if int(thirdPlayerMove) == 2:
board[2] = 'X'
break
if int(thirdPlayerMove) == 3:
board[3] = 'X'
break
if int(thirdPlayerMove) == 4:
board[4] = 'X'
break
if int(thirdPlayerMove) == 5:
board[5] = 'X'
break
if int(thirdPlayerMove) == 6:
board[6] = 'X'
break
if int(thirdPlayerMove) == 7:
board[7] = 'X'
break
if int(thirdPlayerMove) == 8:
board[8] = 'X'
break
if int(thirdPlayerMove) == 9:
board[9] = 'X'
break
#Computer's Third Move
thirdComputerMove = random.randint(1,9)
while int(thirdComputerMove) == int(firstPlayerMove):
thirdComputerMove = random.randint(1,9)
while int(thirdComputerMove) == firstComputerMove:
thirdComputerMove = random.randint(1,9)
while int(thirdComputerMove) == int(secondPlayerMove):
thirdComputerMove = random.randint(1,9)
while int(thirdComputerMove) == secondComputerMove:
thirdComputerMove = random.randint(1,9)
while int(thirdComputerMove) == int(thirdPlayerMove):
thirdComputerMove = random.randint(1,9)
while int(thirdComputerMove) != int(firstPlayerMove) or firstComputerMove or int(secondPlayerMove) or secondComputerMove or int(thirdPlayerMove):
if int(thirdComputerMove) == 1:
board[1] = 'O'
break
if int(thirdComputerMove) == 2:
board[2] = 'O'
break
if int(thirdComputerMove) == 3:
board[3] = 'O'
break
if int(thirdComputerMove) == 4:
board[4] = 'O'
break
if int(thirdComputerMove) == 5:
board[5] = 'O'
break
if int(thirdComputerMove) == 6:
board[6] = 'O'
break
if int(thirdComputerMove) == 7:
board[7] = 'O'
break
if int(thirdComputerMove) == 8:
board[8] = 'O'
break
if int(thirdComputerMove) == 9:
board[9] = 'O'
break
#Player's Fourth Move
print('This is what the board looks like:')
print(board[1] + '|' + board[2] + '|' + board[3])
print('_ _ _')
print(board[4] + '|' + board[5] + '|' + board[6])
print('_ _ _')
print(board[7] + '|' + board[8] + '|' + board[9])
fourthPlayerMove = input('Where do you want to move?')
while int(fourthPlayerMove) == int(firstPlayerMove):
fourthPlayerMove = input('Sorry, that space is taken, please try again.')
while int(fourthPlayerMove) == firstComputerMove:
fourthPlayerMove = input('Sorry, that space is taken, please try again.')
while int(fourthPlayerMove) == int(secondPlayerMove):
fourthPlayerMove = input('Sorry, that space is taken, please try again.')
while int(fourthPlayerMove) == secondComputerMove:
fourthPlayerMove = input('Sorry, that space is taken, please try again.')
while int(fourthPlayerMove) == int(thirdPlayerMove):
fourthPlayerMove = input('Sorry, that space is taken, please try again.')
while int(fourthPlayerMove) == thirdComputerMove:
fourthPlayerMove = input('Sorry, that space is taken, please try again.')
while int(fourthPlayerMove) != int(firstPlayerMove) or firstComputerMove or int(secondPlayerMove) or secondComputerMove or int(thirdPlayerMove) or thirdComputerMove:
if int(fourthPlayerMove) == 1:
board[1] = 'X'
break
if int(fourthPlayerMove) == 2:
board[2] = 'X'
break
if int(fourthPlayerMove) == 3:
board[3] = 'X'
break
if int(fourthPlayerMove) == 4:
board[4] = 'X'
break
if int(fourthPlayerMove) == 5:
board[5] = 'X'
break
if int(fourthPlayerMove) == 6:
board[6] = 'X'
break
if int(fourthPlayerMove) == 7:
board[7] = 'X'
break
if int(fourthPlayerMove) == 8:
board[8] = 'X'
break
if int(fourthPlayerMove) == 9:
board[9] = 'X'
break
#Computer's Fourth Move
fourthComputerMove = random.randint(1,9)
while int(fourthComputerMove) == int(firstPlayerMove):
fourthComputerMove = random.randint(1,9)
while int(fourthComputerMove) == firstComputerMove:
fourthComputerMove = random.randint(1,9)
while int(fourthComputerMove) == int(secondPlayerMove):
fourthComputerMove = random.randint(1,9)
while int(fourthComputerMove) == secondComputerMove:
fourthComputerMove = random.randint(1,9)
while int(fourthComputerMove) == int(thirdPlayerMove):
fourthComputerMove = random.randint(1,9)
while int(fourthComputerMove) == thirdComputerMove:
fourthComputerMove = random.randint(1,9)
while int(fourthComputerMove) == int(fourthPlayerMove):
fourthComputerMove = random.randint(1,9)
while int(fourthComputerMove) != int(firstPlayerMove) or firstComputerMove or int(secondPlayerMove) or secondComputerMove or int(thirdPlayerMove) or thirdComputerMove or int(fourthPlayerMove):
if int(fourthComputerMove) == 1:
board[1] = 'O'
break
if int(fourthComputerMove) == 2:
board[2] = 'O'
break
if int(fourthComputerMove) == 3:
board[3] = 'O'
break
if int(fourthComputerMove) == 4:
board[4] = 'O'
break
if int(fourthComputerMove) == 5:
board[5] = 'O'
break
if int(fourthComputerMove) == 6:
board[6] = 'O'
break
if int(fourthComputerMove) == 7:
board[7] = 'O'
break
if int(fourthComputerMove) == 8:
board[8] = 'O'
break
if int(fourthComputerMove) == 9:
board[9] = 'O'
break
#Player's Last Move
print('This is what the board looks like:')
print(board[1] + '|' + board[2] + '|' + board[3])
print('_ _ _')
print(board[4] + '|' + board[5] + '|' + board[6])
print('_ _ _')
print(board[7] + '|' + board[8] + '|' + board[9])
print('There is only one last spot.')
if board[1] == ' ':
print('You had to move to spot 1')
board[1] = 'X'
if board[2] == ' ':
print('You had to move to spot 2')
board[2] = 'X'
if board[3] == ' ':
print('You had to move to spot 3')
board[3] == 'X'
if board[4] == ' ':
print('You had to move to spot 4')
board[4] = 'X'
if board[5] == ' ':
print('You had to move to spot 5')
board[5] = 'X'
if board[6] == ' ':
print('You had to move to spot 6')
board[6] = 'X'
if board[7] == ' ':
print('You had to move to spot 7')
board[7] = 'X'
if board[8] == ' ':
print('You had to move to spot 8')
board[8] = 'X'
if board[9] == ' ':
print('You had to move to spot 9')
board[9] = 'X'
#Final Board
print('The final board looks like:')
print(board[1] + '|' + board[2] + '|' + board[3])
print('_ _ _')
print(board[4] + '|' + board[5] + '|' + board[6])
print('_ _ _')
print(board[7] + '|' + board[8] + '|' + board[9])
winCondition = True
print('The final board looks like:')
print(board[1] + '|' + board[2] + '|' + board[3])
print('_ _ _')
print(board[4] + '|' + board[5] + '|' + board[6])
print('_ _ _')
print(board[7] + '|' + board[8] + '|' + board[9])
This is a Tic Tac Toe program, but it has a certain twist to it...you are able to cover up an opponent's x or o with a larger x or o. You have medium pieces and large pieces. For some reason, I can't get my board to display the current moves and it doesn't seem to recognize winning conditions. Any help would be greatly appreciated.
#Winner checker.
def player_done(playerSym, board):
return ((board[6] == playerSym and board[7] == playerSym and board[8] == playerSym) or # across the top
(board[3] == playerSym and board[4] == playerSym and board[5] == playerSym) or # across the middle
(board[0] == playerSym and board[1] == playerSym and board[2] == playerSym) or # across the bottom
(board[6] == playerSym and board[3] == playerSym and board[0] == playerSym) or # down the left side
(board[7] == playerSym and board[4] == playerSym and board[3] == playerSym) or # down the middle
(board[8] == playerSym and board[5] == playerSym and board[2] == playerSym) or # down the right side
(board[6] == playerSym and board[4] == playerSym and board[2] == playerSym) or # diagonal
(board[8] == playerSym and board[4] == playerSym and board[0] == playerSym)) # diagonal
def opponent_done(oppSym, board):
return ((board[6] == oppSym and board[7] == oppSym and board[8] == oppSym) or # across the top
(board[3] == oppSym and board[4] == oppSym and board[5] == oppSym) or # across the middle
(board[0] == oppSym and board[1] == oppSym and board[2] == oppSym) or # across the bottom
(board[6] == oppSym and board[3] == oppSym and board[0] == oppSym) or # down the left side
(board[7] == oppSym and board[4] == oppSym and board[1] == oppSym) or # down the middle
(board[8] == oppSym and board[5] == oppSym and board[2] == oppSym) or # down the right side
(board[6] == oppSym and board[4] == oppSym and board[2] == oppSym) or # diagonal
(board[8] == oppSym and board[4] == oppSym and board[0] == oppSym)) # diagonal
# Sets up the Board
def drawBoard(board):
print(' | |')
print(' ' + board[6] + ' | ' + board[7] + ' | ' + board[8])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[5] + ' | ' + board[4] + ' | ' + board[3])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[0] + ' | ' + board[1] + ' | ' + board[2])
print(' | |')
#Prints the current board
def print_board(board):
# Make a duplicate of the board list and return it the duplicate.
dupeBoard = []
for i in board:
dupeBoard.append(i)
return dupeBoard
#The Board
board = ["0", "1", "2", "3", "4", "5", "6", "7", "8"]
done = False
#The Move list for X's and O's
xmovesList = ["*","x","X"]
omovesList = [".","o","O"]
#Greeting message and choosing the initial X and O assignment.
print "Welcome to Tic-Tac-Toe-Cover-Up!"
playerSym = raw_input("Player 1, please select either X or O for your pieces: ")
print
#Player and opponent move assignment
if (playerSym == "X"):
playerSym = xmovesList
oppSym = omovesList
turn = "X"
else:
playerSym = omovesList
oppSym = xmovesList
turn = "O"
#Main game loop.
while not done:
drawBoard(board)
print turn,"'s turn"
if (turn == "X"):
player = xmovesList
opponent = omovesList
else:
player = omovesList
opponent = xmovesList
print "Select the place you want to play (0-8)"
print_board(board)
pos = input("Select: ")
if pos <=8 and pos >=0:
Y = pos/3
X = pos%3
if X != -1:
X -=1
else:
X = 2
Y -=1
if board == " ":
board = player[9]
moved = True
done = player()
elif board != " ":
if board == opponent[0]:
board = player[1]
moved = True
done = player_done()
done = opponent_done()
if board == opponent[1]:
board = player[2]
moved = True
done = player_done()
done = opponent_done()
if done == False:
if turn == "X":
turn = "O"
else:
turn = "X"
There were mltiple issues with it.
For emptiness You were comparing with " " where as you are initialing board with 1-9
Also major issue of error :
board = player[9]
This you needed
board[pos] = player[0]
Also you need to fix checking logic to :
board[6] in playerSym # and not board[6] == playerSym
This is program with some fixes.
#Winner checker.
def check_done(playerSym,board):
return ((board[6] in playerSym and board[7] in playerSym and board[8] in playerSym) or # across the top
(board[3] in playerSym and board[4] in playerSym and board[5] in playerSym) or # across the middle
(board[0] in playerSym and board[1] in playerSym and board[2] in playerSym) or # across the bottom
(board[6] in playerSym and board[3] in playerSym and board[0] in playerSym) or # down the left side
(board[7] in playerSym and board[4] in playerSym and board[3] in playerSym) or # down the middle
(board[8] in playerSym and board[5] in playerSym and board[2] in playerSym) or # down the right side
(board[6] in playerSym and board[4] in playerSym and board[2] in playerSym) or # diagonal
(board[8] in playerSym and board[4] in playerSym and board[0] in playerSym)) # diagonal
# Sets up the Board
def drawBoard(board):
print(' | |')
print(' ' + board[6] + ' | ' + board[7] + ' | ' + board[8])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[5] + ' | ' + board[4] + ' | ' + board[3])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[0] + ' | ' + board[1] + ' | ' + board[2])
print(' | |')
#Verifies if board is not full with all largest signs and no mpre moves are possible.
def movesPossible(board):
#TODO: implement this
return True
#Prints the current board
def print_board(board):
# Make a duplicate of the board list and return it the duplicate.
dupeBoard = []
for i in board:
dupeBoard.append(i)
return dupeBoard
#The Board
board = ["0", "1", "2", "3", "4", "5", "6", "7", "8"]
done = False
#The Move list for X's and O's
xmovesList = ["*","x","X"]
omovesList = [".","o","O"]
#Greeting message and choosing the initial X and O assignment.
print "Welcome to Tic-Tac-Toe-Cover-Up!"
playerSym = raw_input("Player 1, please select either X or O for your pieces: ")
print
#Player and opponent move assignment
if (playerSym == "X"):
player = xmovesList
opponent = omovesList
else:
player = omovesList
opponent = xmovesList
drawBoard(board)
#Main game loop.
while movesPossible(board):
print player[2],"'s turn"
print "Select the place you want to play (0-8)"
print_board(board)
moved = False
pos = input("Select: ")
if pos <=8 and pos >=0:
Y = pos/3
X = pos%3
if X != -1:
X -=1
else:
X = 2
Y -=1
if board[pos] == str(pos):
board[pos] = player[0]
moved = True
done = check_done(player,board)
else :
if board[pos] == opponent[0]:
board[pos] = player[1]
moved = True
done = check_done(player,board)
if board[pos] == opponent[1]:
board[pos] = player[2]
moved = True
done = check_done(player,board)
drawBoard(board)
if done:
break;
if moved :
player,opponent = opponent,player
if(done):
print player[2], "wins "
else:
print "No more moves possible. It's a draw."