i need to implement a function that checks if a space is taken in my tic tac toe that's being played in the terminal the problem is that i cant see how i can avoid the choosen position to get into the board if a space is taken i have alreadey made the function heres my code:
import random
board = [[' ',' ',' '],
[' ',' ',' '],
[' ',' ',' ']]
def checkwin(board):
for i in range(3):
if board[i][0] != " " and board[i][0] == board[i][1] == board[i][2]:
return True #winning row
if board[0][i] != " " and board[0][i] == board[1][i] == board[2][i]:
return True #winning column
#winning diagonals
if board[1][1] != " " and board[0][0] == board[1][1] == board[2][2]:
return True
if board[1][1] != " " and board[2][0] == board[1][1] == board[0][2]:
return True
else:
return False
def check_space_taken(board, number):
if not choose_position(board, number) == ' ':
return True
else:
return False
def choose_position(board, number):
if number <= 3:
board[0][number-1] = 'X'
elif number <= 6:
board[1][number-4] = 'X'
elif number <= 9:
board[2][number-7] = 'X'
return board, number
def computer_position(board, computer_number):
computer_number = random.randint(0,9)
if computer_number <= 3:
board[0][computer_number-1] = 'O'
elif computer_number <= 6:
board[1][computer_number-4] = 'O'
elif computer_number <= 9:
board[2][computer_number-7] = 'O'
return board, computer_number
Game_over = False
while not Game_over:
player_input = int(input('move to: '))
player_changed_board = choose_position(board, player_input)
computer_input = random.randint(0,9)
computer_changed_board = computer_position(board, computer_input)
for x in player_changed_board:
print(x)
for y in computer_changed_board:
print('computer move')
print(y)
if checkwin(board):
print('\n-----------------------Congrats you won-----------------------\n')
Game_over = True
I think this would be easier if you used x, y coordinates, but here goes:
from itertools import chain
from random import choice
def cast(x, y, base):
"""
Create a y by x matrix from a vector
"""
if x * y == len(base):
return [list(base[i*x: x+i*x]) for i in range(y)]
raise ValueError('Dimensions do not agree with base')
def flat(board):
"""
Create a 1D vector from a matrix
"""
return [*chain.from_iterable(board)]
def check_space_taken(board, number):
"""
check if a space is taken
"""
return flat(board)[number] == ' '
def empty_space_indices(board):
"""
find all empty spaces
"""
flattened = flat(board)
return [*filter(lambda x: flattened[x]==' ', range(len(flattened)))]
def play(board, number, letter):
"""
Simplify the code base by using a single function for move-making
"""
board = flat(board)
board[number] = letter
board = cast(3, 3, board)
return board
def won(board, letter):
"""
checkwin seems to have a bug
"""
for i in range(3):
if letter == board[i][0] == board[i][1] == board[i][2]:
return True
elif letter == board[0][i] == board[1][i] == board[2][i]:
return True
elif letter == board[0][0] == board[1][1] == board[2][2]:
return True
elif letter == board[2][0] == board[1][1] == board[0][2]:
return True
return False
def show(board):
"""
Neat representation of the board.
checkout the module tabulate for better options:
https://github.com/astanin/python-tabulate
"""
table = '\n'.join("{}|{}|{}".format(*row) for row in board)
table = table.join('\n' * 2)
print(table)
return table
def game_over(board):
"""
check if the board is full or there is a winner
"""
return len(empty_space_indices(board))==0 or won(board, 'x') or won(board, 'o')
def main(board=None):
"""REPL"""
if board:
show(board)
board = board if not isinstance(board, type(None)) else [
[' ',' ',' '],
[' ',' ',' '],
[' ',' ',' ']
]
player_move = None
while not game_over(board):
while not player_move in empty_space_indices(board):
player_move = int(input(f'pick a tile from {empty_space_indices(board)}:\n\t'))
board = play(board, player_move, 'x')
if not game_over(board):
computer_move = choice(empty_space_indices(board))
board = play(board, computer_move, 'o')
show(board)
main()
Warning:
I think there may be something wrong with checkwin because the following did not terminate the game:
x|o|o
|o|o
x|x|x
you can use the following to check:
def relist(table):
"""parse the table from show back into a list"""
t = table.splitlines()
return [i.split('|') for i in t]
t = """x|o|o
|o|o
x|x|x"""
rt = relist(t)
for r in rt: print(r)
print(checkwin(rt))
print(game_over(rt))
print(won(rt, 'x'))
Related
I am new to python. Would like to print the game board for the tic tac toe. May I know how to print using for loop?
Here is my code:
`
board = {
1: ' ', 2: ' ', 3: ' ',
4: ' ', 5: ' ', 6: ' ',
7: ' ', 8: ' ', 9: ' '
}
def printBoard():
print(board[1] + '|'+ board[2]+'|'+board[3])
print('-----')
print(board[4] + '|'+board[5]+'|' + board[6])
print('-----')
print(board[7] + '|'+board[8]+'|' + board[9])
return
`
Your code is fine. You just need to call the function at the end of the script so that it actually gets executed. And the return keyword is not needed as the function doesn't return any value, only prints the board.
board = {
1: ' ', 2: ' ', 3: ' ',
4: ' ', 5: ' ', 6: ' ',
7: ' ', 8: ' ', 9: ' '
}
def printBoard():
print(board[1] + '|'+ board[2]+'|'+board[3])
print('-----')
print(board[4] + '|'+board[5]+'|' + board[6])
print('-----')
print(board[7] + '|'+board[8]+'|' + board[9])
printBoard()
You can make a Tic Tac Toe game using the folowing code :
import random
class TicTacToe:
def __init__(self):
self.board = []
def create_board(self):
for i in range(3):
row = []
for j 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 i in range(n):
win = True
for j in range(n):
if self.board[i][j] != player:
win = False
break
if win:
return win
# checking columns
for i in range(n):
win = True
for j in range(n):
if self.board[j][i] != 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[i][n - 1 - i] != 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()
# taking user input
row, col = list(
map(int, input("Enter row and column numbers to fix spot: ").split()))
print()
# fixing the spot
self.fix_spot(row - 1, col - 1, player)
# checking whether current player is won or not
if self.is_player_win(player):
print(f"Player {player} wins the game!")
break
# checking whether the game is draw or not
if self.is_board_filled():
print("Match Draw!")
break
# swapping the turn
player = self.swap_player_turn(player)
# showing the final view of board
print()
self.show_board()
# starting the game
tic_tac_toe = TicTacToe()
tic_tac_toe.start()
You can use two generator expression, one for row and one for each cell. You can add the separators by using the generators in join()
def print_board():
print('\n-----\n'.join(('|'.join(board[i + j] for i in range(1, 4)) for j in range(0, len(board), 3))))
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
When i was making a simple tic-tac-toe game i suddenly got this error in my winner() function which uses line_winner(line) to find a winner for each row column and diagonal but i don't know why it is throwing "Attribute None type doesn't have have method line.count()" error which i think it shouldn't so i'm attaching whole program so that you can test that and play that game if it works fine and help me out where i was wrong.
from random import randint
def new_board():
"""Generate and return a new empty board"""
board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
return board
def square(board, row, column):
"""Return the contents of square (row, column) of board.
The value is either 'O', 'X' or ' '
"""
return board[row][column]
def row(board, row_num):
"""Return the given numbered row (0 - 2) of board"""
if -1 < row_num < 3:
return board[row_num]
return 0
def column(board, column_num):
"""Return the given numbered column (0 - 2) of board"""
col = []
if -1 < column_num < 3:
for rows in range(0, len(board)):
col.append(board[rows][column_num])
return col
return 0
def diagonal(board, diagonal_selector):
"""Return the 3 element diagonal of the board selected by
diagonal_selector, one of TOP_LEFT_BOTTOM_RIGHT or
TOP_RIGHT_BOTTOM_LEFT
"""
diagonals = []
if diagonal_selector == 1:
diagonals.append(board[0][2])
diagonals.append(board[1][1])
diagonals.append(board[2][0])
elif diagonal_selector == 0:
diagonals.append(board[0][0])
diagonals.append(board[1][1])
diagonals.append(board[2][2])
else:
return diagonals
def empty_squares(board):
"""Return a list of the empty squares in the board, each as
a (row, column) tuple"""
indexes = []
for rows in range(0, len(board)):
for col in range(0, len(board[0])):
if square(board, rows, col) == ' ':
indexes.append((rows, col))
return indexes
def line_winner(line):
"""Return 'O' or 'X' if all elements in the 3-element list line
are the same and non-blank. Otherwise return None"""
if line.count(line[0]) == 3 and line[0] != ' ':
return line[0]
return None
def winner(board):
"""Return 'O' or 'X' if either of those has won the game.
Otherwise return None. It is assumed there can be only a
single winning line."""
game_winner = None
for index in range(0, len(board)):
# Check rows
if line_winner(row(board, index)) is not None:
game_winner = line_winner(row(board, index))
# check columns
elif line_winner(column(board, index)) is not None:
game_winner = line_winner(column(board, index))
# check diagonals
elif index < 2:
if line_winner(diagonal(board, index)) is not None:
game_winner = line_winner(diagonal(board, index))
# final winner
return game_winner
def game_over(board):
"""Given a board state return true iff there's a winner or
if the game is drawn."""
# there is a winner
if winner(board):
return True
# every square is filled
elif len(empty_squares(board)) == 0:
return True
return False
def game_result(board):
"""Return 'Won by O', 'Won by X' or 'Draw' according to the
state of board. It is assume the game is over."""
if winner(board) == 'X':
print("Won by player X")
elif winner(board) == 'O':
print("Won by player O")
else:
print("Draw")
def make_human_move(current_player, board):
"""Given a board state and the human piece ('O' or 'X')
ask the player for a location to play in. Repeat until a
valid response is given. Then make the move, i.e., update
the board by setting the chosen square to the player's piece.
"""
if current_player == 'X':
print("X's move")
if current_player == 'O':
print("O's move")
move = input("Enter row and column [0-2] ")
rows = int(move[0])
col = int(move[-1])
if -1 < int(move[0]) < 3 and -1 < int(move[-1]) < 3 and square(board, rows, col) == ' ':
board[rows][col] = current_player
else:
print("Illegal move try again")
make_human_move(current_player, board)
def play_one_turn(board, current_player, human_player):
"""Given a board state and the current
player ('O' or 'X'), play one move"""
if current_player == human_player:
make_human_move(current_player, board)
else:
make_computer_move(current_player, board)
def other_player(player):
"""Return X if player is O else return O"""
if player == 'X':
return 'O'
elif player == 'O':
return 'X'
return ' '
def get_O_or_X():
"""Ask the human if they want to play O or X and return their
choice"""
choice = input("Would you like to play O or X ?")
if choice == 'X' or choice == 'O':
return choice
else:
get_O_or_X()
def play_game(human_player, board):
"""Play until a win or a draw"""
current_player = human_player
while game_over(board) is False:
display(board)
play_one_turn(board, current_player, human_player)
current_player = other_player(current_player)
game_result(board)
def make_computer_move(current_player, board):
"""Given a board state and the computer piece ('O' or 'X')
choose a square for the computer to play in and
make the move (i.e., update the board accordingly).
"""
candidates = empty_squares(board)
choice = randint(0, len(candidates) - 1)
row, column = candidates[choice]
print("Computer plays at ({},{})".format(row, column))
board[row][column] = current_player
def display(board):
"""Display the given board"""
separator = '+---+---+---+'
print(separator)
for row in board:
print('|', end='')
for col in row:
print(' {} |'.format(col), end='')
print('\n' + separator)
print()
def main():
"""Play a game of noughts and crosses"""
board = new_board()
human_player = get_O_or_X()
try:
play_game(human_player, board)
display(board)
except ValueError:
print("The program has encountered an error and needs to die. Bye.")
main()
diagonal() doesn't return the diagonals list when diagonal_selector is 1 or 2. The return diagonals statement should not be in else:, it should be done always.
def diagonal(board, diagonal_selector):
"""Return the 3 element diagonal of the board selected by
diagonal_selector, one of TOP_LEFT_BOTTOM_RIGHT or
TOP_RIGHT_BOTTOM_LEFT
"""
diagonals = []
if diagonal_selector == 1:
diagonals.append(board[0][2])
diagonals.append(board[1][1])
diagonals.append(board[2][0])
elif diagonal_selector == 0:
diagonals.append(board[0][0])
diagonals.append(board[1][1])
diagonals.append(board[2][2])
return diagonals
i have a problem with creating a dict in python.
In my mainloop i call function 1 which should creat an empty dict.
function 1 calls function 2.
function 2 calls itself (loop through a game tree)
but i can not use the dict i created in f1.
and it is not possible to pass it as agrument.
i would like to have the dict globaly accessible
def f1(): # function 1
#test_dict = {} # this needs to be global scope
#test_dict["key"] = "value"
test_dict["key2"] = "value2"
print (test_dict)
f2()
def f2(): # function 2
# here starts a loop that calls f2 again and again -> global dict is needed
# dict needs to be created
print (test_dict)
test_dict = {} # only works without errors when i create it before calling f1
test_dict["key"] = "value"
f1()
Here is my "real" Code :)
The >>MinMaxComputerMove<< need to edit the dict.
but at the end of a nood i cant pass it because the for loop just goes on.
# [] [] []
# [] [] []
# [] [] []
#Input Layer:
#9 Punkte mit -1 (geg.) 0 (leer) 1 (eig.)
from time import sleep
from random import randint
from random import choice
from IPython.display import clear_output
def clearBoard():
board = [0] * 10
return (board)
def drawBoard(board, PlayerSymbol, ComputerSymbol, turn):
turn += 1
#clear_output()
Symbolboard = []
for index, value in enumerate(board):
if value == 1:
Symbolboard.append(PlayerSymbol)
elif value == -1:
Symbolboard.append(ComputerSymbol)
else:
Symbolboard.append(" ")
print ("Turn: " + str(turn))
print ("")
print (str(Symbolboard[7]) + " - " + str(Symbolboard[8]) + " - " + str(Symbolboard[9]))
print ("| \ | / |")
print (str(Symbolboard[4]) + " - " + str(Symbolboard[5]) + " - " + str(Symbolboard[6]))
print ("| / | \ |")
print (str(Symbolboard[1]) + " - " + str(Symbolboard[2]) + " - " + str(Symbolboard[3]))
return (validMoves(board), turn)
def validMoves(board):
#return list with valid indices
validMoveList = []
for index, value in enumerate(board):
if index > 0 and value == 0:
validMoveList.append(index)
return (validMoveList)
def Symbol():
#X always goes first
if randint(0, 1) == 0:
print ("X: YOU")
print ("O: COMPUTER")
return ("X"), ("O")
else:
print ("X: COMPUTER")
print ("O: YOU")
return ("O"), ("X")
def PlayerMove(validMoveList, PlayerSymbol):
PlayerInput = input("Welches Feld? (1-9):")
if int(PlayerInput) in validMoveList:
return (PlayerInput, PlayerSymbol)
else:
print("Falsche Eingabe." + PlayerInput + " kein möglicher Zug")
def ComputerMove(validMoveList, board, PlayerSymbol, ComputerSymbol, AI):
print("ComputerMove")
if AI == 1:
return RandomComputerMove(validMoveList, ComputerSymbol)
elif AI == 2:
path_dict = {}
return MinMaxComputerMove(validMoveList, board, PlayerSymbol, ComputerSymbol, depth = 1, firstrun = 1)
# more AIs
# ...
def ComputerThinking():
print("Computer is thinking", end = "")
sleep(0.5)
print(".", end = "")
sleep(0.5)
print(".", end = "")
sleep(0.5)
print(".")
sleep(1)
return
def RandomComputerMove(validMoveList, ComputerSymbol):
ComputerChoice = choice(validMoveList)
ComputerThinking()
print("ComputerChoice: " + str(ComputerChoice))
sleep(1.5)
print("RandomComputerMove Output: " + str((ComputerChoice, ComputerSymbol)))
return (ComputerChoice, ComputerSymbol)
def MinMaxComputerMove(validMoveList, board, PlayerSymbol, ComputerSymbol, depth, firstrun = 0, start_path = -1):
initial_validMoveList = validMoveList.copy()
initial_board = board.copy()
turns_left = len(initial_validMoveList)
#debug
print("firstrun: " + str(firstrun))
print("depth: " + str(depth))
if firstrun == 1: #first run of function
path_dict = {}
for path, field in enumerate(initial_validMoveList):
path_dict[path] = {}
for extent in range(3):
path_dict[path][extent+1] = 5
#debug
print("---MinMaxComputerMove---")
print("Start MinMaxComputerMove with depth: " + str(depth))
print("validMoveList: " + str(validMoveList) + str(id(validMoveList)))
print("board: " + str(board) + str(id(board)))
print("ComputerSymbol: " + str(ComputerSymbol))
print("start_path: " + str(start_path))
for path, field in enumerate(initial_validMoveList): #(2, 6, 8):
if firstrun == 1:
start_path = path
print("start_path: " + str(start_path))
# for every path in tree diagram create a key in dict with empty list
# goal: dict("path": [field, depth_1_(max)value, depth_2_(min)value, depth_3_(max)value])
#debug
print("depth: " + str(depth))
if depth % 2 == 1: # Computer:
ChoosenIndex = (str(field), ComputerSymbol)
else: # Player
ChoosenIndex = (str(field), PlayerSymbol)
new_board = updateBoard(initial_board.copy(), ChoosenIndex, PlayerSymbol) # copy() or initial_board would change
new_validMoveList = validMoves(new_board)
#debug
print("---For Loop---")
print("ChoosenIndex: " + str(ChoosenIndex) + str(id(ChoosenIndex)))
print("new_validMoveList: " + str(new_validMoveList) + str(id(new_validMoveList)))
print("new_board: " + str(new_board) + str(id(new_board)))
print("path_dict: " + str(path_dict))
print("depth: " + str(depth))
if checkWinner(new_board) == 0 and depth != 3 and turns_left >= 1: # no winner yet and game not over
print ("no winner yet and game not over")
# go deeper
path_dict[start_path][depth] = 0
MinMaxComputerMove(new_validMoveList, new_board, PlayerSymbol, ComputerSymbol, depth + 1, 0, start_path)
elif checkWinner(new_board) == 0 and depth == 3 and turns_left >= 1: # no winner yet and game not over and minmax ends (depth = 3)
print ("checkWinner(new_board) == 0 and depth == 3 and turns_left >= 1")
path_dict[start_path][depth] = 0
elif checkWinner(new_board) == -1: # computer wins
print ("elif checkWinner(new_board) == -1")
if depth % 2 == 1: # Computer -> MIN:
path_dict[start_path][depth] <= -1
else: # Player -> MAX
if path_dict[start_path][depth] > -1:
path_dict[start_path][depth] = -1
elif checkWinner(new_board) == 1: # player wins
print ("elif checkWinner(new_board) == 1")
path_dict[start_path][depth] = 1
elif depth >= 3 or turns_left < 1: # reached depth 3 or no more turns
print ("elif depth >= 3 or turns_left < 1:")
else:
print ("else")
print("--- END FOR PATH ---")
print("--- END FOR LOOP ---")
print(path_dict)
# return choise
return (2, ComputerSymbol)
def updateBoard(board, ChoosenIndex, PlayerSymbol): #[0, 1, -1, 0, ...],[5, "X"], "X"
if PlayerSymbol == ChoosenIndex[1]:
board[int(ChoosenIndex[0])] = 1
return (board)
else:
board[int(ChoosenIndex[0])] = -1
return (board)
def checkWinner(board):
if (board[7] == board[8] == board[9]) and 0 != board[7]: # top row
return board[7]
elif (board[4] == board[5] == board[6]) and 0 != board[4]: # mid row
return board[4]
elif (board[1] == board[2] == board[3]) and 0 != board[1]: # bot row
return board[1]
elif (board[7] == board[4] == board[1]) and 0 != board[7]: # left column
return board[7]
elif (board[8] == board[5] == board[2]) and 0 != board[8]: # mid row
return board[8]
elif (board[9] == board[6] == board[3]) and 0 != board[9]: # right row
return board[9]
elif (board[7] == board[5] == board[3]) and 0 != board[7]: # diagonal \
return board[7]
elif(board[1] == board[5] == board[9]) and 0 != board[1]: # diagonal /
return board[1]
else:
return 0
def GameLoop(AI, turn = 0, winner = 0):
#choose AI difficulty
#...
#...
#set first player (X)
PlayerSymbol, ComputerSymbol = Symbol()
sleep(3)
#init board with list 10 * 0
board = clearBoard()
#debug
board = [0, 1, 0, 1, -1, -1, 0, 1, 0, -1]
PlayerSymbol, ComputerSymbol = ("O", "X") # computer first
#draw current board
validMoveList, turn = drawBoard(board, PlayerSymbol, ComputerSymbol, turn)
while winner == 0 and turn <=9:
sleep(1.5)
if turn % 2 == 1: # "X" player move
if PlayerSymbol == "X":
#player move
ChoosenIndex = PlayerMove(validMoveList, PlayerSymbol)
#update current board
board = updateBoard(board, ChoosenIndex, PlayerSymbol)
#draw current board
validMoveList, turn = drawBoard(board, PlayerSymbol, ComputerSymbol, turn)
#check for winner
winner = checkWinner(board)
else:
#computer move
ChoosenIndex = ComputerMove(validMoveList, board, PlayerSymbol, ComputerSymbol, AI)
#update current board
board = updateBoard(board,ChoosenIndex, PlayerSymbol)
#draw current board
validMoveList, turn = drawBoard(board, PlayerSymbol, ComputerSymbol, turn)
#check for winner
winner = checkWinner(board)
else: # "O" player move
if PlayerSymbol == "O":
#player move
ChoosenIndex = PlayerMove(validMoveList, PlayerSymbol)
#update current board
board = updateBoard(board,ChoosenIndex, PlayerSymbol)
#draw current board
validMoveList, turn = drawBoard(board, PlayerSymbol, ComputerSymbol, turn)
#check for winner
winner = checkWinner(board)
else:
#computer move
ChoosenIndex = ComputerMove(validMoveList, board, PlayerSymbol, ComputerSymbol, AI)
#update current board
board = updateBoard(board,ChoosenIndex, PlayerSymbol)
#draw current board
validMoveList, turn = drawBoard(board, PlayerSymbol, ComputerSymbol, turn)
#check for winner
winner = checkWinner(board)
else:
if winner == 1:
print ("YOU WON!")
elif winner == -1:
print ("COMPUTER WON!")
else:
print ("DRAW!")
GameLoop(AI = 2)
The "return value" answer is:
def f1(test_dict): # function 1
#test_dict = {} # this needs to be global scope
#test_dict["key"] = "value"
test_dict["key2"] = "value2"
print ('In f1 {}'.format(test_dict))
f2(test_dict)
return test_dict
def f2(test_dict): # function 2
# here starts a loop that calls f2 again and again -> global dict is needed
# dict needs to be created
print ('In f2 {}'.format(test_dict))
return test_dict
test_dict = {} # only works without errors when i create it before calling f1
test_dict["key"] = "value"
test_dict = f1(test_dict)
which gives output of:
In f1 {'key2': 'value2', 'key': 'value'}
In f2 {'key2': 'value2', 'key': 'value'}
But at some level, you probably want to put some of this into a class and then have test_dict as a variable within the class. That allows f1 and f2 (assuming they are class methods) to access the class variable without passing it as a parameter to the two methods.
class Example:
def __init__(self):
self._test_dict = {}
self._test_dict["key"] = "value"
def f1(self): # function 1
self._test_dict["key2"] = "value2"
print ('In f1 {}'.format(self._test_dict))
self.f2()
def f2(self): # function 2
print ('In f2 {}'.format(self._test_dict))
example = Example()
example.f1()
Below is a very simply version of what your script is attempting. You need to consider what your function parameters should be (what is passed to the function), as well as what your function should be providing at the end of its execution (given to you with the return statement). This way you can manipulate objects without having to keep everything in global scope, and you can avoid having to initialize every conceivable variable at the start of the routine.
Python Functions
Return Statement
def f1():
f1_dict = {}
f1_dict = f2(f1_dict)
return f1_dict
def f2(dict_arg):
f2_dict = {}
for i in range(0,5):
f2_dict[str(i)] = i**i
return f2_dict
dictionary = f1()
print(dictionary)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm very new to Python and I have to create a tic tac toe game with 3 players, 'X', 'O' and 'Y'. The grid has to be 6x6 instead of the normal 3x3. I have been having a lot of trouble with this and I'm very unsure how to do it. I have a 2 player 3x3 game working but implementing another player and validating the wins is becoming more tedious than I previously expected. I need help with validating a win. I haven't written the code to check for a diagonal win because I want to get everything else working before I do that. This is what I have so far but it's not correct. It's not printing out the values entered and when I do enter a value it says X has won straight away. I'd really appreciate it if you could help me. Thanks!
grid = [[0,0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0,0]]
def get_state(grid, row, col):
occupant = grid[col-1][row-1]
if occupant == 1:
return 'X'
if occupant == 2:
return 'O'
if occupant == 3:
return 'Y'
return ' '
def set_state(grid, row, col, player):
if player == 'X':
occupant = 1
elif player == 'O':
occupant = 2
elif player == 'Y':
occupant = 3
grid[col-1][row-1] = occupant
def is_winner(grid):
if grid[0][0] == grid[0][1] == grid [0][2]:
return True
if grid[0][1] == grid[0][2] == grid [0][3]:
return True
if grid[0][2] == grid[0][3] == grid [0][4]:
return True
if grid[0][3] == grid[0][4] == grid [0][5]:
return True
if grid[1][0] == grid[1][1] == grid [1][2]:
return True
if grid[1][1] == grid[1][2] == grid [1][3]:
return True
if grid[1][2] == grid[1][3] == grid [1][4]:
return True
if grid[1][3] == grid[1][4] == grid [1][5]:
return True
if grid[2][0] == grid[2][1] == grid [2][2]:
return True
if grid[2][1] == grid[2][2] == grid [2][3]:
return True
if grid[2][2] == grid[2][3] == grid [2][4]:
return True
if grid[2][3] == grid[2][4] == grid [2][5]:
return True
if grid[3][0] == grid[3][1] == grid [3][2]:
return True
if grid[3][1] == grid[3][2] == grid [3][3]:
return True
if grid[3][2] == grid[3][3] == grid [3][4]:
return True
if grid[3][3] == grid[3][4] == grid [3][5]:
return True
if grid[4][0] == grid[4][1] == grid [4][2]:
return True
if grid[4][1] == grid[4][2] == grid [4][3]:
return True
if grid[4][2] == grid[4][3] == grid [4][4]:
return True
if grid[4][3] == grid[4][4] == grid [4][5]:
return True
if grid[5][0] == grid[5][1] == grid [5][2]:
return True
if grid[5][1] == grid[5][2] == grid [5][3]:
return True
if grid[5][2] == grid[5][3] == grid [5][4]:
return True
if grid[5][3] == grid[5][4] == grid [5][5]:
return True
if grid[0][0] == grid[1][0] == grid [2][0]:
return True
if grid[1][0] == grid[2][0] == grid [3][0]:
return True
if grid[2][0] == grid[3][0] == grid [4][0]:
return True
if grid[3][0] == grid[4][0] == grid [5][0]:
return True
if grid[0][1] == grid[1][1] == grid [2][1]:
return True
if grid[1][1] == grid[2][1] == grid [3][1]:
return True
if grid[2][1] == grid[3][1] == grid [4][1]:
return True
if grid[3][1] == grid[4][1] == grid [5][1]:
return True
if grid[0][2] == grid[1][2] == grid [2][2]:
return True
if grid[1][2] == grid[2][2] == grid [3][2]:
return True
if grid[2][2] == grid[3][2] == grid [4][2]:
return True
if grid[3][2] == grid[4][2] == grid [5][2]:
return True
if grid[0][3] == grid[1][3] == grid [2][3]:
return True
if grid[1][3] == grid[2][3] == grid [3][3]:
return True
if grid[2][3] == grid[3][3] == grid [4][3]:
return True
if grid[3][3] == grid[4][3] == grid [5][3]:
return True
if grid[0][4] == grid[1][4] == grid [2][4]:
return True
if grid[1][4] == grid[2][4] == grid [3][4]:
return True
if grid[2][4] == grid[3][4] == grid [4][4]:
return True
if grid[3][4] == grid[4][4] == grid [5][4]:
return True
if grid[0][5] == grid[1][5] == grid [2][5]:
return True
if grid[1][5] == grid[2][5] == grid [3][5]:
return True
if grid[2][5] == grid[3][5] == grid [4][5]:
return True
if grid[3][5] == grid[4][5] == grid [5][5]:
return True
return False
def print_grid(grid):
print_row(grid,1)
print('-----------')
print_row(grid,2)
print('-----------')
print_row(grid,4)
print('-----------')
print_row(grid,4)
print('-----------')
print_row(grid,5)
print('-----------')
print_row(grid,6)
def print_row(grid, row):
output = get_state(grid,row,1)
output += '|' + get_state(grid, row, 2)
output += '|' + get_state(grid, row, 3)
output += '|' + get_state(grid, row, 4)
output += '|' + get_state(grid, row, 5)
output += '|' + get_state(grid, row, 5)
print (output)
ongoing = True
currentPlayer = 'X'
spaces = 36
while ongoing:
print_grid(grid)
print (currentPlayer + "'s turn")
print("Column?")
col = int(input())
print("Row?")
row = int(input())
current = get_state(grid,row,col)
if current != ' ':
print ("That spot is taken!")
else:
set_state(grid, row, col, currentPlayer)
spaces -= 1
if is_winner(grid):
print (currentPlayer + "'s wins!")
ongoing = False
else:
if currentPlayer == 'X':
currentPlayer = 'O'
elif currentPlayer == 'O':
curentPlayer = 'Y'
elif currentPlayer == 'Y':
currentPlayer = 'X'
if spaces == 0:
print("Stalemate!")
ongong = False
The is_winner(grid) function checks if 3 of the grid cells are the same. You initialized the grid to be 0, so the first player would always 'win'. One fix I suggest would be to initialize the list with different values. Another one would be to check (after finding that 3 cells are same) the values of the grid:
if grid[0][0] == grid[0][1] == grid[0][2]:
return grid[0][0] in ['X', 'O', 'Y']
The answer given by chucksys is good, although I would do it in a slightly different way. You need to determine that the 3 cells are the same, and not empty - so just check against your default value.
if grid[0][0] == grid[0][1] == grid[0][2] != 0:
return True
good luck with your game it's fun !!!! You can leave the code as it is. just make a different grid. one that contains a different value in every cell. That will prevent you from rewriting a lot of the game. At the beginning add the following code:grid = []
inner = []
b = 10
for i in xrange(6):
for ii in xrange(6):
inner.append(b)
b += 1
grid.append(inner)
inner = list()
This will make your grid, error proof from your checker function is_winner
There is also one small bug. curentPlayer = 'Y' change to currentPlayer = 'Y' near the end of the code
class Board(object):
def __init__(self):
## board[0] denotes whoes turn it is
self.board = [0,1,2,3,4,5,6,7,8,9]
def putMarker(self,player,move):
##makes move, false if space is full
if self.board[move].isalpha():
return False
if self.board[move].isdigit():
self.board[move] = player
return True
def isFull (self):
##checks if board is full, false if not
for i in range (1,10):
if str(self.board[i]).isdigit():
return False
return True
def score(self):
#checks for win, false if not
if cell[0] == cell[1] == cell[2] == 'O' or cell[3] == cell[4] == cell[5] == 'O' or cell[6] == cell[7] == cell[8] == 'O' or cell[0] == cell[3] == cell[6] == 'O' or cell[1] == cell[4] == cell[7] == 'O' or cell[2] == cell[5] == cell[8]== 'O':
return "The player with O's wins"
if cell[0] == cell[1] == cell[2] == 'X' or cell[3] == cell[4] == cell[5] == 'X' or cell[6] == cell[7] == cell[8] == 'X' or cell[0] == cell[3] == cell[6] == 'X' or cell[1] == cell[4] == cell[7] == 'X' or cell[2] == cell[5] == cell[8]== 'X':
return "The player with X's wins"
else:
return False
def __str__ (self):
##prints board
return str(self.board[1]) + "|" + str(self.board[2]) + "|" + str(self.board[3]) + "\n" +"-+-+-\n" +str(self.board[4]) + "|" + str(self.board[5]) + "|" + str(self.board[6]) + "\n" +"-+-+-\n"+str(self.board[7]) + "|" + str(self.board[8]) + "|" + str(self.board[9])
##class Player(object):
## def __init__(self,name):
## self.name = name
## self.shape = shape
class HumanPlayer(object):
def __init__(self,name):
self.name = name
self.symbol = "A"
self.MyScore = 0
def name(self):
return self.name
def getNextMove (self, board):
##prompts for and executes move:
move = input("it is your move" + self.name + "where do you want to play?")
if board.putMarker(symbol,move):
board.putMarker(symbol,move)
def PlayGame(p1,p2):
TheBoard = Board()
p1.symbol = "X"
p2.symbol = "O"
while TheBoard.score == False:
print TheBoard
if TheBoard.board[0] == 0 and TheBoard.isFull == False:
p1.getNextMove(TheBoard)
TheBoard.board[0] = 1
if TheBoard.board[0] == 1 and TheBoard.isFull == False:
p2.getNextMove(TheBoard)
TheBoard.board[0] = 0
##Display board..
##Ask for new move..
##Execute move, if false skip turn..
##alternate turn
You have to now create a module where you declare the function PlayGame as the function to be executed.
When you run the above script, it only creates all the functions, but no function really gets called.