任务目的
0.培养编程思维,提高分析问题能力
1.掌握二维数组(矩阵)
2.掌握循环,分支条件的用法
任务描述
设想有一只机械海龟,它在程序的控制下在屋里四处爬行。海龟拿了一支笔,这只笔或朝
上或朝下,当笔朝下时,海龟用笔画下自己的移动轨迹,当笔朝上时,海龟在移动过程中什么也不画。
使用一个50x50的数组,并把数组初始化为0。从一个装有命令的数组中读取各种命令。不
管是笔朝上还是笔朝下,都要跟踪海龟的当前位置。假定海龟总是从地板上(0,0)出发
,并且开始时笔是朝上的。程序必须处理的一组命令如下:
命令 含义
1 笔朝上
2 笔朝下
3 右转弯
4 左转弯
5,10 向前走10格(或其他的格数)
6 打印50x50的数组
9 数据结束(标记)
假设海龟现在处于靠近地板中心的某个位置,下面的“程序”绘制并打印出了一个12*12的方框。
2
5,12
3
5,12
3
5,12
3
5,12
1
6
9
在海龟爬行过程中,如果笔朝下,把数组floor中对应于海龟所处位置的元素置1。当给出命令6(打印)后,在数组中元素为1的位置全部用#号显示,元素为0的位置全部用*号显示。
编写一个可以处理上述海龟命令的程序。
编写一些其他的海龟命令,用自己编写的海龟命令处理程序解析,画出有趣的形状,比如一个“日”字。
实例
上面的海龟命令,经过我们编写的程序解析后,会打印出下面的图形
import numpy as np
if __name__ == '__main__':
floor = np.zeros((50, 50), dtype='int32')
def print_floor():
row_num = floor.shape[0]
col_num = floor.shape[1]
for i in range(row_num):
for j in range(col_num):
if floor[i,j] == 0:
print('*', end=' ')
else:
print('#', end=' ')
print()
command = """
2
5,12
3
5,12
3
5,12
3
5,12
1
6
9
"""
lstCmd = command.split()
print(lstCmd)
isPenUp = True
#0,1,2,3-----向右,向下,向左,向上
head_direction = 0
xPos = 10
yPos = 10
for cmd in lstCmd:
current_cmd_lst = cmd.split(',')
if len(current_cmd_lst) == 1:
true_cmd = int(current_cmd_lst[0])
if true_cmd == 1:
isPenUp = True
elif true_cmd == 2:
isPenUp = False
elif true_cmd == 3:
head_direction += 1
if head_direction > 3:
head_direction = 0
elif true_cmd == 4:
head_direction -= 1
if head_direction < 0:
head_direction = 3
elif true_cmd == 6:
print_floor()
elif true_cmd == 9:
break
else:
cmd = int(current_cmd_lst[0])
step = int(current_cmd_lst[1])
if cmd == 5:
#向右
if head_direction == 0:
target = xPos + step
if target >= 50:
target = 50
if isPenUp:
xPos = target - 1
else:
floor[yPos,xPos:target] = 1
xPos = target - 1
# 向下
if head_direction == 1:
target = yPos + step
if target >= 50:
target = 50
if isPenUp:
yPos = target - 1
else:
floor[yPos:target,xPos] = 1
yPos = target - 1
# 向左
if head_direction == 2:
target = xPos - step
if target < 0:
target = -1
if isPenUp:
xPos = target + 1
else:
floor[yPos, target+1:xPos] = 1
xPos = target + 1
# 向上
if head_direction == 3:
target = yPos - step
if target < 0:
target = -1
if isPenUp:
yPos = target + 1
else:
floor[target+1:yPos, xPos] = 1
yPos = target + 1
请先登陆 或 注册