Checking multiple indexes in a list python 3.8 - python

I'm making a tic tac toe game and I need a way to check winning conditions. I made an
if statement to check if X has 3 in a row, but for some reason I can't reach a winning condition. I can have this X| |X but when I try to fill in the blank it tells me that I can't do that.
tiles = [1, 2, 3, 4, 5, 6, 7, 8, 9]
tiles_str = ("1", "2", "3", "4", "5", "6", "7", "8", "9")
global turn_count
turn_count = 0
def board():
divider = "-----"
play_board = str(tiles[0]) + "|" + str(tiles[1]) + "|" + str(tiles[2])
play_board_1 = str(tiles[3]) + "|" + str(tiles[4]) + "|" + str(tiles[5])
play_board_2 = str(tiles[6]) + "|" + str(tiles[7]) + "|" + str(tiles[8])
print(play_board)
print(divider)
print(play_board_1)
print(divider)
print(play_board_2)
while True:
def Turn_X():
board()
x_turn = input("X take your turn: ")
if x_turn in tiles_str:
x_turn = int(x_turn)
if x_turn in tiles:
if isinstance(tiles[x_turn], int):
global turn_count
turn_count = turn_count+1
tiles[x_turn -1] = "X"
if turn_count < 9:
Turn_O()
else:
print("Not an option")
Turn_X()
else:
print("Not an option")
Turn_X()
else:
print("Not an option")
Turn_X()
def Turn_O():
board()
o_turn = input("O take your turn: ")
if o_turn in tiles_str:
o_turn = int(o_turn)
if o_turn in tiles:
if isinstance(tiles[o_turn], int):
global turn_count
turn_count = turn_count+1
tiles[o_turn -1] = "O"
print(turn_count)
Turn_X()
else:
print("Not an option")
Turn_O()
else:
print("Not an option")
Turn_O()
else:
print("Not an option")
Turn_O()
if turn_count >= 9:
board()
print("\nDraw")
break
if tiles[0] == "X" and tiles[1] == "X" and tiles[2] == "X":
print("X wins")
break
Turn_X()
This is what I have for my game so far. I don't know if it's interfering with something else because I didn't have this issue before hand.

x_turn = int(x_turn)
if x_turn in tiles:
if isinstance(tiles[x_turn], int):
Python lists are zero-indexed. If the player entered 3, you're checking tiles[3] which is actually the fourth square.

Your architecture has some issues. Don't define functions inside a while loop; prepare all your functions at the front, then USE them.
Don't use recursion for retrying an input. That's wasteful. Instead, use a while loop.
Note that the X and O functions are practically identical. Just use the same code and pass the letter.
Your code only checked for a top line. There's no reason to check X and O separately; just check whether the set of three are identical to each other.
This works:
def board():
divider = "-----"
play_board = f"{tiles[0]}|{tiles[1]}|{tiles[2]}"
play_board_1 = f"{tiles[3]}|{tiles[4]}|{tiles[5]}"
play_board_2 = f"{tiles[6]}|{tiles[7]}|{tiles[8]}"
print(play_board)
print(divider)
print(play_board_1)
print(divider)
print(play_board_2)
def Turn(xo):
board()
while True:
turn = input(xo + " take your turn: ")
if not "1" <= turn <= "9":
print( "Not an option." )
continue
turn = int(turn)-1
if isinstance(tiles[turn], int):
tiles[turn] = xo
if turn_count < 9:
return
print("Not an option")
def checkdraw(tiles):
return not any(isinstance(i,int) for i in tiles)
def checkwin(tiles):
if tiles[0] == tiles[1] == tiles[2]:
return tiles[0]
if tiles[3] == tiles[4] == tiles[5]:
return tiles[3]
if tiles[6] == tiles[7] == tiles[8]:
return tiles[6]
if tiles[0] == tiles[3] == tiles[6]:
return tiles[0]
if tiles[1] == tiles[4] == tiles[7]:
return tiles[1]
if tiles[2] == tiles[5] == tiles[8]:
return tiles[2]
if tiles[0] == tiles[4] == tiles[8]:
return tiles[4]
if tiles[2] == tiles[4] == tiles[6]:
return tiles[4]
return False
tiles = [1, 2, 3, 4, 5, 6, 7, 8, 9]
turn_count = 0
while True:
Turn('X')
turn_count = turn_count+1
if checkdraw(tiles):
print("Draw")
board()
break
if checkwin(tiles):
print("X wins!")
board()
break
Turn('O')
turn_count = turn_count+1
if checkdraw(tiles):
print("Draw")
board()
break
if checkwin(tiles):
print("O wins!")
board()
break
One cute optimization:
def checkwin(tiles):
for l in (
(0,1,2),(3,4,5),(6,7,8),
(0,3,6),(1,4,7),(2,5,8),
(0,4,8),(2,4,6)
):
if tiles[l[0]] == tiles[l[1]] == tiles[l[2]]:
return tiles[l[0]]
return False

