Python tic tac toe game - python

I am unsure if all of the code will be necessary or not so i will post it:
# Tic-Tac-Toe
# Plays the game of tic-tac-toe against a human opponent
# global constants
X = "X"
O = "O"
EMPTY = " "
TIE = "TIE"
NUM_SQUARES = 9
def display_instruct():
"""Display game instructions."""
print(
"""
Welcome to the greatest intellectual challenge of all time: Tic-Tac-Toe.
This will be a showdown between your human brain and my silicon processor.
You will make your move known by entering a number, 0 - 8. The number
will correspond to the board position as illustrated:
0 | 1 | 2
---------
3 | 4 | 5
---------
6 | 7 | 8
Prepare yourself, human. The ultimate battle is about to begin. \n
"""
)
def ask_yes_no(question):
"""Ask a yes or no question."""
response = None
while response not in ("y", "n"):
response = input(question).lower()
return response
def ask_number(question, low, high):
"""Ask for a number within a range."""
response = None
while response not in range(low, high):
response = int(input(question))
return response
def pieces():
"""Determine if player or computer goes first."""
go_first = ask_yes_no("Do you require the first move? (y/n): ")
if go_first == "y":
print("\nThen take the first move. You will need it.")
human = X
computer = O
else:
print("\nYour bravery will be your undoing... I will go first.")
computer = X
human = O
return computer, human
def new_board():
"""Create new game board."""
board = []
for square in range(NUM_SQUARES):
board.append(EMPTY)
return board
def display_board(board):
"""Display game board on screen."""
print("\n\t", board[0], "|", board[1], "|", board[2])
print("\t","---------")
print("\t",board[3], "|", board[4], "|", board[5])
print("\t","---------")
print("\t",board[6], "|", board[7], "|", board[8])
def legal_moves(board):
"""Create list of legal moves."""
moves = []
for square in range(NUM_SQUARES):
if board[square] == EMPTY:
moves.append(square)
return moves
def winner(board):
"""Determine the game winner."""
WAYS_TO_WIN = ((0, 1, 2),
(3, 4, 5),
(6, 7, 8),
(0, 3, 6),
(1, 4, 7),
(2, 5, 8),
(0, 4, 8),
(2, 4, 6))
for row in WAYS_TO_WIN:
if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
winner = board[row[0]]
return winner
if EMPTY not in board:
return TIE
return None
def human_move(board, human):
"""Get human move."""
legal = legal_moves(board)
move = None
while move not in legal:
move = ask_number("Where will you move? (0 - 8):", 0, NUM_SQUARES)
if move not in legal:
print("\nThat square is already occupied, foolish human. Choose another.\n")
print("Fine...")
return move
def computer_move(board, computer, human):
"""Make computer move."""
# make a copy to work with since function will be changing list
board = board[:]
# the best positions to have, in order
BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7)
print("I shall take square number,", end="")
# if computer can win, take that move
for move in legal_moves(board):
board[move] = computer
if winner(board) == computer:
print(move)
return move
# done checking this move, undo it
board[move] = EMPTY
# if human can win, block that move
for move in legal_moves(board):
board[move] = human
if winner(board) == human:
print(move)
return move
# done checkin this move, undo it
board[move] = EMPTY
# since no one can win on next move, pick best open square
for move in BEST_MOVES:
if move in legal_moves(board):
print(move)
return move
def next_turn(turn):
"""Switch turns."""
if turn == X:
return O
else:
return X
def congrat_winner(the_winner, computer, human):
"""Congratulate the winner."""
if the_winner != TIE:
print(the_winner, "won!\n")
else:
print("It's a tie!\n")
if the_winner == computer:
print("As I predicted, human, I am triumphant once more. \n" \
"Proof that computers are superior to humans in all regards.")
elif the_winner == human:
print("No, no! It cannot be! Somehow you tricked me, human. \n" \
"But never again! I, the computer, so swear it!")
elif the_winner == TIE:
print("You were most lucky, human, and somehow managed to tie me. \n" \
"Celebrate today... for this is the best you will ever achieve.")
def main():
display_instruct()
computer, human = pieces()
turn = X
board = new_board()
display_board(board)
while not winner(board):
if turn == human:
move = human_move(board, human)
board[move] = human
else:
move = computer_move(board, computer, human)
board[move] = computer
display_board(board)
turn = next_turn(turn)
the_winner = winner(board)
congrat_winner(the_winner, computer, human)
# start the program
main()
input("\n\nPress the enter key to quit.")
This is an example in a book i am reading and i am not fully understanding, i think understand all of it up until:
for row in WAYS_TO_WIN:
if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
winner = board[row[0]]
return winner
Can somebody please explain what this function does and more specifically what the condition
if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY: is testing?

