I didn't know what sort of title to give this post. I'm a new to python, and I'm 4 weeks into my first class. I wrote a Tic Tac Toe program with an AI, but the AI is weird. It behaves differently at my home PC than at my school PC. At school, the program just crashes once it become's the computers turn for a move. It doesn't even draw the boxes. At home the computer just doesn't move. My home computer is significantly better than my school computer by the way. Also it's running Windows 10 TP vs. Windows 7 at school. I showed my teacher and he couldn't tell me the problem. This is my code. Sorry it's all one file and it's all the code I have because I have no idea where the problem is. Also I'm using PyProcessing which is basically a python IDE that provides some simple ways for graphics. The setup() function runs automatically at the beginning and so does draw() but I'm not sure when or what causes the draw() function to run.
board = [[None, None, None],
[None, None, None],
[None, None, None]]
turn = 0
player_letter = ""
computer_letter = ""
game_ended = False
def setup():
global game_ended
global player_letter
global turn
global board
global computer_letter
size(300,300)
drawBoard(board)
drawLetters(board)
turn = 0
if turn == 0:
player_letter = "X"
computer_letter = "O"
else:
player_letter = "O"
computer_letter = "X"
def check_win(board, letter):
if board[0][0] == letter and board[0][1] == letter and board[0][2] == letter:
return True
elif board[1][0] == letter and board[1][1] == letter and board[1][2] == letter:
return True
elif board[2][0] == letter and board[2][1] == letter and board[2][2] == letter:
return True
elif board[0][0] == letter and board[1][0] == letter and board[2][0] == letter:
return True
elif board[0][1] == letter and board[1][1] == letter and board[2][1] == letter:
return True
elif board[0][2] == letter and board[1][2] == letter and board[2][2] == letter:
return True
elif board[0][0] == letter and board[1][1] == letter and board[2][2] == letter:
return True
elif board[2][0] == letter and board[1][1] == letter and board[0][2] == letter:
return True
else:
return False
def run_player_turn(player_letter):
global board
if mousePressed and board[mouseY//100][mouseX//100] == None:
board[mouseY//100][mouseX//100] = player_letter
return True
else:
return False
def getPotentialWin(computer_letter, player_letter):
global board
check1 = [board[0][0], board[0][1], board[0][2]]
check2 = [board[1][0], board[1][1], board[1][2]]
check3 = [board[2][0], board[2][1], board[2][2]]
check4 = [board[0][0], board[1][0], board[2][0]]
check5 = [board[0][1], board[1][1], board[2][1]]
check6 = [board[0][2], board[1][2], board[2][2]]
check7 = [board[0][0], board[1][1], board[2][2]]
check8 = [board[2][0], board[1][1], board[0][2]]
checks = [check1, check2, check3, check4, check5, check6, check7, check8]
cletters = 0
pletters = 0
letters = 0
for check in checks:
for letter in check:
if letter != None:
letters += 1
if letter == computer_letter:
cletters += 1
else:
pletters += 1
if cletters == 2 and letters == 2:
for letter in check:
if letter == None:
return letter
return None
def getPotentialLoss(computer_letter, player_letter):
global board
check1 = [board[0][0], board[0][1], board[0][2]]
check2 = [board[1][0], board[1][1], board[1][2]]
check3 = [board[2][0], board[2][1], board[2][2]]
check4 = [board[0][0], board[1][0], board[2][0]]
check5 = [board[0][1], board[1][1], board[2][1]]
check6 = [board[0][2], board[1][2], board[2][2]]
check7 = [board[0][0], board[1][1], board[2][2]]
check8 = [board[2][0], board[1][1], board[0][2]]
checks = [check1, check2, check3, check4, check5, check6, check7, check8]
cletters = 0
pletters = 0
letters = 0
for check in checks:
for letter in check:
if letter != None:
letters += 1
if letter == player_letter:
pletters += 1
else:
cletters += 1
if pletters == 2 and letters == 2:
for letter in check:
if letter == None:
return letter
return None
def draw():
global board
global turn
global player_letter
global computer_letter
if (not check_win(board, player_letter)) and (not check_win(board, computer_letter)):
if turn == 0:
if run_player_turn(player_letter):
turn = 1
else:
if run_computer_turn(computer_letter):
turn = 0
drawLetters(board)
def get_starting_player():
random_num = int(random(2))
return random_num
def drawLetters(board):
for row in range(len(board)):
for col in range(len(board[0])):
if board[row][col] != None:
textSize(32)
fill(0,0,0)
text(board[row][col], col*100+25, row*100+75)
def drawBoard(board):
for y in range(len(board)):
for x in range(len(board[0])):
rect(x * 100, y * 100, 100, 100)
def run_computer_turn(computer_letter):
global board
global turn
global cHasGone
global player_letter
potentialLoss = getPotentialLoss(computer_letter, player_letter)
potentialWin = getPotentialWin(computer_letter, player_letter)
if potentialLoss != None:
potentialLoss = computer_letter
return True
elif potentialWin != None:
potentialWin = computer_letter
return True
else:
found = False
while not found:
x = int(random(0, 3))
y = int(random(0, 3))
if board[x][y] == None:
board[x][y] == computer_letter
found = True
return True
return True
def checkAvailibleWin(row, col):
print("Hi")
def getAdjacents(row, col):
adjs = [[None, None, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None]]
row += 1
col += 1
adjs[row - 1][col - 1] = True;
adjs[row - 1][col] = True;
adjs[row - 1][col + 1] = True;
adjs[row][col - 1] = True;
adjs[row][col] = True;
adjs[row][col + 1] = True;
adjs[row + 1][col - 1] = True;
adjs[row + 1][col] = True;
adjs[row + 1][col + 1] = True;
trueAdjs = [[None, None, None],
[None, None, None],
[None, None, None]]
for y in adjs:
for x in adjs:
if((x > 0 and x < 3) and (y > 0 and y < 1)):
trueAdjs[y-1][x-1] = True
return trueAdjs
Related
I am trying to create a tictactoe AI for the CS50AI's 1st assignment. I get the error which you will see below. This means action in the result function is None somehow. But the issue is it is a mouse click by me how could it be N one?
my function gives the following error:
Traceback (most recent call last):
File "c:\Users\ahmet\Desktop\tictactoe\runner.py", line 116, in <module>
board = ttt.result(board, move)
File "c:\Users\ahmet\Desktop\tictactoe\tictactoe.py", line 69, in result
raise Exception("Invalid action")
Exception: Invalid action
So action parameter of result becomes None at some point but I couldn't understand why any help ?
This is the tictactoe.py file until the result function. Thanks for all the help.
"""
Tic Tac Toe Player
"""
import math
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def initial_stateh():
return [[X, X, X],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def initial_statetie():
return [[O, X, O],
[X, O, X],
[X, X, O]]
def initial_stateboş():
return [[EMPTY, O, O],
[X, O, EMPTY],
[X, X, EMPTY]]
def player(board):
numx = 0
numo = 0
for i in range(3):
for j in range(3):
if board[i][j] == X:
numx = numx + 1
if board[i][j] == O:
numo = numo + 1
if numx == numo:
return X
elif numx > numo:
return O
def actions(board):
possiblemoves = set()
for i in range(3):
for j in range(3):
if board[i][j] == EMPTY:
possiblemoves.add((i,j))
return possiblemoves
def result(board, action):
"""
Returns the board that results from making move (i, j) on the board.
"""
if action is None:
raise Exception("Invalid action")
copyboard = [row[:] for row in board]
if copyboard[ action[0] ][ action[1] ] is EMPTY:
#print(action[0],action[1])
copyboard[ action[0] ][ action[1] ] = player(board)
return copyboard
else:
raise Exception("Move is not possible")
def horizontal(board):
for x in range(3):
if (board[x][0] == board[x][1] and board[x][1] == board[x][2]) and board[x][0] != None:
pl = board[x][0]
return pl
return None
def vertical(board):
for y in range(3):
if (board[0][y] == board[1][y] and board[1][y] == board[2][y]) and board[1][y] != None:
pl = board[1][y]
return pl
return None
def diagonally(board):
if (board[0][0] == board[1][1] and board[1][1]==board[2][2]) and board[0][0] != None:
return board[0][0]
if (board[0][2] == board[1][1] and board[1][1]==board[2][0]) and board[0][2] != None:
return board[0][2]
else:
return None
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
if vertical(board) != None :
return vertical(board)
if horizontal(board) != None :
return horizontal(board)
if diagonally(board) != None :
return diagonally(board)
else:
return None
def arethereanyspace(board):
space = 0
for row in board:
for item in row:
if item == None:
space +=1
else:
return space
def tie(board):
if winner(board) == None and arethereanyspace(board) == None:
return True
else:
return False
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
if tie(board) == True :
return True
if winner(board) != None:
return True
else:
return False
def utility(board):
"""
Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
"""
if winner(board) == X:
return 1
if winner(board) == O:
return -1
if tie(board):
return 0
def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
if terminal(board) == True: #if the game has ended
return None
for move in actions(board):
if winner(result(board, move)) != None:#if the move is a winning move, do it!
return move
i = move[0]
j = move[1]
if j+1 <= 2 and board[i][j+1] == player(board): #check horizontal
return move
if j-1 >= 0 and board[i][j-1] == player(board): #check horizontal
return move
if i+1 <= 2 and board[i+1][j] == player(board): #check vertical
return move
if i-1 >= 0 and board[i-1][j] == player(board): #check vertical
return move
if (j+1<=2) and (i+1<= 2) and board[i+1][j+1] == player(board): #checking the diag
return move
if (i-1 >= 0) and (j-1 >= 0) and board[i-1][j-1] == player(board): #checking the diag
return move
if (i-1 >= 0) and (j+1 <= 2) and board[i-1][j+1] == player(board):
return move
if (i+1 <= 2) and (j-1 >= 0) and board[i+1][j-1] == player(board):
return move
I found the answer: It's because of my minimax function. Unless there is a winning move it returns none. I forgot to code the rest of it. Thanks for all the help though.
I am currently trying to make a Tic Tac Toe game with minimax implemented in Python. Another feature that I'm trying to implement is different board sizes. But overall, unfortunately, the algorithm is not working.
As a beginner, this is not a surprise for me, but this case seems hopeless. I tried tweaking quite a lot of things (may seem like a lot just to me) just to end up with the same result - the computer filling up the fields from top left to bottom right.
#Sprawdzenie czy ktos wygral w poziomie lub pionie / straight line check
def winLine(line, letter):
return all(n == letter for n in line)
#Utworzenie nowej listy z elementow przekatnych / diagonal check
def winDiagonal(board, letter):
arr = []
tArr = []
for n in range(boardSize):
arr.append(board[n][n])
tArr.append(board[n][boardSize-n-1])
if winLine(arr, letter):
return True
elif winLine(tArr, letter):
return True
else:
return False
def checkWinner (board):
#Liczenie wolnych pol / checking the available fields
openSpots = 9
for n in range(boardSize):
for m in range(boardSize):
if board[n][m] == '0':
openSpots += 1
#Transpozycja planszy, by mozna bylo latwo zastosowac winLine na kolumach / transposition of the board
for letter in (person, ai):
transPos = list(zip(*board))
#Sprawdzanie w poziomie / horizontal check
if any(winLine(row, letter) for row in board):
#print('winline horizontal')
return letter
#Sprawdzanie w pionie / vertical check
elif any (winLine(col, letter) for col in transPos):
#print('winline vertical')
return letter
#Sprawdzanie po przekatnych / diagonal check
elif winDiagonal(board, letter):
return letter
elif openSpots == 0: return 'tie'
else: return 'none'
#Funkcja sprawdzajaca czy dane pole jest wolne / checks whether the field is available
def available (row, col):
global board
#Sprawdzenie czy pole jest wolne
if board[row][col] == '0':
return True
else:
return False
#Stale dla algorytmu minimax / minimax initial scores to compare against
minTarget = float('inf')
maxTarget = float('-inf')
#Slownik z wartosciami liczbowi dla wynikow, komputer maksymalizuje / a dictionary with scores for particular results
scores = {
'X': 10,
'O': -10,
'tie': 0
}
#Algorytm minimax
def minimax(myBoard, depth, maximizes):
#Sprawdzenie czy zaszla wygrana lub remis / Checking whether there is a win or tie
res = checkWinner(myBoard)
if (res != 'none'):
return scores[res]
#Gracz maksymalizujacy/ Maximizing player
elif maximizes == True:
bestScoreMax = maxTarget
for n in range(boardSize):
for m in range(boardSize):
if board[n][m] == '0':
board[n][m] = person
score = minimax(board, depth + 1, False)
board[n][m] = '0'
bestScoreMax = max([score, bestScoreMax])
return bestScoreMax
#Gracz minimalizujacy / minimizing player
elif maximizes == False:
bestScoreMin = minTarget
for n in range(boardSize):
for m in range(boardSize):
if board[n][m] == '0':
board[n][m] = ai
score = minimax(board, depth + 1, True)
board[n][m] = '0'
bestScoreMin = min([score, bestScoreMin])
return bestScoreMin
def makeMove(row, col):
global board
board[row][col] = ai
def computedMove():
global board
myBoard = board
computedTarget = maxTarget
moveX = 2
moveY = 2
for n in range(boardSize):
for m in range(boardSize):
if myBoard[n][m] == '0':
score = minimax(myBoard, 0, True)
if score > computedTarget:
computedTarget = score
moveX = n
moveY = m
makeMove(moveX, moveY)
#print(str(move.x) + ' ' + str(move.y))
# Funkcja pobierajaca ruch uzytkownika / player input for the move
def getPlayerMove():
global board
res = input('Please type in your move on the form \"x y\", x being the number of the row and y the number of the column of your choosing.\n')
col, row = res.split(" ")
row = int(row)
col = int(col)
if available(row-1, col-1):
board[row-1][col-1] = person
else:
print('You cannot make that move')
getPlayerMove()
def drawBoard():
global board
for n in range(boardSize):
for m in range(boardSize):
if board[n][m] == '0':
print(' - ', end='')
else:
print(' '+board[n][m]+' ', end='')
print('\n')
#Zmienna powiadamiajaca o stanie rozgrywki / variable indicating the state of the game
playing = False
# initializing the variable
boardSize = 0
# initializing the players
person = 'X'
ai = 'O'
#Gracz posiadajacy ruch (a takze rozpoczynajacy) / player who is playing at the moment
currentPlayer = ''
while True:
currentPlayer = person
boardSize = int(input("Please enter the size of the board. (one side)\n"))
global board
board = [['0' for i in range(boardSize)] for i in range(boardSize)]
print("You go first.")
playing = True
while playing:
if currentPlayer == person:
drawBoard()
getPlayerMove()
if checkWinner(board) == person:
drawBoard()
print("Yaay, you won!")
playing = False
else:
if checkWinner(board) == 'tie':
drawBoard()
print('It\'s a tie!')
break
else:
currentPlayer = ai
elif currentPlayer == ai:
computedMove()
if checkWinner(board) == ai:
drawBoard()
print('You lose!')
playing = False
else:
if checkWinner(board) == 'tie':
drawBoard()
print('It\'s a tie!')
break
else:
currentPlayer = person
if not input('Do you want to play again?').lower().startswith('y'):
break
In computedMove, you should first play the ai move then check the scores.
def computedMove():
global board
myBoard = board
computedTarget = maxTarget
moveX = 2
moveY = 2
for n in range(boardSize):
for m in range(boardSize):
if myBoard[n][m] == '0':
myBoard[n][m] = ai #This is added
score = minimax(myBoard, 0, True)
if score > computedTarget:
computedTarget = score
moveX = n
moveY = m
makeMove(moveX, moveY)
Also in minimax function, you should use same variable for myBoard and board.
I was programming a simple Connect 4 game however I need to add global variables
# Board(0:6, 0:7) : str (but ignore row 0 and column
0)
# ThisPlayer : str[1]
# GameFinished, WinnerFound : bool
# ColumnNumber : int
# ValidColumn, ValidRow : int
which im stuck on as I cant remember how to define global booleans etc (global variables are above)
when I run the code it gives me the error code (Board is not defined) how can I add the global variables so my program runs ?
Code is below
Board[0:6][0:7]
Blank = '.'
def InititialiseBoard():
Board = [[Blank for i in range(7)]
for j in range(6)]
def SetUpGame():
ThisPlayer = 'o'
GameFinished = False
def OutputBoard():
for Row in range(6 , 0 , -1):
for Column in range(7):
print(Board[Row][Column] , end = '')
print()
def ColumnNumberValud():
Valid = False
if ColumnNumber >= 1 and CalumnNumber <= 7:
if Board[6][ColumnNumber] == Blank:
Valid = True
return Valid
def ThisPlayerChoosesColumn():
print('Player ' + ThisPlayer + ' turn.')
while ColumnNumberValid == False:
print('Enter Valid Column Number')
ColumnNumber = int(input('Enter Column Number: '))
return ColumnNumber
def ThisPlayerMakesMove():
ValidColumn = ThisPlayerChoosesColumn()
ValidRow = FindNextFreePositionInColumn()
Board[ValidRow][ValidColumn] = ThisPlayer
def FindNextFreePositionInColumn():
ThisRow = 1
while Board[ThisRow][ValidColumn] != Blank:
ThisRow = ThisRow + 1
return ThisRow
def CheckHorizontalLineInValidRow():
for i in range(4):
if Board[ValidRow][i] == ThisPlayer and Board[ValidRow][i+1] == ThisPlayer and Board[ValidRow][i+2] == ThisPlayer and Board[ValidRow][i+3] == ThisPlayer:
WinnerFound = True
def CheckVerticalLineInValidRow():
if ValidRow == 4 or ValidRow == 5 or ValidRow == 6:
if Board[ValidRow][ValidColumn] == ThisPlayer and Board[ValidRow - 1][ValidColumn] == ThisPlayer and Board[ValidRow - 2][ValidColumn] == ThisPlayer and Board[ValidRow - 3 ][ValidColumn] == ThisPlayer:
WinnerFound = True
def CheckForFullBoard():
BlankFound = False
ThisRow = 0
while ThisRow !=6 or BlankFound == False:
ThisColumn = 0
ThisRow = ThisRow + 1
while ThisColumn != 7 or BlankFound == True:
ThisColumn = ThisColumn + 1
if Board[ThisRow][ThisColumn] == Blank:
BlankFound = True
if Blankfound == False:
print('Draw')
GameFinished = True
def CheckIfThisPlayerHasWon():
WinnerFound = False
CheckHorizontalLineInValidRow()
if WinnerFound == False:
CheckVerticalLineInValidColumn()
if WinnerFound == True:
GameFinished = True
print(ThisPlayer , 'Winner')
else:
CheckForFullBoard()
To use global variables:
global x
x = 1
def foo():
global x
x+=1
print(x)
foo()
print(x)
I would recommend avoiding global variables and use class variables instead.
class yourclass():
def__init__(self):
self.x = 1
def foo(self):
self.x+=1
def print_value(self):
print(self.x)
if __name__=='__main__':
test = yourclass()
test.print_value()
test.foo()
test.print_value()
I'm trying to build a Snake game using python, but I'm struggling with the input system. In the snake game, the snake walks through the same direction until someone change his direction.
The way I did was stopping the snake from moving while waits for the next key, but that's not what I want. The snake must walk to the same direction until receive an input to change direction.
How to do the get the key so the snake changes his direction while moving it through the screen and colliding with objects?
import os
from msvcrt import getch
class SnakeGame(object):
screen = None
def __init__(self, rows_count, column_count):
self.screen = self.initialize_screen(rows_count, column_count)
self.collided = False
def initialize_screen(self, rows_count, column_count):
#creates the 2D list with 0 in all values
screen = [[0 for x in range(column_count)] for y in range(rows_count)]
#get the rows
for row in range(len(screen)):
if row == 0 or row == len(screen) - 1:
screen[row] = self.add_same_value_entire_list(screen[row], 1)
else:
for column in range(len(screen[row])):
if column == 0 or column == len(screen[row]) - 1:
screen[row][column] = 1
return screen
def add_same_value_entire_list(self, list, value):
populatedList = [value for i in range(len(list))]
return populatedList
def print_screen(self):
screen_text = ''
for row in self.screen:
for column in row:
screen_text = screen_text + self.translated_value(column)
screen_text = screen_text + '\n'
return screen_text
def translated_value(self, value):
if value == 1:
return '#'
elif value == 2:
return '*'
elif value == -1: #snake body
return 'O'
elif value == -2: #moving left snake head left <----
return '<'
elif value == -3: #moving right snake head right ---->
return '>'
elif value == -4: #moving down
return 'V'
elif value == -5: #moving up
return '^'
else:
return ' '
def play(self):
player = Player()
key_pressed = 9999
self.add_player_to_screen(player)
while(self.defeated() is not True and key_pressed != 27):
self.clear()
print(self.print_screen())
key_pressed = self.read_key()
player.move(self.translate_key(key_pressed))
self.add_player_to_screen(player)
def read_key(self):
return ord(getch())
def add_player_to_screen(self, player):
print(player.location_x)
print(player.location_y)
if(player.position_cordination == 'E'):
self.screen[player.location_x][player.location_y - 1] = 0
elif (player.position_cordination == 'W'):
self.screen[player.location_x][player.location_y + 1] = 0
elif (player.position_cordination == 'N'):
self.screen[player.location_x + 1][player.location_y] = 0
elif (player.position_cordination == 'S'):
self.screen[player.location_x - 1][player.location_y] = 0
if(self.screen[player.location_x][player.location_y] == 0):
self.screen[player.location_x][player.location_y] = player.body
elif(self.screen[player.location_x][player.location_y] < 0):
self.collided = True
def translate_key(self, key):
print (key)
if (key == 224):
key = ord(getch())
print(key)
if (key == 72):
return 'N'
elif (key == 80):
return 'S'
elif (key == 75):
return 'W'
elif (key == 77):
return 'E'
else:
pass
def defeated(self):
return self.collided
def clear(self):
os.system('cls' if os.name=='nt' else 'clear')
class Player(object):
def __init__(self):
self.nodes_size = 1
self.position_cordination = 'E'
self.last_cordination = 'E'
self.location_x = 4
self.location_y = 4
self.body = -3
def draw(self):
body = ''
for index in range(self.nodes_size):
if(index == 0 and self.position_cordination == 'E'):
body = '>'
elif(index == 0 and self.position_cordination == 'W'):
body = '<'
elif(index == 0 and self.position_cordination == 'N'):
body = '^'
elif(index == 0 and self.position_cordination == 'S'):
body = 'V'
else:
body += '-'
return body
def move(self, cordination):
print("Cordinations x = " + str(self.location_x) + " y = " + str(self.location_y))
if (self.position_cordination != 'S' and cordination == 'N'):
self.location_x -= 1
self.body = -5
elif (self.position_cordination != 'N' and cordination == 'S'):
self.location_x +=1
self.body = -4
elif (self.position_cordination != 'W' and cordination == 'E'):
self.location_y += 1
self.body = -3
elif (self.position_cordination != 'E' and cordination == 'W'):
self.location_y -= 1
self.body = -2
else:
pass
self.position_cordination = cordination
print("Cordinations x = " + str(self.location_x) + " y = " + str(self.location_y))
snake = SnakeGame(32, 32)
snake.play()
I have coded a game of noughts and crosses, and am using a while loop to run the game. However, I must be doing something wrong as I cannot get it to print 'You win' or 'You lose' when a row/column/diagonal of X or O is on the board. I know the function that checks the board works as I have tested it on its own, by putting Xs in the board manually, but when playing the game normally it completely disregards any Xs or Os in 3. Here is the code, sorry it's abit long. Thanks
import random
board = [
['1','-','-','-'],
['2','-','-','-'],
['3','-','-','-'],
['#','1','2','3'],
[' ',' ',' ',' ']
]
rows = {
'top':
board[0][1:],
'mid':
board[1][1:],
'bottom':
board[2][1:]
}
cols = {
'left':
[board[0][1],
board[1][1],
board[2][1]],
'mid':
[board[0][2],
board[1][2],
board[2][2]],
'right':
[board[0][3],
board[1][3],
board[2][3]]
}
diags = {
'top-bottom':
[board[0][1],
board[1][2],
board[2][3]],
'bottom-top':
[board[2][1],
board[1][2],
board[0][3]]
}
gamestate = 1
def print_board(board):
for i in board:
print " ".join(i)
def win_check(rows,cols,diags):
plrWin = ['X','X','X']
cpuWin = ['O','O','O']
global gamestate
for i in rows.values():
if i == plrWin:
return True
gamestate = 0
elif i == cpuWin:
return False
gamestate = 0
for x in cols.values():
if x == plrWin:
return True
gamestate = 0
elif x == cpuWin:
return False
gamestate = 0
for y in diags.values():
if y == plrWin:
return True
gamestate = 0
elif y == cpuWin:
return False
gamestate = 0
def game_entry():
print "Your turn."
coordY = input("Guess column: ")
coordX = input("Guess row: ")
board[coordX - 1][coordY] = 'X'
def random_location():
while True:
cpuX = random.randint(1,3)
cpuY = random.randint(1,3)
if (board[cpuX - 1][cpuY] == 'X') or (board[cpuX - 1][cpuY] == 'O'):
continue
else:
board[cpuX - 1][cpuY] = 'O'
break
while gamestate == 1:
print_board(board)
game_entry()
random_location()
if win_check(rows,cols,diags) == True:
print "You win!"
gamestate = 0
break
elif win_check(rows,cols,diags) == False:
print "You lose."
gamestate = 0
break
else:
continue
Your problem is with all of the rows and cols dictionaries:
>>> l = [[1, 2, 3], [4, 5, 6]]
>>> x = l[0][1:]
>>> x
[2, 3]
>>> l[0][1] = 4
>>> x
[2, 3]
As you can see, they don't update when the board is changed. You'll have to find another way of doing this.
I would just use a few loops and check the diagonals manually:
def has_someone_won(board):
# Rows
for row in board:
if row[0] == row[1] == row[2] != '-':
return True
# Columns
for i in range(3):
if board[0][i] == board[1][i] == board[2][i] != '-':
return True
# Diagonal 1
if board[0][0] == board[1][1] == board[2][2] != '-':
return True
# Diagonal 2
if board[2][0] == board[1][1] == board[0][2] != '-':
return True
# There's no winner
return False