Sorry but there is too much wrong to fix it without changing everything. You only check if x won when you have set all 9 fields. Check it before you call turn_o or turn_x.
Look for try: and except: and custom error class instead of the 3 if statements.
You can print a break line with \n so you have one variable instead of 4 to print your field and you can do this for example:
field = f"{str(tiles[0])}|"
And you have much code duplication which you could fix when you use functions with parameters

Related

Python bingo project

so my code is designed to basically create a bingo card, then when you press enter draws a number and changes the bingo card value to 0 if the drawn number matches. My issue is that my code isn't properly producing a bingo or not a bingo which you can see towards the end of the code. How should I change this so that my code will return bingo when I have bingo.
import random #Condernsed solo version with call and player together
import numpy as np
def bingo_card(): #Code to generate BINGO card using numpy array
test1=np.array(random.sample(range(1,16),5))
test2=np.array(random.sample(range(16,31),5))
test3=np.array(random.sample(range(31,46),5))
test4=np.array(random.sample(range(46,61),5))
test5=np.array(random.sample(range(61,76),5))
test= np.concatenate((test1,test2,test3,test4,test5))
test= test.reshape(5,5)
test[2,2]=0
bingo_card.test = test
BINGO= print("Your Card")
print("B", test[0]),
print("I", test[1]),
print("N", test[2]),
print("G", test[3]),
print("O", test[4])
card = BINGO
return card
def called_value(): #should be close to the code we use to check if called value is in generated matrix, may need some formatting and fixing
checked_card = bingo_card.test
while True:
called_num = input ("Type called number to mark card or press 's' to quit if you think you have bingo").lower()
if called_num != "s":
number_check = int(called_num)
checked_card = np.where(checked_card==number_check,0,checked_card)
BINGO = print("Your Card")
print("B", checked_card[0]),
print("I", checked_card[1]),
print("N", checked_card[2]),
print("G", checked_card[3]),
print("O", checked_card[4])
elif called_num == "s":
BINGO = print("Your Card")
print("B", checked_card[0]),
print("I", checked_card[1]),
print("N", checked_card[2]),
print("G", checked_card[3]),
print("O", checked_card[4])
row_zeros = np.count_nonzero(checked_card == 0, axis=1)
col_zeros = np.count_nonzero(checked_card == 0, axis=0)
diagonal_zeros = np.count_nonzero(np.diag(checked_card) == 0)
diagonal1_zeros = np.count_nonzero(np.diag(np.fliplr(checked_card)) == 0)
for i in range (5):
if (row_zeros[i] or col_zeros[i]) == 5:
return ("Bingo!")
elif (diagonal_zeros or diagonal1_zeros) == 5:
return ("Bingo!")
else:
return ("Not Bingo")
def solo():
bingo_card()
called_value()
solo()
You've committed one of the classic blunders.
for i in range (5):
if (row_zeros[i] or col_zeros[i]) == 5:
return ("Bingo!")
elif (diagonal_zeros or diagonal1_zeros) == 5:
return ("Bingo!")
else:
return ("Not Bingo")
row_zeros[i] or col_zeros[i] is going to be True or False (usually True), which is never equal to 5. And you don't need to loop to check the diagonals. You need:
if diagonal_zeros == 5 or diagonal1_zeros == 5:
return ("Bingo!")
for i in range (5):
if row_zeros[i] == 5 or col_zeros[i] == 5:
return ("Bingo!")
return ("Not Bingo")