It's just checking the current board to see if any winning combination of cells (as listed in the row array) have (a) the same value and (b) that value is not EMPTY.
Note: in Python, if a == b == c != d, checks that a ==b AND b == c AND c != d
So if cells 0, 1, and 2, all have X, then on the first pass through the loop, it will return X from the winner routine.

The best way to see what is going on is to put some print statements in this code when you run it.
Judging by the way things are names, you can tell that you're looking to see if someone has won the game. You know from the rules of TicTacToe that if X or O have three in a row, column, or diagonal, that player wins. You see in the board[x] == board[y] == board[z] that we're probably testing for three in a row here. So what is x, y z? Well, look at WAYS_TO_WIN. In that array are rows indicating the indices that are in a row, column, or diagonal. Thus, we're testing to see if a row, column, or diagonal contains the same character, and that character is NOT EMPTY (which is the " " [space] character).

I am new to Python. The script below for tic tac toe game is from one of my exercises. It uses a different approach.
For the data structure, I used integer value 0 for blank cells, +1 for computer placed cells and -1 for user placed cells.
The main benefit is I can use the lineValue, i.e., the sum of all three cells' values in a line, to track the status of each line. All 8 line values are stored in the list lineValues. This can make the decision much easier. For example, When it's my (computer's) turn, if there is a line with lineValue==2, I know I am going to win. Otherwise, if there are line(s) with lineValue ==-2, I have to block the intersection (if any) of these lines.
The key for making decision is the function findMostValuableCell. What it does is to find out which cell is most valuable for the next move (i.e., which cell appears in most number of lines for a specific lineValue). There is no try-out test (what-if test) in this script. It uses quite a few list comprehensions.
Hope it can help.
ttt = [0 for i in range(9)]
lines = [[0, 1, 2],[3, 4, 5],[6, 7, 8],[0, 3, 6],[1, 4, 7],[2, 5, 8],[0, 4, 8],[2, 4, 6]]
lineValues = [0 for i in range(8)]
userChar = {1: "O", -1: "X", 0: "_"}
turn = -1 # defalut to user move first
#*****************************************************
def main():
global userChar, turn
if input("Do you want me to start first? (Y/N)").lower()=="y":
userChar = {1:"X",-1:"O",0:"_"}
turn = 1
display()
while not hasWinner():
if 0 in ttt:
nextMove(turn)
turn *= -1
display()
else:
print("It's a tie!")
break
#*****************************************************
def hasWinner():
if max(lineValues) == 3:
print("******** I win!! ********")
return True
elif min(lineValues) == -3:
print("******** You win ********")
return True
#*****************************************************
def nextMove(turn):
if turn== -1: #User's turn
print("It's your turn now (" + userChar[-1]+"):")
while not isUserMoveSuccessful(input("Please choose your cell number:")):
print("Your choice is not valid!")
else: #Computer's turn
print("It's my turn now...")
for lineValue in [2,-2,-1,1,0]:
cell = findMostValuableCell(lineValue)
if cell>=0: #found a cell for placement
markCell(cell, turn)
print ("I chose cell", str(cell),"." )
return
#*****************************************************
def isUserMoveSuccessful(userInput):
s = list(userInput)[0]
if '012345678'.find(s)>=0 and ttt[int(s)]==0:
markCell(int(s), turn)
return True
#*****************************************************
def findMostValuableCell(lineValue):
if set(ttt)=={0}:
return 1
allLines = [i for i in range(8) if lineValues[i]==lineValue]
allCells =[j for line in allLines for j in lines[line] if ttt[j]==0]
cellFrequency = dict((c, allCells.count(c)) for c in set(allCells))
if len(cellFrequency)>0: # get the cell with highest frequency.
return max(cellFrequency, key=cellFrequency.get)
else:
return -1
#*****************************************************
def markCell(cell, trun):
global lineValues, ttt
ttt[cell]=turn
lineValues = [sum(cellValue) for line in lines for cellValue in [[ttt[j] for j in line]]]
#*****************************************************
def display():
print(' _ _ _\n'+''.join('|'+userChar[ttt[i]]+('|\n' if i%3==2 else '') for i in range(9)))
#*****************************************************
main()

I would put it simply.
Row is a variable that is assigned to each tuple in the tuple WAYS_TO_WIN.
In the first iteration, row = (0,1,2)
it checks if value at 0==1==2.
In the second iteration, row = (3,4,5)
it checks if value at 3==4==5.
Row goes to each inner tuple of the outer tuple ways_to_win till row = (2,4,6) is reached.
That's what the program is doing.

List item
def tic_tac_toe():
board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
end = False
win_commbinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))
def draw():
print(board[0], board[1], board[2])
print(board[3], board[4], board[5])
print(board[6], board[7], board[8])
print()
def p1():
n = choose_number()
if board[n] == "X" or board[n] == "O":
print("\nYou can't go there. Try again")
p1()
else:
board[n] = "X"
def p2():
n = choose_number()
if board[n] == "X" or board[n] == "O":
print("\nYou can't go there. Try again")
p2()
else:
board[n] = "O"
def choose_number():
while True:
while True:
a = input()
try:
a = int(a)
a -= 1
if a in range(0, 9):
return a
else:
print("\nThat's not on the board. Try again")
continue
except ValueError:
print("\nThat's not a number. Try again")
continue
def check_board():
count = 0
for a in win_commbinations:
if board[a[0]] == board[a[1]] == board[a[2]] == "X":
print("Player 1 Wins!\n")
print("Congratulations!\n")
return True
if board[a[0]] == board[a[1]] == board[a[2]] == "O":
print("Player 2 Wins!\n")
print("Congratulations!\n")
return True
for a in range(9):
if board[a] == "X" or board[a] == "O":
count += 1
if count == 9:
print("The game ends in a Tie\n")
return True
while not end:
draw()
end = check_board()
if end == True:
break
print("Player 1 choose where to place a cross")
p1()
print()
draw()
end = check_board()
if end == True:
break
print("Player 2 choose where to place a nought")
p2()
print()
if input("Play again (y/n)\n") == "y":
print()
tic_tac_toe()

