Python 基于文本的二维数组“;游戏“;
我通过构建一个基于2D文本的小游戏来学习嵌套列表。我已经有了一个程序,名为Python 基于文本的二维数组“;游戏“;,python,arrays,Python,Arrays,我通过构建一个基于2D文本的小游戏来学习嵌套列表。我已经有了一个程序,名为print\u board,它接受代表棋盘的字符列表(如棋盘游戏)。为了保持简单,下一步是创建一个名为move\u bot的过程,该过程接受三个参数: 由带有字符的嵌套列表表示的板。空格由“.”字符表示。所有其他角色都是机器人无法通过的 机器人由四个值的列表表示,包括机器人名称字符串、机器人在板上x和y位置的整数值,以及用于在板上显示机器人的单个字符串 一个移动方向,由一个元组表示,该元组分别具有x(水平)和/或y(垂直)
print\u board
,它接受代表棋盘的字符列表(如棋盘游戏)。为了保持简单,下一步是创建一个名为move\u bot
的过程,该过程接受三个参数:
def print_board (board):
"""
Receives a list of lists of characters and displays them
to the screen such that a rectangular border is drawn around
the entire board.
Examples:
>>> print_board([list('..'),list('..')])
+--+
|..|
|..|
+--+
>>> print_board([list('..'),list('.....'),list('..')])
+-----+
|.. |
|.....|
|.. |
+-----+
"""
max_len = max([len(r) for r in board])
bound = "+"+"-"*max_len+"+\n"
disp = bound
for r in range(len(board)):
disp += "|"
for c in range(len(board[r])):
disp += board[r][c]
for e in range(max_len - len(board[r])):
disp+=" "
disp+="|\n"
print(disp+bound,end='')
这个很好用。我遇到的问题是move\u bot
过程。也就是说,我不知道从哪里开始。到目前为止,我真的只有这一点:
def move_bot(board, robot, move_dir):
print_board(board)
有人能帮我弄清楚如何让它正常工作吗?所需输出如下:
>>>b = [list('....R'),list('.W.'),list('..W')] #create board
>>>robot = ["Robbie",4,0,'R'] #create the robot
>>>print_board(b) #Display initial board
+-----+
|....R|
|.W. |
|..W |
+-----+
>>>move_bot(b,robot,(-1,0)) #move left
>>> move_bot(b,robot,(-1,0)) #move left
>>> move_bot(b,robot,(0,1)) #move down
>>> print_board(b) #R is now 2 left and 1 down
+-----+
|.....|
|.WR |
|..W |
+-----+
>>> move_bot(b,robot,(1,0)) #Off the end of a row!
Traceback (most recent call last):
...
IndexError: Robbie can't move to (3,1)
>>> move_bot(b, robot,(-1,0)) #Bump into a wall to the left!
Traceback (most recent call last):
...
ValueError: Robbie bumped into something!
您可以尝试以下方法:
def move_bot(board, robot, move_dir):
# Obtain the starting position
x_start = robot[1]
y_start = robot[2]
# Calculate the new robot position.
x_new = x_start + move_dir[0]
y_new = y_start + move_dir[1]
# Now, you have to check if the new location is within range of the board
# If it is in range, check if it contains a ".". If either of these things
# is not true, raise an error.
# If no error was raised, you can change the old position of the robot on
# the board to ".", and put robot[3] in the new position.
b[y_start][x_start] = "."
b[y_new][x_new] = robot[3]
# Oh, and don't forget to update Robbie!
robot[1] = x_new
robot[2] = y_new
return(b, robot)
请不要破坏你自己的帖子。当你在这里发帖时,你给了SO分发CCBYSA4.0下内容的权利。任何故意破坏行为都将恢复原状。