TicTacToe and Minimax

I am a young programmer that is learning python and struggling to implement an AI (using minimax) to play TicTacToe. I started watching a tutorial online, but the tutorial was on JavaScript and thus couldn't solve my problem. I also had a look at this question ( Python minimax for tictactoe ), but it did not have any answers and the implementation was considerably different from mine.
EDIT: the code you will find below is an edit suggested by one of the answers (#water_ghosts).
EDIT #2: I deleted possiblePositions, as the AI should choose a free field and not a place from the possiblePositions (that wouldn't make it that smart while implementing minimax :) )
Now the code doesn't give out any errors at all and functions properly, but one small thing: the AI always chooses the next available field. For example in situations where i am i move away from winning, instead of blocking my win option, it chooses the next free spot.
If you're wondering what that elements dict is doing there: i just wanted to make sure the programm chose the best index...
Here is my code:
class TicTacToe:
def __init__(self):
self.board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
self.playerSymbol = ""
self.playerPosition = []
self.aiSymbol = ""
self.aiPosition = []
self.score = 0
self.winner = None
self.scoreBoard = {
self.playerSymbol: -1,
self.aiSymbol: 1,
"tie": 0
}
self.turn = 0
self.optimalMove = int()
def drawBoard(self):
print(self.board[0] + " | " + self.board[1] + " | " + self.board[2])
print("___" + "___" + "___")
print(self.board[3] + " | " + self.board[4] + " | " + self.board[5])
print("___" + "___" + "___")
print(self.board[6] + " | " + self.board[7] + " | " + self.board[8])
def choice(self):
answer = input("What do you want to play as? (type x or o) ")
if answer.upper() == "X":
self.playerSymbol = "X"
self.aiSymbol = "O"
else:
self.playerSymbol = "O"
self.aiSymbol = "X"
def won(self):
winningPositions = [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 4, 8}, {2, 4, 6}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}]
for position in winningPositions:
if position.issubset(self.playerPosition):
self.winner = self.playerSymbol
print("Player Wins :)")
return True
elif position.issubset(self.aiPosition):
self.winner = self.aiSymbol
print("AI wins :(")
return True
if self.board.count(" ") == 0:
self.winner = "tie"
print("Guess it's a draw")
return True
return False
def findOptimalPosition(self):
bestScore = float("-Infinity")
elements = {} # desperate times call for desperate measures
for i in range(9):
if self.board[i] == " ":
self.board[i] = self.aiSymbol # AI quasi made the move here
if self.minimax(True) > bestScore:
bestScore = self.score
elements[i] = bestScore
self.board[i] = " "
return max(elements, key=lambda k: elements[k])
def minimax(self, isMaximizing):
if self.winner is not None:
return self.scoreBoard[self.winner]
if isMaximizing:
bestScore = float("-Infinity")
for i in range(9):
if self.board[i] == " ":
self.board[i] = self.aiSymbol
bestScore = max(self.minimax(False), bestScore)
self.board[i] = " "
return bestScore
else:
bestScore = float("Infinity")
for i in range(9):
if self.board[i] == " ":
self.board[i] = self.playerSymbol
bestScore = min(self.minimax(True), bestScore)
self.board[i] = " "
return bestScore
def play(self):
self.choice()
while not self.won():
if self.turn % 2 == 0:
pos = int(input("Where would you like to play? (0-8) "))
self.playerPosition.append(pos)
self.board[pos] = self.playerSymbol
self.turn += 1
self.drawBoard()
else:
aiTurn = self.findOptimalPosition()
self.aiPosition.append(aiTurn)
self.board[aiTurn] = self.aiSymbol
self.turn += 1
print("\n")
print("\n")
self.drawBoard()
else:
print("Thanks for playing :)")
tictactoe = TicTacToe()
tictactoe.play()
I come from a java background and am not used to this :(
Any help would be highly appreciated
I am open to suggestions and ways to improve my code and fix this problem.
Thanks in advance and stay healthy,
Kristi
Change this part, your implementation will return optimalMove even if it doesn't go inside the if statement, and optimalMove will not be assigned at that point, so put the return inside.
if score > sampleScore:
sampleScore = score
optimalMove = i
return optimalMove
optimalMove = 0 in play() and optimalMove = i in findOptimalField() are declaring two distinct variables, each of which is local to the function declaring it.
If you want multiple functions to have access to the same variable, you can use the global keyword, but that's generally considered a bad practice. It can make it hard to reason about the code (e.g. is var = x creating a new local variable or overwriting the value of a global?) and it doesn't stop you from accidentally using a variable before it's declared.
Since you're coming from a Java background, you can turn this into a class to get behavior more like what you expect, eliminating the need for globals:
class TicTacToe:
def __init__(self):
self.board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
self.playerSymbol = ""
self.playerPosition = []
self.aiSymbol = ""
self.aiPosition = []
self.score = 0
self.playerSymbol = None
self.aiSymbol = None
...
def drawBoard(self):
print(self.board[0] + " | " + self.board[1] + " | " + self.board[2])
...
def choice(self):
answer = input("What do you want to play as? (type x or o) ")
if answer.upper() == "X":
self.playerSymbol = "X"
self.aiSymbol = "O"
...
Each method now takes an explicit self argument that refers to the current instance, and you can use this to access any variables that belong to the class instance instead of a particular method. If you don't include self. before a variable, that variable will still be local to the method that declares it. In this case, the drawBoard() method won't be able to access the answer variable defined in choice().
You can create new self. variables in any of the class's methods, but the best practice is to initialize all of them in the __init__ constructor method, using None as a placeholder for variables that don't have a value yet.
I am posting this as an answer, just in case somebody in the future stumbles upon the same problem :)
the main issue i encountered (besides my bad programming style) is that i forgot to update the contents the lists playerPosition and aiPosition.
You can review the rest of the changes in the working code:
class TicTacToe:
def __init__(self):
self.board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
self.playerSymbol = ""
self.playerPosition = []
self.aiSymbol = ""
self.aiPosition = []
self.winner = None
self.scoreBoard = None
self.turn = 0
self.optimalMove = int()
def drawBoard(self):
print(self.board[0] + " | " + self.board[1] + " | " + self.board[2])
print("___" + "___" + "___")
print(self.board[3] + " | " + self.board[4] + " | " + self.board[5])
print("___" + "___" + "___")
print(self.board[6] + " | " + self.board[7] + " | " + self.board[8])
def choice(self):
answer = input("What do you want to play as? (type x or o) ")
if answer.upper() == "X":
self.playerSymbol = "X"
self.aiSymbol = "O"
else:
self.playerSymbol = "O"
self.aiSymbol = "X"
self.scoreBoard = {
self.playerSymbol: -1,
self.aiSymbol: 1,
"tie": 0
}
def availableMoves(self):
moves = []
for i in range(0, len(self.board)):
if self.board[i] == " ":
moves.append(i)
return moves
def won_print(self):
self.won()
if self.winner == self.aiSymbol:
print("AI wins :(")
exit(0)
elif self.winner == self.playerSymbol:
print("Player Wins :)")
exit(0)
elif self.winner == "tie":
print("Guess it's a draw")
exit(0)
def won(self):
winningPositions = [{0, 1, 2}, {3, 4, 5}, {6, 7, 8},
{0, 4, 8}, {2, 4, 6}, {0, 3, 6},
{1, 4, 7}, {2, 5, 8}]
for position in winningPositions:
if position.issubset(self.playerPosition):
self.winner = self.playerSymbol
return True
elif position.issubset(self.aiPosition):
self.winner = self.aiSymbol
return True
if self.board.count(" ") == 0:
self.winner = "tie"
return True
self.winner = None
return False
def set_i_ai(self, i):
self.aiPosition.append(i)
self.board[i] = self.aiSymbol
def set_clear_for_ai(self, i):
self.aiPosition.remove(i)
self.board[i] = " "
def set_i_player(self, i):
self.playerPosition.append(i)
self.board[i] = self.playerSymbol
def set_clear_for_player(self, i):
self.playerPosition.remove(i)
self.board[i] = " "
def findOptimalPosition(self):
bestScore = float("-Infinity")
elements = {} # desperate times call for desperate measures
for i in self.availableMoves():
self.set_i_ai(i)
score = self.minimax(False)
if score > bestScore:
bestScore = score
elements[i] = bestScore
self.set_clear_for_ai(i)
if bestScore == 1:
print("you messed up larry")
elif bestScore == 0:
print("hm")
else:
print("whoops i made a prog. error")
return max(elements, key=lambda k: elements[k])
def minimax(self, isMaximizing):
if self.won():
return self.scoreBoard[self.winner]
if isMaximizing:
bestScore = float("-Infinity")
for i in self.availableMoves():
self.set_i_ai(i)
bestScore = max(self.minimax(False), bestScore)
self.set_clear_for_ai(i)
return bestScore
else:
bestScore = float("Infinity")
for i in self.availableMoves():
self.set_i_player(i)
bestScore = min(self.minimax(True), bestScore)
self.set_clear_for_player(i)
return bestScore
def play(self):
self.choice()
while not self.won_print():
if self.turn % 2 == 0:
pos = int(input("Where would you like to play? (0-8) "))
self.playerPosition.append(pos)
self.board[pos] = self.playerSymbol
self.turn += 1
self.drawBoard()
else:
aiTurn = self.findOptimalPosition()
self.aiPosition.append(aiTurn)
self.board[aiTurn] = self.aiSymbol
self.turn += 1
print("\n")
print("\n")
self.drawBoard()
else:
print("Thanks for playing :)")
if __name__ == '__main__':
tictactoe = TicTacToe()
tictactoe.play()
But as mentioned, the code may work, but there are MANY problems regarding the logic and structure, so do not straight-forward copy-paste it :))