Related

TicTacToe doesn't apply Win-Conditions && Wrong moves on minimax

i am trying to learn python and have been trying to programm a simple tictactoe game.
Below is the code:
import random
class TicTacToe03:
def __init__(self):
# first, the board
self.board = self.board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
# then, the symbols the players will choose
self.playerSymbol = ""
self.aiSymbol = ""
# the game is always ongoing, unless somebody won
self.gameOngoing = True
# you also need to tell the ai how different conditions are evaluated
self.scoreBoard = {
self.playerSymbol: -10, # if the player wins, it is seen as smth bad from the ai
self.aiSymbol: 10,
"tie": 0
}
# every tictactoe game starts by drawing the board
def drawBoard(self):
print("""
{} | {} | {}
-----------
{} | {} | {}
-----------
{} | {} | {}
""".format(*self.board))
# then, eveybody chooses what the like
def chooseYourPlayer(self):
self.playerSymbol = input("choose your player X/O ").upper()
if self.playerSymbol == "X":
self.aiSymbol = "O"
else:
self.aiSymbol = "X"
# everybody has to behave and leave their turn when it's over
def nextPlayer(self, player):
if player == self.playerSymbol:
return self.aiSymbol
return self.playerSymbol
# ppl also have to be able to make moves
def move(self, player, index):
self.board[index] = player
# and find what moves they CAN make, so they don't override each-other
def availableMoves(self):
availableMoves = []
for fieldIndex in range(len(self.board)):
if self.board[fieldIndex] == " ":
availableMoves.append(fieldIndex) # yes, i append indexes, not empty fields
return availableMoves
def getMoves(self, player):
playerMoves = []
for fieldIndex in range(len(self.board)):
if self.board[fieldIndex] == player:
playerMoves.append(fieldIndex)
return playerMoves
# here is the algo to check who won, based on a set of winPos is subset of playerMoves
def won(self):
winningPositions = [{0, 1, 2}, {3, 4, 5}, {6, 7, 8},
{0, 4, 8}, {2, 4, 6}, {0, 3, 6},
{1, 4, 7}, {2, 5, 8}]
for player in ("X", "O"):
playerPositions = self.getMoves(player)
for position in winningPositions:
if position.issubset(playerPositions):
print(player + "wins")
self.gameOngoing = False
return player
if self.board.count(" ") == 0: # and this dude outside of the main loop
print("Guess it's a draw")
self.gameOngoing = False
return "tie"
def minimax(self, isMaximizing, player):
if not self.gameOngoing: # base in minimax: if this is an end-state, return it's evaluation
return self.scoreBoard[self.won()]
if isMaximizing:
bestScore = float("-Infinity") # the worst eval for max
for move in self.availableMoves():
self.move(player, move)
score = self.minimax(False, self.nextPlayer(player)) # you should pick the max of what your opponent chooses
self.move(" ", move)
bestScore = max(bestScore, score)
return bestScore
else:
bestScore = float("Infinity")
for move in self.availableMoves():
self.move(player, move)
score = self.minimax(True, self.nextPlayer(player))
self.move(" ", move)
bestScore = min(bestScore, score)
return bestScore
def findOptimalMove(self, player):
goldenMiddle = 0
choices = []
for move in self.availableMoves():
self.move(player, move)
score = self.minimax(True, player)
self.move(" ", move)
if score > goldenMiddle:
choices = [move] # this is a one-element list
break
elif score == goldenMiddle:
choices.append(move)
# here is the code block that mustn't be wrongly interpreted:
# the idea is: you choose a random element, from a ONE-ELEMENT list!!!
if len(choices) > 0:
return random.choice(choices)
else:
return random.choice(self.availableMoves())
def play(self):
self.chooseYourPlayer()
while self.gameOngoing:
personMove = int(input("Choose a position (1-9) "))
self.move(self.playerSymbol, personMove - 1)
self.drawBoard()
if not self.gameOngoing:
break
print("Computer choosing move...")
aiMove = self.findOptimalMove(self.aiSymbol)
self.move(self.aiSymbol, aiMove)
self.drawBoard()
print("Thanks for playing :)")
tictactoe = TicTacToe03()
tictactoe.play()
The game "works", as of it displays the fields of the user, however it won't show whether anybody won or not.
As you can see, i tried implementing the simple minimax algorithm, but that doesn't work properly either, because the ai just chooses the next available field to go to and not the one it logically should.
As for the errors i am getting: i only got one once, after the board was full and it was the following: IndexError: Cannot choose from an empty sequence (on line 133).
I have also posted another version of this, where the "winning" issue is not present ( TicTacToe and Minimax ), but since nobody was answering that question, I thought it would be helpful asking again (sorry if i did anything wrong)
As always, I remain open to suggestions and ways to improve my code :)
In my opinion, the only issue is that you forgot to call self.won() in the play() method:
def play(self):
self.chooseYourPlayer()
while self.gameOngoing:
personMove = int(input("Choose a position (1-9) "))
self.move(self.playerSymbol, personMove - 1)
self.drawBoard()
self.won() #<--- call self.won() here
if not self.gameOngoing:
break
print("Computer choosing move...")
aiMove = self.findOptimalMove(self.aiSymbol)
self.move(self.aiSymbol, aiMove)
self.drawBoard()
print("Thanks for playing :)")
I think you tried to do something similar in minimax() method. But I didn't understand what did you mean by:
if not self.gameOngoing:
return self.scoreBoard[self.won()]

