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.
Related
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.
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.
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()
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
I'm writing a tic-tac-toe game for an assignment. It needs to use object-oriented programming and it has to be relatively smart - it needs to block the player's success. I'm having a lot of trouble with this.
My trouble comes from my rowabouttowin method: I did a very convoluted list comprehension and I don't think that I did it correctly.
What I want is a method that checks if the player is about to win the game horizontally (O _ O, O O _, or _ O O if mark = O) and, if the player is, returns the position where the computer should play.
Any help or advice on how best to approach this?
from random import randint
class TTT:
board = [[' ' for row in range(3)] for col in range(3)]
currentgame = []
def print(self):
"""Displays the current board."""
print("\n-----\n".join("|".join(row) for row in self.board))
def mark(self,pos,mark):
"""Method that places designated mark at designated position on the board."""
x,y = pos
self.board[x][y] = mark
def win(self,mark):
"""Method that checks if someone has won the game."""
if mark == self.board[0][0] == self.board[1][1] == self.board[2][2]:
return True
if mark == self.board[2][0] == self.board[1][1] == self.board[0][2]:
return True
elif mark == self.board[0][0] == self.board[1][0] == self.board[2][0]:
return True
elif mark == self.board[1][0] == self.board[1][1] == self.board[1][2]:
return True
elif mark == self.board[0][1] == self.board[1][1] == self.board[2][1]:
return True
elif mark == self.board[0][2] == self.board[1][2] == self.board[2][2]:
return True
elif mark == self.board[0][0] == self.board[0][1] == self.board[0][2]:
return True
elif mark == self.board[2][0] == self.board[2][1] == self.board[2][2]:
return True
else:
return False
def choose(self,mark):
"""The computer chooses a place to play. If the player is not about to win,
plays randomly. Otherwise, does a series of checks to see if the player is about
to win horizontally, vertically, or diagonally. I only have horizontal done."""
spotx = randint(0,2)
spoty = randint(0,2)
if self.rowabouttowin(mark):
self.mark((self.rowabouttowin(mark)),mark)
elif self.legalspace(spotx,spoty):
self.mark((spotx,spoty),mark)
else:
self.choose(mark)
def legalspace(self,spotx,spoty):
"""Returns True if the provided spot is empty."""
if self.board[spotx][spoty] == ' ':
return True
else:
return False
def rowabouttowin(self,mark):
"""If the player is about to win via a horizontal 3-in-a-row,
returns location where the computer should play"""
for row in range(3):
if any(' ' == self.board[row][1] for i in range(3)) and any(self.board[row][i] == self.board[row][j] for i in range(3) for j in range(3)):
if self.board[row][i] == ' ' : yield(self.board[row][i % 3], self.board[row][i])
This currently gives this error message:
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
x.choose('x')
File "/Users/richiehoffman/Documents/Python Programs/Tic Tac Toe.py", line 40, in choose
self.mark((self.rowabouttowin(mark)),mark)
File "/Users/richiehoffman/Documents/Python Programs/Tic Tac Toe.py", line 11, in mark
x,y = pos
File "/Users/richiehoffman/Documents/Python Programs/Tic Tac Toe.py", line 61, in rowabouttowin
if self.board[row][i] == ' ' : yield(self.board[row][i % 3], self.board[row][i])
NameError: global name 'i' is not defined
A few tips:
You're using class variables, not instance variables, so look up the difference. I changed your class to use instance variables, as the variables that you set should belong in an instance.
Consider making things more readable.
Use __str__ to make the printable version of your class. That way, you can do print(class_instance) and it'll come out all nice.
Here's what I changed:
from random import randint
class TTT(object):
def __init__(self):
self.board = [[' ' for row in range(3)] for col in range(3)]
self.currentgame = []
def __str__(self):
"""Displays the current board."""
return "\n-----\n".join("|".join(row) for row in self.board)
def mark(self, pos, mark):
"""Method that places designated mark at designated position on the board."""
x, y = pos
self.board[x][y] = mark
def win(self, mark):
"""Method that checks if someone has won the game."""
for row in self.board:
if row[0] == row[1] == row[2]:
return True
for i in range(3):
if self.board[0][i] == self.board[1][i] == self.board[2][i]:
return True
if board[0][0] == board[1][1] == board[2][2]:
return True
elif board[0][2] == board[1][1] == board[2][0]:
return True
else:
return False
def choose(self, mark):
"""The computer chooses a place to play. If the player is not about to win,
plays randomly. Otherwise, does a series of checks to see if the player is about
to win horizontally, vertically, or diagonally. I only have horizontal done."""
spotx = randint(0, 2)
spoty = randint(0, 2)
if self.rowabouttowin(mark):
self.mark((self.rowabouttowin(mark)), mark)
elif self.legalspace(spotx, spoty):
self.mark((spotx, spoty), mark)
else:
self.choose(mark)
def legalspace(self, spotx, spoty):
"""Returns True if the provided spot is empty."""
return self.board[spotx][spoty] == ' '
def rowabouttowin(self, mark):
"""If the player is about to win via a horizontal 3-in-a-row,
returns location where the computer should play"""
for row in range(3):
check_one = any(' ' == self.board[row][1] for i in range(3))
check_two = any(self.board[row][i] == self.board[row][j] for i in range(3) for j in range(3))
# I have no idea what this code does
if self.board[row][i] == ' ' :
yield self.board[row][i % 3], self.board[row][i]