I need winning combinations for Tic Tac Toe (or at least some hints/tips)

For a class project, my groupmates and I are to code a tic tac toe program. So far, this is what we have. All of us have 0 experience in python and this is our first time actually coding in python.
import random
import colorama
from colorama import Fore, Style
print(Fore.LIGHTWHITE_EX + "Tic Tac Toe - Below is the key to the board.")
Style.RESET_ALL
player_1_pick = ""
player_2_pick = ""
if (player_1_pick == "" or player_2_pick == ""):
if (player_1_pick == ""):
player_1_pick = "Player 1"
if (player_2_pick == ""):
player_2_pick = "Player 2"
else:
pass
board = ["_"] * 9
print(Fore.LIGHTBLUE_EX + "0|1|2\n3|4|5\n6|7|8\n")
def print_board():
for i in range(0, 3):
for j in range(0, 3):
if (board[i*3 + j] == 'X'):
print(Fore.RED + board[i*3 + j], end = '')
elif (board[i*3 + j] == 'O'):
print(Fore.BLUE + board[i*3 + j], end = '')
else:
print(board[i*3 + j], end = '')
print(Style.RESET_ALL, end = '')
if j != 2:
print('|', end = '')
print()
print_board()
while True:
x = input('Player 1, pick a number from 0-8: ') #
x = int(x)
board[x] = 'X'
print_board()
o = input('Player 2, pick a number from 0-8:')
o = int(o)
board[o] = 'O'
print_board()
answer = raw_input("Would you like to play it again?")
if answer == 'yes':
restart_game()
else:
close_game()
WAYS_T0_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))
We're stuck on how to have the program detect when someone has won the game and then have it print "You won!" and also having the program detect when it's a tie and print "It's a tie!". We've looked all over the internet for a solution but none of them work and we can't understand the instructions. No use asking the teacher because they don't know python or how to code.
I have changed your code in such a way that first of all "save players choices" and in second "check if a player won and break the loop":
import random
import colorama
from colorama import Fore, Style
print(Fore.LIGHTWHITE_EX + "Tic Tac Toe - Below is the key to the board.")
Style.RESET_ALL
player_1_pick = ""
player_2_pick = ""
if (player_1_pick == "" or player_2_pick == ""):
if (player_1_pick == ""):
player_1_pick = "Player 1"
if (player_2_pick == ""):
player_2_pick = "Player 2"
else:
pass
board = ["_"] * 9
print(Fore.LIGHTBLUE_EX + "0|1|2\n3|4|5\n6|7|8\n")
def print_board():
for i in range(0, 3):
for j in range(0, 3):
if (board[i*3 + j] == 'X'):
print(Fore.RED + board[i*3 + j], end = '')
elif (board[i*3 + j] == 'O'):
print(Fore.BLUE + board[i*3 + j], end = '')
else:
print(board[i*3 + j], end = '')
print(Style.RESET_ALL, end = '')
if j != 2:
print('|', end = '')
print()
def won(choices):
WAYS_T0_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 tpl in WAYS_T0_WIN:
if all(e in choices for e in tpl):
return True
return False
print_board()
turn = True
first_player_choices = []
second_player_choices = []
while True:
if turn:
x = input('Player 1, pick a number from 0-8: ') #
x = int(x)
if board[x] == '_':
board[x] = 'X'
first_player_choices.append(x)
turn = not turn
print_board()
if won(first_player_choices):
print('Player 1 won!')
break
else:
print('Already taken! Again:')
continue
else:
o = input('Player 2, pick a number from 0-8: ') #
o = int(o)
if board[o] == '_':
board[o] = 'O'
second_player_choices.append(o)
turn = not turn
print_board()
if won(second_player_choices):
print('Player 2 won!')
break
else:
print('Already taken! Again:')
continue
# answer = input("Would you like to play it again?")
# if answer == 'yes':
# restart_game()
# else:
# close_game()
I also added a condition to check if players choice is already taken! By the way, you can do it way much better. :)
EDIT: there was a little problem with spaces in my answer here and I solve it in edit. Now you can directly copy it in a py file and run it!
Firstly, you need a condition which doesn't allow the same space to be allocated twice, when test running I could type space 3 as much as I wanted for example without it stopping me. You need some sort of check for this.
Secondly, for the actual win system, you made it easy because you already have the co-ordinates for all of the winning games, I recommend something along the lines of:
def checkwin(team):
for i in WAYS_TO_WIN:
checked = False
while not checked:
k = 0
for j in i:
if board[j] == team:
k+=1
if k == 3:
return True
checked = True
This way is checks if any of the co-ordinates have all 3 of any set. You might have to adjust this code, but this looks like a solution.
Note: I'm still a beginner at coding and I stumbled upon your thread, this is an idea not necessarily a working solution

