I was programming a simple Connect 4 game however I need to add global variables
# Board(0:6, 0:7) : str (but ignore row 0 and column
0)
# ThisPlayer : str[1]
# GameFinished, WinnerFound : bool
# ColumnNumber : int
# ValidColumn, ValidRow : int
which im stuck on as I cant remember how to define global booleans etc (global variables are above)
when I run the code it gives me the error code (Board is not defined) how can I add the global variables so my program runs ?
Code is below
Board[0:6][0:7]
Blank = '.'
def InititialiseBoard():
Board = [[Blank for i in range(7)]
for j in range(6)]
def SetUpGame():
ThisPlayer = 'o'
GameFinished = False
def OutputBoard():
for Row in range(6 , 0 , -1):
for Column in range(7):
print(Board[Row][Column] , end = '')
print()
def ColumnNumberValud():
Valid = False
if ColumnNumber >= 1 and CalumnNumber <= 7:
if Board[6][ColumnNumber] == Blank:
Valid = True
return Valid
def ThisPlayerChoosesColumn():
print('Player ' + ThisPlayer + ' turn.')
while ColumnNumberValid == False:
print('Enter Valid Column Number')
ColumnNumber = int(input('Enter Column Number: '))
return ColumnNumber
def ThisPlayerMakesMove():
ValidColumn = ThisPlayerChoosesColumn()
ValidRow = FindNextFreePositionInColumn()
Board[ValidRow][ValidColumn] = ThisPlayer
def FindNextFreePositionInColumn():
ThisRow = 1
while Board[ThisRow][ValidColumn] != Blank:
ThisRow = ThisRow + 1
return ThisRow
def CheckHorizontalLineInValidRow():
for i in range(4):
if Board[ValidRow][i] == ThisPlayer and Board[ValidRow][i+1] == ThisPlayer and Board[ValidRow][i+2] == ThisPlayer and Board[ValidRow][i+3] == ThisPlayer:
WinnerFound = True
def CheckVerticalLineInValidRow():
if ValidRow == 4 or ValidRow == 5 or ValidRow == 6:
if Board[ValidRow][ValidColumn] == ThisPlayer and Board[ValidRow - 1][ValidColumn] == ThisPlayer and Board[ValidRow - 2][ValidColumn] == ThisPlayer and Board[ValidRow - 3 ][ValidColumn] == ThisPlayer:
WinnerFound = True
def CheckForFullBoard():
BlankFound = False
ThisRow = 0
while ThisRow !=6 or BlankFound == False:
ThisColumn = 0
ThisRow = ThisRow + 1
while ThisColumn != 7 or BlankFound == True:
ThisColumn = ThisColumn + 1
if Board[ThisRow][ThisColumn] == Blank:
BlankFound = True
if Blankfound == False:
print('Draw')
GameFinished = True
def CheckIfThisPlayerHasWon():
WinnerFound = False
CheckHorizontalLineInValidRow()
if WinnerFound == False:
CheckVerticalLineInValidColumn()
if WinnerFound == True:
GameFinished = True
print(ThisPlayer , 'Winner')
else:
CheckForFullBoard()
To use global variables:
global x
x = 1
def foo():
global x
x+=1
print(x)
foo()
print(x)
I would recommend avoiding global variables and use class variables instead.
class yourclass():
def__init__(self):
self.x = 1
def foo(self):
self.x+=1
def print_value(self):
print(self.x)
if __name__=='__main__':
test = yourclass()
test.print_value()
test.foo()
test.print_value()
Related
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 2 days ago.
This post was edited and submitted for review 2 days ago.
Improve this question
class Hand:
def __init__(self, hand):
self.hand = hand
def rank_to_index_converter(rank):
if rank == 2:
return 0
elif rank == 3:
return 1
elif rank == 4:
return 2
elif rank == 5:
return 3
elif rank == 6:
return 4
elif rank == 7:
return 5
elif rank == 8:
return 6
elif rank == 9:
return 7
elif rank == 10:
return 8
elif rank == 'J':
return 9
elif rank == 'Q':
return 10
elif rank == 'K':
return 11
elif rank == 'A':
return 1
else:
raise ValueError
def suit_to_index_converter(suit):
if suit == 'C':
return 0
elif suit == 'D':
return 1
elif suit == 'H':
return 2
elif suit == 'S':
return 3
else:
raise ValueError
def is_consecutive(hand):
### BEGIN YOUR SOLUTION
first = 0
string = ""
count = 0
for x in hand:
#print(x[0])
if x[0] == ("J"):
if first != 10 and (count != 0):
return False
string = x[0]
elif x[0] == ("Q"):
if string != "J" and (count != 0):
return False
string = x[0]
elif x[0] == ("K"):
if string != "Q" and (count != 0):
return False
string = x[0]
elif x[0] == ("A"):
if string != "K" and (count != 0):
return False
string = x[0]
elif x[0] != ("J" or "Q" or "K" or "A"):
if (x[0] != (first + 1)) and (count != 0):
if (hand[0][0] != "A"):
return False
first = x[0]
count = count + 1
return True
def is_suit(hand):
suit = hand[0][1]
for x in hand:
if x[1] != suit:
return False
return True
def is_flush(hand):
return is_suit(hand) and not is_consecutive(hand)
def is_four_of_a_kind(hand):
count = 0
pair_num = 0
lst = [0 for i in range(13)]
for x in hand:
index = rank_to_index_converter(x[0])
lst[index] += 1
for x in lst:
if x == 4:
return True
return False
def is_full_house(hand):
count = 0
pair_num = 0
lst = [0 for i in range(13)]
for x in hand:
index = rank_to_index_converter(x[0])
lst[index] += 1
three_pair = False
pair = False
for x in lst:
if x == 3:
three_pair = True
if x == 2:
pair = True
if three_pair and pair:
return True
return False
def is_flush(hand):
count = 0
while count < (len(hand) - 2):
if hand[count][1] != hand[count + 1][1]:
return False
count += 1
return True
def is_straight(hand):
if is_consecutive(hand) and not is_suit(hand):
return True
return False
def is_three_of_a_kind(hand):
lst = [0 for i in range(13)]
for x in hand:
index = rank_to_index_converter(x[0])
lst[index] += 1
three_pair = False
for x in lst:
if x == 3:
three_pair = True
if three_pair and not is_full_house(hand) and not is_suit(hand):
return True
return False
def is_two_pair(hand):
lst = [0 for i in range(13)]
for x in hand:
index = rank_to_index_converter(x[0])
lst[index] += 1
two_pair = False
counter = 0
switch = 0
while counter != len(lst):
if lst[counter] == 2:
switch = 1
if lst[counter] == 2 & switch == 1:
two_pair = True
if two_pair and not is_full_house(hand) and not is_suit(hand) and not is_four_of_a_kind(hand) and not is_three_of_a_kind(hand):
return True
return False
def is_pair(hand):
lst = [0 for i in range(13)]
for x in hand:
index = rank_to_index_converter(x[0])
lst[index] += 1
pair = False
for x in lst:
if x == 2:
pair = True
if pair and not is_full_house(hand) and not is_suit(hand):
return True
return False
def maximum_value(hand):
sum = 0
for x in hand:
sum += rank_to_index_converter(x[0])
return sum
The is_full_house function uses the rank_to_index_converter function. The rank_to_index_converter function is defined above the is_full_house function. Why am I receiving an error that the rank_to_index_converter function is not defined?
I am lost on where to proceed; therefore, I haven't tried anything, besides copying and pasting the rank_to_index_converter function into the is_full_house function; however, it is more convenient if the rank_to_index_converter is a separate function. That is why I want to solve this issue.
i understand that this error happens when a variable gets mentioned before its defined but "key" is assigned to its value. I started learning python a week ago so i am sorry if my question has a really simple answer.
the code:
from stat import SF_APPEND
import time
import random
keyType = 0
key = 0
deCypherKey = 0
operationType = 0
needToLoop = True
alphabet = "abcdefghijklmnopqrstuvwxyz "
print("ogulSifreleyici v1.0")
time.sleep(0.3)
print("Ipucu: Hem Sifrelemek Hem de Desifrelemek Icin Programi 2 Kere Calistirabilirsiniz")
def cypher():
message = input("Mesajini Gir:\n")
message = message.lower()
unCypheredMessageLength = len(message)
letterOfMessageInQueue = 0
keyStr = str(key)
keyStrInt = 0
whichOrderOfAlphabet = 0
whichLetterOfAlphabet = " "
whichDigitOfKey = 0
orderOfCypheredLetter = 0
cypheredLetter = "a"
cypheredMessageList = []
cypheredStr = ""
while unCypheredMessageLength > 0:
whichLetterOfAlphabet = alphabet[whichOrderOfAlphabet]
if message[letterOfMessageInQueue] == whichLetterOfAlphabet:
print("match")
print(whichOrderOfAlphabet, message[letterOfMessageInQueue], whichLetterOfAlphabet)
keyStrInt = int(keyStr[whichDigitOfKey])
orderOfCypheredLetter = whichOrderOfAlphabet + keyStrInt
if orderOfCypheredLetter > 26:
orderOfCypheredLetter = orderOfCypheredLetter - 26
cypheredLetter = alphabet[orderOfCypheredLetter]
cypheredMessageList.append(cypheredLetter)
unCypheredMessageLength = unCypheredMessageLength - 1
letterOfMessageInQueue = letterOfMessageInQueue + 1
whichOrderOfAlphabet = 0
whichDigitOfKey = whichDigitOfKey + 1
if whichDigitOfKey > 4:
whichDigitOfKey = whichDigitOfKey - 5
if len(cypheredMessageList) == len(message):
cypheredStr = "".join(cypheredMessageList)
print("Sifrelenmis Mesajiniz:\n" + cypheredStr)
time.sleep(1)
lastUserAnswer = input("1-Sifrele(Ayni Anahtar) 2-Sifrele(Farkli Anahtar)\n")
if lastUserAnswer == "1":
cypher()
if lastUserAnswer == "2":
key = input("Anahtar Giriniz(5 Haneli Sayi):\n")
while len(str(key)) != 5:
key = input("Lutfen Bes Haneli Bir Sayi Giriniz\n")
if len(str(key)) == 5:
cypher()
cypher()
else:
whichOrderOfAlphabet = whichOrderOfAlphabet + 1
def deCypher():
deCypherMessage = input("Sifreli Mesajinizi Giriniz:\n")
operationType = input("1-Sifrele 2-DeSifrele\n")
while needToLoop == True:
if operationType == "1":
keyType = input("1-Anahtar gir(5 haneli sayi) 2-Rastgele Anahtar\n")
if keyType == "1":
key = input("Anahtar Giriniz:\n")
while len(str(key)) != 5:
key = input("Lutfen Bes Haneli Bir Sayi Giriniz\n")
if len(str(key)) == 5:
needToLoop = False
cypher()
needToLoop = False
cypher()
if keyType == "2":
key = int(random.uniform(10000, 100000))
print("Anahtariniz: " + str(key))
cypher()
needToLoop = False
else:
print("Lutfen Seceneklerden Birini Seciniz")
needToLoop = True
if operationType == "2":
deCypherKey = input("Anahtarinizi Giriniz:\n")
while len(str(deCypherKey)) != 5:
key = input("Lutfen Bes Haneli Bir Sayi Giriniz\n")
if len(str(key)) == 5:
needToLoop = False
deCypher()
needToLoop = False
deCypher()
else:
print("Lutfen Seceneklerden Birini Seciniz")
needToLoop = True
this is not exactly the reason you wrote, the fact is that the function cannot see variables that are outside the function. In order for the function to see them, you need to pass the variable as an argument to the function. That is, you need to change line 86 like this: cypher(key). But as you can see, this will give an error, because your function initially does not accept any arguments, in order to fix this we need to add the key argument in line 16 like this: def cypher(key):. There is the site where you can read more about it https://levelup.gitconnected.com/5-types-of-arguments-in-python-function-definition-e0e2a2cafd29
Python Code Connect-N Game.
Hi there, I need help with detecting the winner for the 8 directions in Connect N. The game is like Connect 4, but the user inputs N to whatever they want it to be. So could be Connect 5, or 6, etc. However, at the moment, my code is not detecting the 8 directions. I really am struggling with this function. Can someone show me how some code that would work to apply into my def have_winner function.
Thank you!
Instructions for the game
# GLOBAL VARIABLES
N = 5
num_row = N + 3
num_col = N + 2
disk = ['\u2B1C', '\u26AA', '\u26AB']
board = []
def init_board(n):
'''initialise the board'''
global N, num_row, num_col
N = n
num_row = n + 3
num_col = n + 2
for c in range(num_col):
board.append([0]*num_row)
def display():
'''print the board'''
to_print = " "
for i in range(num_col):
to_print = to_print + f'[{i}]'
print(to_print)
for i in range(num_row):
to_print = f'[{i:2}]'
for j in range(num_col):
to_print = f'{to_print}{disk[board[j][i]]:2}'
print(to_print)
def game():
'''play the game'''
n = input('Please input N:')
init_board(int(n))
p = 0
while True:
c = input(f'Player {p} select colomn:')
if c == 'q': # quit the game
print(f'Player {p} resigned')
break
# drop disk
f = drop_disk(int(c), p+1)
if f == 0: # illegal move
print(f'Column {c} is an illegal move')
continue
display()
# check winner and switch side
w = have_winner()
if w == 1:
print(f'Player {p} won')
break
elif w == 2:
print('draw')
break
else:
p = (p + 1)%2
def drop_disk(c, player):
"""player drop a disk at ch colomn. Return 1 if successfully drop the disk, return 0 if this is a illegal move, e.g. the colomn is full."""
if board[c][0] != 0:
return 0
for r in range(num_row -1, -1, -1):
if board[c][r] == 0:
board[c][r] = player
return 1
return 0
def have_winner():
"""return 1 if there is a winner, return 2 if the board is full, return 0 otherwise"""
for c in range(num_col):
for r in range(num_row):
if board[c][r] == 0:
return 0
return 2
# MAIN CODE
game()
I am not sure why do i get this error from the console:
<<
print stirngp[state[i][j]]
^
SyntaxError: invalid syntax
<<
Furthermore it seems that the IDE put a red close on the following code line
line = raw_input("Enter:")
I am not sure what did i do wrong, the following code is as shown below
def isTerminal(state):
stateT = zip(*state)
for i in range(3):
if all(state[i][0] == j for j in state[i]) and state[i][0] != 0:
return state[i][0]
if all(stateT[i][0] == j for j in stateT[i]) and stateT[i][0] != 0:
return stateT[i][0]
if (state[0][0] == state[1][1] == state[2][2]) or \
(state[0][2] == state[1][1] == state[2][0]):
if state[1][1] != 0:
return state[1][1]
for i in range(3):
if 0 in state[i]:
return None
return 0
def succ(state):
# print state
countX = 0
countO = 0
for i in range(3):
for j in range(3):
if state[i][j] == 1: countX = countX + 1
if state[i][j] == -1: countO = countO + 1
if countX > countO:
player = "MIN"
else:
player = "MAX"
succList = []
v = {"MIN":-1,"MAX":1}
for i in range(3):
for j in range(3):
if state[i][j] == 0:
succ = [k[:] for k in state]
succ[i][j] = v[player]
succList = succList + [succ]
# print succList
return succList
def nextplay(player):
if player == "MIN":
return "MAX"
else:
return "MIN"
def minimax(state,alpha,beta,player):
value = isTerminal(state)
if value != None:
# print "TERMINAL:", state, value, player
return value
if player == "MIN":
for y in succ(state):
beta = min(beta, minimax(y,alpha,beta,"MAX"))
if beta <= alpha: return alpha
return beta
if player == "MAX":
for y in succ(state):
alpha = max(alpha, minimax(y,alpha,beta,"MIN"))
if alpha >= beta: return beta
return alpha
def printing(state):
p = {-1:"O",0:".",1:"X"}
for i in range(3):
for j in range(3):
print p[state[i][j]],
print ""
print ""
def main():
state = [[0,0,0],
[0,0,0],
[0,0,0]]
val = isTerminal(state)
while val == None:
line = raw_input("Enter:")
x = line.split(",")
a = int(x[0]); b = int(x[1])
state[a][b] = 1
if isTerminal(state) != None:
printing(state)
return
# determine which successive state is better
succList = succ(state)
succValList = []
for i in succList:
succValList = succValList + [(minimax(i,-1,1,"MAX"),i)]
succValList.sort(key=lambda x:x[0])
state = succValList[0][1] # can also randomly choose other states of the same minimax value
printing(state)
val = isTerminal(state)
if __name__ == '__main__':
main()
As far as i know you can't use raw_input() in Python 3. It's been changed to just input()
http://docs.python.org/dev/whatsnew/3.0.html
also what is stringp? is it an existing list?
if so then state[i][j] MUST return an integer so you can retrieve the item at that index of stringp[]
I have coded a game of noughts and crosses, and am using a while loop to run the game. However, I must be doing something wrong as I cannot get it to print 'You win' or 'You lose' when a row/column/diagonal of X or O is on the board. I know the function that checks the board works as I have tested it on its own, by putting Xs in the board manually, but when playing the game normally it completely disregards any Xs or Os in 3. Here is the code, sorry it's abit long. Thanks
import random
board = [
['1','-','-','-'],
['2','-','-','-'],
['3','-','-','-'],
['#','1','2','3'],
[' ',' ',' ',' ']
]
rows = {
'top':
board[0][1:],
'mid':
board[1][1:],
'bottom':
board[2][1:]
}
cols = {
'left':
[board[0][1],
board[1][1],
board[2][1]],
'mid':
[board[0][2],
board[1][2],
board[2][2]],
'right':
[board[0][3],
board[1][3],
board[2][3]]
}
diags = {
'top-bottom':
[board[0][1],
board[1][2],
board[2][3]],
'bottom-top':
[board[2][1],
board[1][2],
board[0][3]]
}
gamestate = 1
def print_board(board):
for i in board:
print " ".join(i)
def win_check(rows,cols,diags):
plrWin = ['X','X','X']
cpuWin = ['O','O','O']
global gamestate
for i in rows.values():
if i == plrWin:
return True
gamestate = 0
elif i == cpuWin:
return False
gamestate = 0
for x in cols.values():
if x == plrWin:
return True
gamestate = 0
elif x == cpuWin:
return False
gamestate = 0
for y in diags.values():
if y == plrWin:
return True
gamestate = 0
elif y == cpuWin:
return False
gamestate = 0
def game_entry():
print "Your turn."
coordY = input("Guess column: ")
coordX = input("Guess row: ")
board[coordX - 1][coordY] = 'X'
def random_location():
while True:
cpuX = random.randint(1,3)
cpuY = random.randint(1,3)
if (board[cpuX - 1][cpuY] == 'X') or (board[cpuX - 1][cpuY] == 'O'):
continue
else:
board[cpuX - 1][cpuY] = 'O'
break
while gamestate == 1:
print_board(board)
game_entry()
random_location()
if win_check(rows,cols,diags) == True:
print "You win!"
gamestate = 0
break
elif win_check(rows,cols,diags) == False:
print "You lose."
gamestate = 0
break
else:
continue
Your problem is with all of the rows and cols dictionaries:
>>> l = [[1, 2, 3], [4, 5, 6]]
>>> x = l[0][1:]
>>> x
[2, 3]
>>> l[0][1] = 4
>>> x
[2, 3]
As you can see, they don't update when the board is changed. You'll have to find another way of doing this.
I would just use a few loops and check the diagonals manually:
def has_someone_won(board):
# Rows
for row in board:
if row[0] == row[1] == row[2] != '-':
return True
# Columns
for i in range(3):
if board[0][i] == board[1][i] == board[2][i] != '-':
return True
# Diagonal 1
if board[0][0] == board[1][1] == board[2][2] != '-':
return True
# Diagonal 2
if board[2][0] == board[1][1] == board[0][2] != '-':
return True
# There's no winner
return False