我为hw制作了一个用于python的2D棋盘游戏。
我让用户为电路板尺寸输入一个整数。例如,7。我在发布之前修改了一下(仅显示重要的内容)。功能如下
def asksize():
while True:
ask=raw_input("Input board size: ")
try:
size=int(ask)
return size
except ValueError:
print "Please enter a integer"
因为它是可变的板大小,我需要在其他函数中重用变量大小,用它来检查用户的移动是否有效,如何重用变量?
def checkmove(move):
#move is sth like eg. A1:B2
move=move.split(":") #I split it so it becomes ['A','1']['B','2']
if size>=int(move[0][1]) and int(move[0][1])>=1 and size>=int(move[1][1]) and int(move[1][1])>=1: #for example if board size is 7, this is to check whether user input is between 1 to 7 within the board
return True
else:
return False
在我的checkmove函数中,我不能在我的参数中使用size,因为它没有定义,我怎样才能使它可行?
由于
答案 0 :(得分:1)
将变量大小设为全局是一个选项,但您应该将您的函数视为API,并在游戏主要部分上使用它们。
所以存储输入如下:
size = asksize() #store the data on to variable called size
#then just call your check move
checkmove(x)
无论如何这是一个糟糕的练习,最好通过游戏代码中的函数传递变量:
#definitions
def asksize():
#your code here
def checkmove(move, size):
#your code here
#game set up here
size = asksize()
#more set up stuff
#end of game set up
#Game Main code
while True: #main game bucle
#Game stuff here
checkmove(move, size)
#more game stuff
答案 1 :(得分:1)
考虑创建一个代表董事会的类。那么size自然就是一个实例变量
class Board(object):
def asksize(self):
while True:
ask=raw_input("Input board size: ")
try:
self.size=int(ask)
return
except ValueError:
print "Please enter a integer"
def checkmove(self, move):
#move is sth like eg. A1:B2
move=move.split(":") #I split it so it becomes ['A','1']['B','2']
if self.size>=int(move[0][1]) and int(move[0][1])>=1 and self.size>=int(move[1][1]) and int(move[1][1])>=1: #for example if board size is 7, this is to check whether user input is between 1 to 7 within the board
return True
else:
return False
# Use it like this
board = Board()
board.asksize()
move = some_function_that_returns_a_move()
board.checkmove(move)
答案 2 :(得分:0)
你(至少)有两个选择:
size
作为checkmove
函数中的参数传递。size= asksize()
函数中调用checkmove
。我认为将大小作为参数传递更有意义,因为那时你可以为AI播放器重用相同的功能......
那是:
def checkmove(move, size):
# rest of definition
# main bit of code
size = asksize()
checkmove(move, size)
答案 3 :(得分:0)
或简单地制作'尺寸'作为全局变量,无论如何,python将在下一个更高的范围内搜索变量。你可以尝试这样:
size = 0
def asksize():
global size
while True:
ask=raw_input("Input board size: ")
try:
size=int(ask)
return size
except ValueError:
print "Please enter a integer"
def checkmove(move):
global size
# move is sth like eg. A1:B2
move = move.split(":") # I split it so it becomes ['A','1']['B','2']
if size >= int(move[0][1]) and int(move[0][1]) >= 1 and size >= int(move[1][1]) and int(move[1][
1]) >= 1: # for example if board size is 7, this is to check whether user input is between 1 to 7 within the board
return True
else:
return False