Tuple index out of range - python

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.

Related

List value being overwritten even though I am checking for it

I'm new to python and writing my first project. I'm trying to implement a check that if a space is already occupied, not to move there. I can't seem to figure out why my move_player method overwrites the index value of the board even though I am explicitly checking it (If it is O's turn and X has already been placed in the index O is trying to move to, it just overwrites it). I have tried hard coding the check for 'X' and 'O' instead of player.player as well but can't seem to figure it out. Does it have to do something with how Python works or am I implementing it wrong?
class Player:
def __init__(self, player):
self.player = player
class Board:
def __init__(self):
self.board = [[' ' for i in range(3)] for j in range(3)]
def display_board(self):
print('---------')
for row in self.board:
print('| ', end='')
for col in row:
print(f'{col} ', end='')
print('|')
print('---------')
def move_player(self, player):
try:
p1 = Player('X')
p2 = Player('O')
coordinates = [int(i) for i in input("Enter coordinates for move: ").split()]
xCoordinate = coordinates[0]
yCoordinate = coordinates[1]
if ((self.board[xCoordinate][yCoordinate] == p1.player) or
(self.board[xCoordinate][yCoordinate] == p2.player)):
print("That space is occupied, please choose another one.")
self.move_player(player)
else:
self.board[xCoordinate - 1][yCoordinate - 1] = player.player
except (ValueError, IndexError):
print("Please only enter numbers between 1 and 3.")
self.move_player(player)
def has_won(self, player):
if self.check_diagonal(player):
return True
elif self.check_across(player):
return True
elif self.check_down(player):
return True
return False
if __name__ == '__main__':
board = Board()
player1 = Player('X')
player2 = Player('O')
player = player1
while True:
board.display_board()
board.move_player(player)
if board.has_won(player):
board.display_board()
print(f'{player.player} wins!!!')
break
if player == player1:
player = player2
else:
player = player1
The code is very convoluted but from what I can see:
if ((self.board[xCoordinate][yCoordinate] == p1.player) or
(self.board[xCoordinate][yCoordinate] == p2.player)):
...
self.board[xCoordinate - 1][yCoordinate - 1] = player.player
You are checking [x,y] but assigning to [x-1,y-1].

I'm stuck in the creating of a Board game in python

I have an excercise to do and I'm stuck. It's the board game Alak, not much known, that I have to code in python. I can link the execrcise with the rules so you can help me better. The code has the main part and the library with all the procedures and function.
from Library_alak import *
n = 0
while n < 1:
n = int(input('Saisir nombre de case strictement positif : '))
loop = True
player = 1
player2 = 2
removed = [-1]
board = newboard(n)
display(board, n)
while loop:
i = select(board, n, player, removed)
print(i)
board = put(board, player, i)
display(board, n)
capture(board, n, player, player2)
loop = True if again(board, n, player, removed) is True else False
if player == 1 and loop:
player, player2 = 2, 1
elif player == 2 and loop:
player, player2 = 1, 2
win(board, n)
print(win(board, n))
And here is the library:
def newboard(n):
board = ([0] * n)
return board
def display(board, n):
for i in range(n):
if board[i] == 1:
print('X', end=' ')
elif board[i] == 2:
print('O', end=' ')
else:
print(' . ', end=' ')
def capture(board, n, player, player2):
for place in range(n):
if place == player:
place_beginning = place
while board[place] != player:
place_end = place
if board[place + x] == player:
return board
else:
return board
def again(board, n, player, removed):
for p in board(0):
if p == 0:
if p not in removed:
return True
else:
return False
def possible(n, removed, player, i, board):
for p in range(n + 1):
if p == 1:
if board[p-1] == 0:
if p not in removed:
return True
else:
return False
def win(board, n):
piecesp1 = 0
piecesp2 = 0
for i in board(0):
if i == 1:
piecesp1 += 1
else:
piecesp2 += 1
if piecesp1 > piecesp2:
print('Victory : Player 1')
elif piecesp2 > piecesp1:
print('Victory : Player 2')
else:
return 'Equality'
def select(board, n, player, removed):
loop = True
while loop:
print('player', player)
i = int(input('Enter number of boxes : '))
loop = False if possible(n, removed, player, i, board)is True else True
return i
def put(board, player, i):
i -= 1
if board[i] == 0:
if player == 1:
board[i] = 1
return board
else:
board[i] = 2
return board
else:
put(board, player, i)
So my problems here are that I have few errors, the first one is that when I enter the number '1' when asked to enter a number of boxes ( which is the place to play on ) nothing happens. Then when entering any other number, either the error is : if board[place + x] == player:
NameError: name 'x' is not defined
or there seems to be a problem with the : if board[place + x] == player:
NameError: name 'x' is not defined
I would appreciate a lot if anyone could help me. I'm conscious that it might not be as detailed as it should be and that you maybe don't get it all but you can contact me for more.
Rules of the Alak game:
Black and white take turns placing stones on the line. Unlike Go, this placement is compulsory if a move is available; if no move is possible, the game is over.
No stone may be placed in a location occupied by another stone, or in a location where a stone of your own colour has just been removed. The latter condition keeps the game from entering a neverending loop of stone placement and capture, known in Go as ko.
If placing a stone causes one or two groups of enemy stones to no longer have any adjacent empty spaces--liberties, as in Go--then those stones are removed. As the above rule states, the opponent may not play in those locations on their following turn.
If placing a stone causes one or two groups of your own colour to no longer have any liberties, the stones are not suicided, but instead are safe and not removed from play.
You shouldn't use "player2" as a variable, there's an easier way, just use "player" which take the value 1 or 2 according to the player. You know, something like that : player = 1 if x%2==0 else 2
and x is just a increasing int from 0 until the end of the game.

