我创建了一个程序,要求玩家的移动,然后玩家在网格内移动。我还试图验证输入,以便玩家不会超出网格的限制,并且这样做会调用要求玩家移动的功能,这样他们就可以继续进行移动直到这是一个有效的举措。但是,再次调用该函数时,x_move和y_move不会被更新,这意味着即使用户现在有效,也会不断要求用户重新输入他们的输入。我认为这与值x_move和y_move的返回有关,就像我在使用用户的新输入后打印它们一样,它们保持不变? 我的代码如下:
def get_move():
advice = 'Please enter your move in two integers, vertical, then horizontal, separated by a space. Use positive numbers for up and right, negative for down and left.'
example = 'For example, an input of \'2 2\' would be 2 moves vertically, and 2 moves horizontally.'
#Here I am joining the two inputs for ease of input for the user and so that the input is easier to work with than two serparate ones. Not sure how this will work yet with validation...
move = input(advice + example)
coor=move.split()
while len(coor)!=2:
print('Invalid input- too many or too few co-ordinates')
print('')
advice = 'Please enter your move in two integers, vertical, then horizontal, separated by a space. Use positive numbers for up and right, negative for down and left.'
example = 'For example, an input of \'2 2\' would be 2 moves vertically, and 2 moves horizontally.'
#Here I am joining the two inputs for ease of input for the user and so that the input is easier to work with than two serparate ones. Not sure how this will work yet with validation...
move = input(advice + example)
coor=move.split()
#Here I am splitting the input using whitespace, hence why nothing is in the bracket
move = move.split()
#Now I am declaring the variables that are assigned to the split move input
y_move,x_move=move
#And now assigning them as integers
x_move = int(x_move)
y_move = int(y_move)
return x_move, y_move
def update_board(b, current_y_loc, current_x_loc):
while (-1>= current_y_loc-y_move) or (current_y_loc-y_move>size_of_grid):
print('INVALID INPUT')
get_move()
while (-1>= current_x_loc+x_move) or (current_x_loc+x_move>size_of_grid):
print('INVALID INPUT')
get_move()
b[current_y_loc-y_move][current_x_loc+x_move] = player_location
current_y_loc -= y_move
current_x_loc += x_move
print("current location = ", current_x_loc, current_y_loc)
return current_y_loc, current_x_loc
答案 0 :(得分:3)
您需要实际将输出从get_move()
传递到x_move
和y_move
,即x_move, y_move = get_move()
答案 1 :(得分:1)
我认为它与x_move和y_move变量的范围有关。他们在get_move()
中声明并分配了值,但之后在update_board()
中引用了它们。
我尝试在while语句之前将x_move,y_move=get_move()
添加到update_board()
,并在while语句中将调用更改为get_move()
以匹配。
此外,这稍微超出了问题的范围,但我尝试重写while循环,以便你有一个循环同时检查所有四个条件,否则你可能会结束结果如下: