提问人:Alegra 提问时间:6/9/2023 最后编辑:AkeAlegra 更新时间:6/10/2023 访问量:50
无法结束循环
Trouble ending a loop
问:
我是 Python 的新手,我必须做这个练习,我需要模拟一只猫在几条线上行走。如果猫找到零食 ( * ),他就会吃掉它,并且位置被地板 ( _ ) 取代。 如果猫找到一个洞( ),他会掉到下一行,并继续朝同一个方向走。这是猫移动到另一条线的唯一方法。 如果猫到达队伍的尽头,它就会改变方向,然后再次走队伍,吃他第一次没有吃的零食。如果猫没有找到另一个洞并到达线的另一端,则循环需要停止。停止循环的另一种方法是,如果猫在最后一行找到一个洞。输出应该是猫在途中发现的零食数量。
我遇到了很多麻烦,试图让猫停下来,只有当它已经到达线的两端时。请帮忙!
这些图像有输入(黑色)和猫应该如何走路(红色)的示例。
platforms = []
n = int(input())
for _ in range(n):
platforms.append(list(input()))
# Path simulation
treats = 0
row = 0
column = 0
direction = 1 # 1 represents the right direction and -1 represents the left direction
while True:
if row >= n:
break
if column < 0 or column >= len(platforms[row]):
column -= direction
direction *= -1 # changes direction at the edges of the rows
# Check if the cat reached both ends of the line without finding any hole
if (column == 0 and platforms[row][column] != '.') or (column == len(platforms[row]) and platforms[row][column] != '.'):
break
elif platforms[row][column] == '_':
column += direction
elif platforms[row][column] == '*':
treats += 1
platforms[row][column] = '_' # replaces the treat with floor ( _ )
column += direction
elif platforms[row][column] == '.':
if row == n:
break
if column == 0 or column == len(platforms[row]):
row += 1 # falls to the lower level in the same column
column += direction # moves to the next column in the same row
else:
row += 1 # falls to the lower level in the same column
column += direction # moves to the next column in the same row
print(treats)
答:
0赞
Selcuk
6/9/2023
#1
你需要一个标志来记住你已经击中了另一个边缘。以下是这个想法的一个微不足道的实现:
# Initialize flag
hit_one_edge = False
while True:
# ...
if column < 0 or column >= len(platforms[row]):
if hit_one_edge:
print("Hit both edges, nowhere to go. Game over.")
break
else:
# This is the first time we hit an edge, keep going
hit_one_edge = True
column -= direction
direction *= -1 # changes direction at the edges of the rows
# ...
elif platforms[row][column] == '.':
# Reset edge flag as we are on a new platform:
hit_one_edge = False
if row == n:
break
# ...
评论
0赞
Alegra
6/9/2023
成功了!谢谢!!!
0赞
Selcuk
6/12/2023
@Alegra 您可以通过单击此答案旁边的复选标记将此答案标记为已接受。
评论