Do while loops have local variables in Python?

I am trying to use a while statement like so:
o = 0
while o == 0:
try:
n = int(raw_input("Which number do you want to begin with?"))
o = 1
except:
o = 0
print "Please use a valid number."
However, when I try to use variable n later, it gives me the "local variable 'n' referenced before assignment' UnboundLocalError. That means that n cannot be recognized as a variable in the def I am using, because it only exists in the while statement? Is this possible?
The whole code:
import time
from sys import argv
import os
os.system("cls")
print "Welcome to Number counter 2.0!"
a = True
def program():
global a
if a == False:
os.system("cls")
o = 0
while o == 0:
try:
n = int(raw_input("Which number do you want to begin with?"))
o = 1
except:
o = 0
print "Please use a valid number."
if n == "/historyKeep false":
if a == False:
print "Command historyKeep is already set to false."
else:
a = False
print "Command set successfully."
elif n == "/historyKeep true":
if a == True:
print "Command historyKeep is already set to true."
else:
a = True
print "Command set successfully."
if n == "/historyKeep false":
n = raw_input("Which number do you want to begin with?")
elif n == "/historyKeep true":
n = raw_input("Which number do you want to begin with?")
d = raw_input("How many seconds between each number?")
d = int(d)
total_s = n * d
while n > 0:
print n
time.sleep(d)
n = n - 1
print "Done in", total_s, "seconds in total!"
end_q = raw_input("Exit or retry? (e/r)")
if end_q == "e":
os.system("cls")
print "Exiting."
time.sleep(0.5)
os.system("cls")
print "Exiting.."
time.sleep(0.5)
os.system("cls")
print "Exiting..."
time.sleep(0.5)
os.system("cls")
exit(0)
elif end_q == "r":
program()
program()
You set a = True at the beginning. You then test if a == False and only set n if it is. But then you test n == "/history.... n has not been set at this point.
You need to make sure n is assigned before you use it. It is not enough to just mention it in a branch that is not taken.
n is not defined in the scope that you are trying to use it to fix this define it outside of the while loop and the if statement the while loop is in:
global a
n = 0
Then when you ask the user for what number to start with, that value will replace 0, and you should be good to go. Also instead of declaring global a, why not just make a an input argument for the program() function?
Just to make sure, declare n outside of the loop first:
n = None
while True:
try:
n = int(raw_input("Text..."))
break
except:
print("Please enter a valid number!")
Note: Usually, you would use break to exit a loop. This is because your method requires an extra variable, which uses more memory (not much, but if you keep doing it, it will stack up).

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

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

Categories

Resources