如何解决(Pygame) 这个函数有什么问题?
所以,我一直在研究用 Pygame 制作的蛇游戏。到目前为止,一切都很好,除了一个问题:当蛇吃水果时,有时会出现在蛇体内的水果(随机产卵)。所以,为了避免这种情况,我做了这个功能:
def random_fruit(body_pos):
global general_fruit_x,general_fruit_y # Fruit rectangle coordinates
while True:
general_fruit_x = randrange(window[0] // snake.w) * snake.w # (Snake is a pygame.Rect)
general_fruit_y = randrange(window[1] // snake.h) * snake.h
if len(list(filter(lambda z: body_pos == (general_fruit_x,general_fruit_y),body_pos))) > 0:
continue # If the spawning position of the fruit is the same as the snake's body,we continue the loop
else:
break # If not,we are done
set_obj_coordinates(general_fruit,general_fruit_x,general_fruit_y) # set fruit random position
并在主游戏循环中实现:
if fruit_eated:
random_ind1 = random_ind2
snake_len += 1
apple_sound.play()
random_fruit(snake_pos) # snake_pos is a list of tuples with all snake's body coordinates
for m in range(3):
snake_imgs[random_ind1][m] = img("snake_" + snake_colors[random_ind1] + str(m + 1)) # Reset snake image
random_ind2 = randint(0,3)
if x_move < 0:
rotate_imgs(90,random_ind1)
if x_move > 0:
rotate_imgs(-90,random_ind1)
if y_move > 0:
rotate_imgs(180,random_ind1)
if y_move < 0:
pass
但似乎 random_fruit 函数忽略了蛇身体的状况。
完整代码如下:https://github.com/n4tm/PySnake/tree/main/snake
解决方法
您必须检查身体的 any
位置是否等于水果的新随机位置:
`if len(list(filter(lambda z: body_pos == (general_fruit_x,general_fruit_y),body_pos))) > 0:
if any(pos == (general_fruit_x,general_fruit_y) for pos in body_pos):
random_fruit
函数:
def random_fruit(body_pos):
global general_fruit_x,general_fruit_y
while True:
general_fruit_x = randrange(window[0] // snake.w) * snake.w
general_fruit_y = randrange(window[1] // snake.h) * snake.h
if not any(pos == (general_fruit_x,general_fruit_y) for pos in body_pos):
break
set_obj_coordinates(general_fruit,general_fruit_x,general_fruit_y)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。