我的问题:我遇到的问题是,我试图使用用户的输入来验证他们是否可以在我制作的播放板上上下左右移动。也就是说,每次我尝试使用WASD移动方向时,它都会将我重定向到随机位置,而不是正确的方向。我还注意到,无论我在黑板上的哪个位置,它都会把我放在相同的位置。
我试过了:
我试着评估我输入的值,但没有帮助我。我也尝试过以不同的方式更新它,但不知道如何去做。在我弄不清楚之后,我通过谷歌和这里的帖子寻求帮助,但无法掌握或理解到底发生了什么。
这是我目前为止的代码:
def CommandPlayer(player, board):
VALID_INPUTS = ["W","A","S","D","Q"]
while True: #input validation loop
userInput = input("Enter a direction (WASD or Q to quit): ").upper()
if userInput in VALID_INPUTS:
break
if userInput == "Q":
input("Goodbye!")
sys.exit(0)
#capture the current player location
row = player['row']
col = player['col']
#remove player from board
player['row'] = row
player['col'] = col
board[row][col] = "."
#if statement that increment or decrement row/col based on input
#there will be four of these
if userInput == "W":
if row == 0: #if row is currently 0:
row += -1 #set row to max row position
else: #else:
row -= 1 #row -= 1
elif userInput == "A":
if col == 0: #if col is currently 0:
col += -1 #set col to max col position
else: #else:
col -= 1 #col -= 1
elif userInput == "S":
if row == -1: #if row is at max:
row = 0 #row = 0
else: #else:
row += 1 #row += 1
elif userInput == "D":
if col == -1: #if col is at max:
col = 0 #col = 0
else: #else:
col += 1 #col += 1
#put player on board
#update row and col in player
board[row][col] = "@"
return board, player
玩家在棋盘上输入的表示:
在这里你会看到一个图片的板。黑板上圈着的@是它随机出现的地方,这很好!虽然另一个@是当我输入W时它移动的位置,这是错误的。
板输出
说明
你是updating the board
与new col and row values
但not the correspoding player attributes
。这就是为什么你会在游戏中看到不止一次玩家(@)。实际的玩家(@)永远不会移动,你只是将角色从点(.)更改为棋盘上其他地方的@。
解决方案在if语句之后更新玩家位置,示例如下。你在if语句之前写了这两行。
...
#put player on board
#update row and col in player
board[row][col] = "@"
player['row'] = row # add this
player['col'] = col # and that
return board, player
你也写了一个正确的评论