Simple 2 Players Tic Tac Toe Python

I am setting up a 2-player tic tac toe game (it's a homework). But I don't understand what mistakes I make.
def start_move(board, letter, move):
board[move] = letter
def next_player(board, player_1_letter):
#determine 2 players' letter position
if player_1_letter == "X":
player_2_letter = "O"
else:
player_2_letter = "X"
def if_board_full(board):
#if the board is full, back to "True"
for i in range(1, 10):
if free_space(board, i):
return False
return True
print("Welcome to tic tac toe !!!")
while True:
#renew the board
the_board = [" "] * 10
player_1_letter, player_2_letter = input_letter()
turn = first_turn()
print(turn + " will go first.")
gamestarts = True
while gamestarts:
if turn == "Player who choose O.":
gameboard(the_board)
move = firstplayermove(the_board)
start_move(the_board, player_1_letter, move)
if winner(the_board, player_1_letter):
gameboard(the_board)
print("Congratulationsss!!!!" + player_1_letter + " has won!")
gamestarts = False
else:
if free_space(the_board):
gameboard(the_board)
print("Tie!")
break
else:
turn = "Player who choose X"
else:
#player 2's turn
move = next_player(the_board, player_2_letter)
start_move(the_board, player_2_letter, move)
if winner(the_board, player_2_letter):
gameboard(the_board)
print("Player 2 has won!!! Congratulations!")
gamestarts = False
else:
if free_space(the_board):
gameboard(the_board)
print("Tie!!!")
break
else:
turn = "Player who choose O"
if not play_again():
break
I expect the game (code) is ok (for me)... but it keep saying.
Traceback (most recent call last): File
"C:\Users\ASUS\Desktop\Python\projectdemo.py", line 122, in
start_move(the_board, player_2_letter, move) File "C:\Users\ASUS\Desktop\Python\projectdemo.py", line 51, in start_move
board[move] = letter TypeError: list indices must be integers or slices, not NoneType
On line 50 you set move = next_player(the_board, player_2_letter). The function next_player() doesn't return any value, so move doesn't get a value.
Change next_player() to this:
def next_player(board, player_1_letter):
#determine 2 players' letter position
if player_1_letter == "X":
player_2_letter = "O"
else:
player_2_letter = "X"
return player_2_letter
You haven't defined move as anything in board[move]. It doesn't know what to do with it.

Tuple index out of range

print "\n\t\t\t\t",moves[6],"|",moves[7],"|",moves[8]
IndexError: tuple index out of range
is the error that I am getting. I am currently writing a python program for tictactoe. moves is equal to ['','','','','','','','','']. Would you like any other info?
I have so far, changed 789 in the row to 678 because indexes begin at 0. Nothing happening.
Next, I tried various other small changes, each of which either changed the error or just gave me the same error.
I also attempted to change formats and things, which did not go so well. I am running python 2.7(?), if that matters.
def draw(moves):
print "\n\t\t\t\t",moves[6],"|",moves[7],"|",moves[8]
print "\t\t\t\t", "--------"
print "\n\t\t\t\t",moves[3],"|",moves[4],"|",moves[5]
print "\t\t\t\t", "--------"
print "\n\t\t\t\t",moves[0],"|",moves[1],"|",moves[2], "\n"
import time
import random
moves = ['','','','','','','','','']
player = ''
ai = ''
restart = ''
first = 19
whosfirst = 1
# Ok, so this is to decide the symbol for each person ---------------------------------------------------
def XorO(man, machine):
print 'Please select a symbol to represent you'
player = raw_input( "Please select \"X\" or \"O\"")
while player not in ('x','X','o','O'):
print "I'm sorry, I don't think I got that. Please try again"
time.sleep(1)
player = raw_input("Select \"X\" or \"O\"")
if player == 'x' or player == 'X':
print "X"
time.sleep(1)
print "Ok, then I'll be \"O\""
ai = 'o'
else:
print "O"
time.sleep(1)
print "Ok, then I'll be \"X\""
ai = 'x'
return player.upper(), ai.upper()
# This is for who is going first -----------------------------------------------------------------------
def first():
number = "a"
while number not in ('n','y',"no",'yes'):
number = raw_input("Do you want to go first? - ").lower()
if number == 'y' or number == 'yes':
return 1
elif number == 'n' or number == 'no':
return 0
else:
print "I'm sorry, I dont think that I understood you."
time.sleep(1)
print "Please select y, yes, n, or no"
#Here Comes the hard part -- drawing the board
def draw(moves):
print "\n\t\t\t\t",moves[6],"|",moves[7],"|",moves[8]
print "\t\t\t\t", "--------"
print "\n\t\t\t\t",moves[3],"|",moves[4],"|",moves[5]
print "\t\t\t\t", "--------"
print "\n\t\t\t\t",moves[0],"|",moves[1],"|",moves[2], "\n"
def playerwon():
print "You won! Yay! Now try again"
def aiwon():
print "I won! Won't you try again?"
def playerfirst(player, ai, moves):
while win(player, ai, moves) is None:
moves = playermove(player, moves - 1)
moves[int(moves)] = player
draw(moves)
if win(player, ai, moves) != None:
break
else:
pass
Dmove = machine_move(player, ai, moves)
print "Nice moves! I'll try ",Dmove
moves[int(Dmove)] = ai
draw(moves)
q = win(player, ai, moves)
if q == 1:
playerwon()
elif q == 0:
aiwon()
else:
print "We tied =-("
time.sleep(2)
print "Let's have another go!"
def aifirst(player, ai, moves):
while not win(player, ai, moves):
Dmove = machine_move(man, machine, moves)
print "I'll take..." , Dmove
moves[Dmove] = machine
draw(moves)
if win(player, ai, moves) != None:
break
else:
pass
moves = playermove(player, moves)
moves[int(moves)] = player
draw(moves)
variable = win(player, ai, moves)
if q == 1:
playerwon()
elif q == 0:
aiwon()
else:
print "We tied =-("
time.sleep(2)
print "Let's have another go!"
def win(player, ai, moves):
ways = ((7,8,9),(4,5,6),(1,2,3),(7,4,1)(8,5,2),(9,6,3),(7,5,3),(9,5,1))
for i in ways:
if ways[i[0]] == ways[i[1]] == ways[i[2]] != empty:
winner = new[i[0]]
if winner == player:
return 1
elif winner == ai:
return 0
if empty not in new:
return 'TIE'
if empty not in new:
return 'TIE'
return None
def playermove(player, moves):
moves = raw_input("Where would you like to place your symbol?")
while True:
if moves not in ('0','1','2','3','4','5','6','7','8'):
print "Sorry, I don't think that's a valid spot... Try again"
moves = raw_input("Where would you like to place your symbol ")
elif moves[int(moves)] != empty:
print "Sorry, I think there's somehing already there..."
moves = raw_input("Where would you like to place your symbol?")
else:
return int(moves)
def aimove(player, ai, moves):
bestmoves = [5, 7, 9, 1, 3]
blank = []
for i in range(0,9):
if moves[i] == empty:
blank.append(i)
for num in blank:
moves[i] = ai
if win(man, ai, moves) is 0:
return i
moves[i] = empty
for num in blank:
moves[i] = man
if win(man, ai, moves) is 1:
return num
moves[i] = empty
return int(blank[random.randrange(len(blank))])
def display_instruction():
print "Welcome to PMARINA's TicTacToe v 1.1.1 ..."
print "In order to place your symbol, just press the corresponding key on your numpad."
print "If you do not have a numpad, then please note down the following arrangement"
print "7 | 8 | 9"
print "-----------"
print "4 | 5 | 6"
print "-----------"
print "1 | 2 | 3"
print "Good Luck, and don't forget to do the most important thing:"
time.sleep(2)
print "HAVING FUN!!"
time.sleep(2)
def letsgo(player, ai, moves):
display_instruction()
print "so lets begin.."
moves = XorO(player, ai)
player = moves[0]
ai = moves[1]
whosfirst = first()
if whosfirst == 1:
print "Ok, you are first!"
print "Lets go!"
draw(moves)
playerfirst(player, ai, moves)
else:
print "Ok, I'll be the first!"
print "So, lets start.."
draw(moves)
aifirst(player, ai, moves)
letsgo(player, ai, moves)
raw_input("Press enter to exit")
Line 14:
moves = ['','','','','','','','','']
Line 192:
moves = XorO(player, ai)
...
draw(moves)
You overwrote your initial declaration of moves, so ('X', 'O') is being passed to draw.
If moves is ['','','','','','','','',''] and the error message you're getting is:
IndexError: tuple index out of range
Then the error is not occurring on the line you say it is. moves is a list, not a tuple. And it does have indices up to 8. moves[9] would generate this error instead:
IndexError: list index out of range
The only tuple I see in the code is ways. Also you don't seem to initialize new before you use it in the function 'win'.
FYI, tuples are made using parentheses tup = (1, 2, 3, 4) while lists use brackets list = [1,2,3,4]. Tuples are also immutable, so you can't modify them later.

How to find tie game python

Hi i was making this tic tac toe game and i watched some tutorials for it, but there wasn't any game that could end with tie game i tried to make one but the game freezes when tie game appears don't worry about my Finnish variables and comments
import random
board = [0,1,2,
3,4,5,
6,7,8]
def show():
print board[0], '|',board[1],'|',board[2]
print '----------'
print board[3], '|',board[4],'|',board[5]
print '----------'
print board[6], '|',board[7],'|',board[8]
def checkLine(char, spot1, spot2, spot3):
if (board[spot1] == char) and (board[spot2] == char) and (board [spot3] == char) :
return True
else:
return False
def checkAll(char):
ret = False
if checkLine(char, 0, 1, 2):
ret = True
if checkLine(char, 0,3, 6):
ret = True
if checkLine(char, 1, 4, 7):
ret = True
if checkLine(char, 2, 5, 8):
ret = True
if checkLine(char, 6, 7, 8):
ret = True
if checkLine(char, 3, 4, 5):
ret = True
if checkLine(char, 2, 4, 6):
ret = True
if checkLine(char, 0, 4, 8):
ret = True
return ret
moves = range(9)
numindex = 1
ratkennut = False
while moves:
show()
input = raw_input("Put x: ")
try:
val = int(input)
input = int(input)
except ValueError:
print("Input number!")
input = raw_input("Put x: ")
input = int(input)
if input in moves:
moves.remove(input)
if board [input] != 'x' and board[input] != 'o':
board[input] = 'x'
if checkAll('x') == True:
print "~~ X Won ~~"
ratkennut = True
break;
while moves:
random.seed() #Gives opponents move
opponent = random.choice(moves)
moves.remove(opponent)
if board[opponent] != 'o' and board[opponent] != 'x':
board[opponent] = 'o'
if checkAll('o') == True:
print "~~ O Won ~~"
ratkennut = True
break;
else:
print 'This spot is taken'
else:
print "Tie!"
Question: What's wrong with this code when the game ends with tie game it freezes and i need to ctrl + c how to make it find the tie game and print "tie game"
I edited it and now it works really great!
Your randint move choice in a while loop for the opponent could run indefinitely, especially as the number of valid moves remaining gets smaller. Instead, make a list of valid moves and list.remove() each move from it:
moves = range(9)
This simplifies the user's move:
if input in moves:
moves.remove(input)
The opponent's move:
opponent = random.choice(moves)
moves.remove(opponent)
And determining the end of the game:
while moves:
...
else:
print "It's a tie."
You could count your moves there are only 9 moves in a tic tac toe game.
You want something like:
if not checkAll('o') and not checkAll('x') and moves == 9:
print "Tie Game"
break

IndexErrors in Tic-Tac-Toe program I'm having issues with

I've pasted the code here:
X = "X"
O = "O"
board = []
EMPTY = ""
def instructions_prompt ():
print "\t\t\tNoughts and Crosses"
print \
"""Foolish human. Now that you've entered this Python program,
there is no exit. None! (At any point in the game if you feel
like you are intimidated by my presence, hit 0 to exit)
This challenge of wits will be one of many failures in your life.
The instructions are as follows:
1. Select a number from the following key:
0 | 1 | 2
---------
3 | 4 | 5
---------
6 | 7 | 8
to place X or O which is predetermined by whether or not you start
the game.
2. Try to save face while failing. And don't talk about Fight Club."""
def start_prompt ():
choice = raw_input ("Would you like to go first (Y/N)?")
lower = choice.lower()
if lower == "y":
human = X
computer = O
print "You're",human
print "I am",computer
elif lower == "n":
computer = X
human = O
print "You're",human
print "I'm in",computer
return human, computer
def display_board (board):
print "",board[0],"|",board[1],"|",board[2],""
print "---------"
print "",board[3],"|",board[4],"|",board[5],""
print "---------"
print "",board[6],"|",board[7],"|",board[8],""
def turn_switcher (turn):
if turn == X:
return O
else:
return X
def fresh_board ():
for i in range (9):
board.append (EMPTY)
return board
def request_move ():
try:
square = int(raw_input("Where'd you like your square to be?"))
if square>8 or square<0:
print "This program can't proceed as that number is not on the board."
else:
return square
except:
print "That's not a number on the board. This program can't proceed."
def legal_moves (board):
legal_moves = []
for i in range (9):
if board [i] == EMPTY:
legal_moves.append(i)
return legal_moves
def winner (board):
if board[0] == board [1] == board [2] != EMPTY:
winner = board [0]
return winner
elif board [0] == board [3] == board [6] != EMPTY:
winner = board [0]
return winner
elif board [0] == board [4] == board [8] != EMPTY:
winner = board [0]
return winner
elif board [1] == board [4] == board [7] != EMPTY:
winner = board [1]
return winner
elif board [2] == board [5] == board [8] != EMPTY:
winner = board [2]
return winner
elif board [2] == board [4] == board [6] != EMPTY:
winner = board [2]
return winner
elif board [6] == board [7] == board [8] != EMPTY:
winner = board [8]
return winner
elif EMPTY not in board:
return None
def human_move (board, square):
legal = legal_moves(board)
if square not in legal:
print "This is not a legal move"
sys.exit()
else:
return square
def computer_move (computer, board, human):
best = (4,0,8,2,6,1,3,5,7)
board = board [:]
legal = legal_moves(board)
for i in legal:
board[i] = computer
if winner(board) == computer:
return i
board = EMPTY
#Stopping human from winning
for i in legal_moves(board):
board [i] = human
if winner(board) == human:
return i
for i in best:
if i in legal_moves(board):
return i
def main ():
instructions_prompt ()
human, computer = start_prompt ()
turn = X
board = fresh_board()
request_move ()
display_board (board)
while not winner(board):
if turn == human:
square = request_move()
move = human_move (board, square)
board[move] = human
else:
move = computer_move(computer, board, human)
board[move] = computer
display_board(board)
turn = turn_switcher(turn)
main ()
raw_input ("Enter a key to end.")
TRACKBACK:
Traceback (most recent call last):
File "C:\Users\COMPAQ\Desktop\NoughtsCrosses.py", line 152, in <module>
main ()
File "C:\Users\COMPAQ\Desktop\NoughtsCrosses.py", line 147, in main
move = computer_move(computer, board, human)
File "C:\Users\COMPAQ\Desktop\NoughtsCrosses.py", line 118, in computer_move
board[i] = computer
TypeError: 'str' object does not support item assignment
You have your arguments mixed up for the function computer_move. On line 113, the arguments are in the order computer, board, human. However, on line 147, where computer_move is called, the order is board, computer, human.
Python gave you the confusing index error because Python strings are really just lists of characters. E.g.
>>> "foo"[2] == "o"
True
Update: You're getting this new error because of the last line of computer_move. It should be board[i] = EMPTY rather than board = EMPTY.

Categories

Resources