英文:
If statement is still running code even when condition is false
问题
以下是您提供的代码的翻译:
这个程序应该循环遍历一个二维列表,如果一个随机数小于敌人可以生成在房间中的百分比机会,那么循环的索引就会被分配给一个敌人。当x和y等于玩家的起始位置时,代码不应该运行,但条件为假时代码仍然运行。
import random, os
while True:
os.system('clear')
map = [
['#', '-', '+', '-', '%'],
['+', '#', '|', '#', '+'],
['+', '-', '%', '-', '#'],
['|', '#', '+', '#', '+'],
['+', '%', '-', '+', '+']
]
startPlayerX = round(len(map[0])/2)
startPlayerY = round(len(map)/2)
monsterMap = [[0 for x in range(5)] for y in range(5)]
for x in range(5):
for y in range(5):
if x != startPlayerX and y != startPlayerY:
monsterChance = random.randint(1, 100)
if map[x][y] == '#':
if monsterChance <= 49:
monsterMap[x][y] = '&'
elif monsterChance > 49 and monsterChance <= 70:
monsterMap[x][y] = '@'
elif map[x][y] == '%':
if monsterChance < 35:
monsterMap[x][y] = '&'
elif monsterChance > 35 and monsterChance <= 50:
monsterMap[x][y] = '@'
break
for x in range(5):
for y in range(5):
print(monsterMap[x][y], ' ', end = '')
print()
希望这可以帮助您理解代码的功能。
英文:
The program is supposed to loop through a 2d list and if a random number is less than the percentage chance that an enemy can spawn in the room, then the index the loop is on is assigned to an enemy. The code is not supposed to run when x and y are equal to the starting position of the player but the code runs anyway even when the condition is false
import random, os
while True:
os.system('clear')
map = [
['#', '-', '+', '-', '%'],
['+', '#', '|', '#', '+'],
['+', '-', '%', '-', '#'],
['|', '#', '+', '#', '+'],
['+', '%', '-', '+', '+']
]
startPlayerX = round(len(map[0])/2)
startPlayerY = round(len(map)/2)
monsterMap = [[0 for x in range(5)] for y in range(5)]
for x in range(5):
for y in range(5):
if x != startPlayerX and y != startPlayerY:
monsterChance = random.randint(1, 100)
if map[x][y] == '#':
if monsterChance <= 49:
monsterMap[x][y] = '&'
elif monsterChance > 49 and monsterChance <= 70:
monsterMap[x][y] = '@'
elif map[x][y] == '%':
if monsterChance < 35:
monsterMap[x][y] = '&'
elif monsterChance > 35 and monsterChance <= 50:
monsterMap[x][y] = '@'
break
for x in range(5):
for y in range(5):
print(monsterMap[x][y], ' ', end = '')
print()
答案1
得分: 1
你的代码问题在于,在if条件中使用了and
运算符来检查x
和y
是否都不等于起始位置。这意味着如果x
或y
中的任何一个等于起始位置,条件仍然会为真。要解决这个问题,你应该使用or
运算符,这样只有当x
或y
中的一个等于起始位置时,代码才会运行。
将这行代码:
if x != startPlayerX and y != startPlayerY:
改为:
if x != startPlayerX or y != startPlayerY:
英文:
The issue in your code is that you're using the and
operator in the if condition to check if both x
and y
are not equal to the starting position. This means that if either x
or y
is equal to the starting position, the condition will still be true. To fix this, you should use the or
operator instead, so the code won't run if either x
or y
equals the starting position.
Change this line:
if x != startPlayerX and y != startPlayerY:
to:
if x != startPlayerX or y != startPlayerY:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论