How to find tie game python - 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

Related

Python tic tac toe program closes on "3 1" input

My problem: Python tab closes on "3 1" input.
This code is heavily inspired by Hafeezul Kareem Shaik's tic-tac-toe game on geekflare.
My code:
import random
class TicTacToe:
def __init__(self):
self.board = []
def create_board(self):
for r0w in range(3):
row = []
for c0l in range(3):
row.append('-')
self.board.append(row)
def get_random_first_player(self):
return random.randint(0,1)
def fix_spot(self, row, col, player):
self.board[row][col] = player
def is_player_win(self, player):
win = None
n = len(self.board)
#checking rows
for r0w in range(n):
win = True
for c0l in range(n):
if self.board[r0w][c0l] != player:
win = False
break
if win:
return win
#checking columns
for r0w in range(n):
win = True
for c0l in range(n):
if self.board[c0l][r0w] != player:
win = False
break
if win:
return win
#checking diagonals
win = True
for i in range (n):
if self.board[i][i] != player:
win = False
break
if win:
return win
win = True
for i in range(n):
if self.board[r0w][n - 1 - r0w] != player:
win = False
break
if win:
return win
return False
for row in self.board:
for item in row:
if item == '-':
return False
return True
def is_board_filled(self):
for row in self.board:
for item in row:
if item == "-":
return False
return True
def swap_player_turn(self, player):
return 'X' if player =='O' else 'O'
def show_board(self):
for row in self.board:
for item in row:
print(item, end=" ")
print()
def start(self):
self.create_board()
player = 'X' if self.get_random_first_player() == 1 else 'O'
while True:
print(f"Player {player} turn")
self.show_board()
# user input
row, col = list(
map(int, input("Enter row and column numbers to fix spot: ").split()))
print()
#fixing spot
self.fix_spot(row - 1, col - 1, player)
#has current player won
if self.is_player_win(player):
print(f"{player} Wins!")
break
#is game a draw
if self.is_board_filled():
print("Draw!")
break
#swapping turn
player = self.swap_player_turn(player)
#final board
print()
self.show_board()
tic_tac_toe = TicTacToe()
tic_tac_toe.start()
The Tic_Tac-Toe Game worked up until I typed "3 1". I tested multiple games and it would always close after that input.
I have tried editing the scope of the following, as I believe that is what is causing it to malfunction
if win:
return win
return False
Unfortunately that has not fixed the problem. Any ideas or suggestions?
This code is so badly written that I wouldn't take it as an example for anything.
But if you really want to know why it ends on 3 1 as input, you should look here:
win = True
for i in range(n):
if self.board[r0w][n - 1 - r0w] != player:
win = False
break
if win:
return win
return False
Here r0w is not reset, it has the last value from the for loop, which is 2, and it's not changing in the loop, so there's only one check made, which is 3 1, translated to 2 0, which is the current player, so that's an instant win.
I assume this was supposed to be a loop to check the other diagonal, but it's clearly flawed.

python tic tac toe problems

I am new to coding and has recently started learning python. My first challenge is to build a tic tac toe game. Below are my codes for the game, everything worked fine except that when I want to restart the game or end the game, the loop won't break or the game cannot start.Could anyone figure out whats wrong with my codes. thank you!
Matrix = [[' ' for i in range(3)]for j in range(3)]
for i in Matrix:
print(i) #this is the 3x3 board
def check_done(value): #this is to check if the player has won the game
for a in range(0,3):
if Matrix[0][a]==Matrix[1][a]==Matrix[2][a]==value\
or Matrix[a][0]==Matrix[a][1]==Matrix[a][2]==value:
print ('won')
return True
#when the vertical column or horizontal row is equal, the
player won the game
if Matrix[0][0]==Matrix[1][1]==Matrix[2][2]==value\
or Matrix[2][0]==Matrix[1][1]==Matrix[0][2]==value:
print('won')
return True
#when the diagonal rows are equal, the player won the game
if ' ' not in Matrix[0] and ' ' not in Matrix[1] and ' ' not in
Matrix[2]:
print('draw')
return True
#when every grid is filled in the board and no win criteria is
fulfilled, it is a draw
return False
def replay(): #this is to determine if the player wants to restart or
end the game
command =input('Enter r to restart, or e to end game: ')
while True:
if command == 'r':
player1_input()
if command == 'e':
return
break
else:
print('Invalid command.')
def player1_input(): #this is an input function to allow players to
position their next move
print('Player 1 insert your name here')
name1=input()
print('player 2 insert your name here')
name2=input()
while True:
inputValid = False
while inputValid == False:
print(name1,'please place x coordinates')
xinput=int(input())
print(name1,'please place y coordinates')
yinput=int(input())
if yinput >= 0 & yinput <= 2 & xinput >=0 & xinput <= 2:
if Matrix[yinput][xinput] == ' ':
Matrix[yinput][xinput] = 'X'
for i in Matrix:
print(i)
if check_done('X'):
print(name1,'won')
replay()
inputValid = True
inputValid = False
while inputValid == False:
print(name2,'please place x coordinates')
xinput=int(input())
print(name2,'please place y coordinates')
yinput=int(input())
if yinput >= 0 & yinput <= 2 & xinput >=0 & xinput <= 2:
if Matrix[yinput][xinput] == ' ':
Matrix[yinput][xinput] = 'O'
for i in Matrix:
print(i)
if check_done('O'):
print(name2,'won')
replay()
inputValid = True
return True
The while loop for the main gameplay is running infinite.
To solve that, you can use a continue_game flag.
A simple example:
def player1_input():
# rest of the code
continue_game = True
while continue_game:
# logic for the game
continue_game = replay()
def replay():
# Returns true or false on user input.
while True:
command = raw_input('...')
if command == 'r':
return True
elif command == 'e':
return False
else:
print ('Invalid command')
The method replay can return a boolean as approriate based on user input.
Further, note that you have to re-initialize the matrix with empty values, if the game is supposed to be restarted.
It is difficult to read the code as it is posted. But it seems to me that your while True is an infinite cycle. I dont see any break that allows you to exit the while

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.

Python tic tac toe game

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()

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