Python: Create Dict in function a and call it in function b

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)

Python validation function generates IndexError: list assignment index out of range

I'm building out Battleships game in Python. I have a list and I'm trying to build a validation tool in Python to catch user inputs that are outside the 10x10 range of my list.
Here is the code:
from random import randint
player = "User"
board = []
board_size = 10
ships = {"Aircraft Carrier":5,
"Battleship":4,
"Submarine":3,
"Destroyer":3,
"Patrol Boat":2}
def print_board(player, board): # to print joined board
print("Here is " + player + "'s board")
for row in board:
print(" ".join(row))
def switch_user(player): # to switch users
if player == "User":
player = "Computer"
elif player == "Computer":
player = "User"
else:
print("Error with user switching")
for x in range(0, board_size): # to create a board
board.append(["O"] * board_size)
print_board(player,board)
def random_row(board): # generate random row
return randint(0, len(board) - 1)
def random_col(board): # generate random column
return randint(0, len(board[0]) - 1)
def user_places_ships(board, ships): # user choses to place its ships by providing starting co-ordinate and direction.
for ship in ships:
valid = False
while(not valid):
user_input_coordinates = input("Please enter row & column number for your " + str(ship) + ", which is " + str(ships[ship]) + "-cells long (row, column).")
ship_row, ship_col = user_input_coordinates.split(",")
ship_row = int(ship_row)
ship_col = int(ship_col)
user_input_dir = input("Please enter direction for your " + str(ship) + ", which is " + str(ships[ship]) + "-cells long (h for horizontal or v for vertical).")
valid = validate_coordinates(board, ships[ship], ship_row, ship_col, user_input_dir)
if not valid:
print("The ship coordinates either outside of" , board_size, "X" , board_size, "range, overlap with or too close to another ship.")
place_ship(board, ships[ship], ship_row, ship_col, user_input_dir)
print("You have finished placing all your ships.")
def validate_coordinates(board, ship_len, row, col, dir): # validates if the co-ordinates entered by a player are within the board and don't overlap with other ships
if dir == "h" or dir == "H":
for x in range(ship_len):
if row-1 > board_size or col-1+x > board_size:
return False
elif row-1 < 0 or col-1+x < 0:
return False
elif board[row-1][col-1+x] == "S":
return False
elif dir == "v" or dir == "V":
for x in range(ship_len):
if row-1+x > board_size or col-1 > board_size:
return False
elif row-1+x < 0 or col-1 < 0:
return False
elif board[row-1+x][col-1] == "S":
return False
return True
def place_ship(board, ship_len, row, col, dir): # to actually place ships and mark them as "S"
if dir == "h" or dir == "H":
for x in range(ship_len):
board[row-1][col-1+x] = "S"
elif dir == "v" or dir == "V":
for x in range(ship_len):
board[row-1+x][col-1] = "S"
else:
print("Error with direction.")
print_board(player,board)
user_places_ships(board,ships)
If a user enters "10,10" for ship coordinates and "h" for horizontal direction, then Python generates the following error message:
Traceback (most recent call last): File "C:/Users/Elchin's PC/Downloads/battleships game.py", line 85, in <module>
user_places_ships(board,ships) File "C:/Users/Elchin's PC/Downloads/battleships game.py", line 49, in user_places_ships
valid = validate_coordinates(board, ships[ship], ship_row, ship_col, user_input_dir) File "C:/Users/Elchin's PC/Downloads/battleships game.py", line 62, in validate_coordinates
elif board[row-1][col-1+x] == "S": IndexError: list index out of range
I know that the error is in this line:
elif board[row-1][col-1+x] == "S":
return False
But I don't know how to fix it. Could you please help me figure out the solution?
If a list has length n, you can access indices from 0 to n-1 (both inclusive).
Your if statements however check:
if row-1+x > board_size or col-1 > board_size: # greater than n
return False
elif row-1+x < 0 or col-1 < 0: # less than 0
return False
elif board[row-1+x][col-1] == "S":
return False
So as a result, if we reach the last elif part, we have guarantees that the indices are 0 < i <= n. But these should be 0 < i < n.
So you should change the first if statement to:
if row-1+x >= board_size or col-1 >= board_size: # greater than or equal n
return False
elif row-1+x < 0 or col-1 < 0: # less than 0
return False
elif board[row-1+x][col-1] == "S":
return False
You can make the code more elegant by writing:
if not (0 < row-1+x < board_size and 0 < col-1 < board_size) or \
board[row-1+x][col-1] == "S":
return False

Categories