如何让敌人改变方向

2024-06-07 16:40:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图用pygame编写一个小游戏,目标是捕捉尽可能多的粪便,避免感染粪便,但我无法让敌人在撞到墙时改变方向

import pygame
from pygame.locals import *

pygame.init()
pygame.display.set_caption('POOPISTINKI')

screen_width = 800
screen_height = 600
game_running = True
pl_x = int(screen_width/10)
pl_y = int(screen_height/2)
pl_width = 80
pl_height = 40
pl_vel = 30
en_width = 80
en_height = 40
en_x = screen_width - screen_width/10 - en_width
en_y = int(screen_height/2)
en_yvel = 10

screen = pygame.display.set_mode((screen_width, screen_height))

while game_running:
    pygame.time.delay(100)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_running = False

        if event.type == MOUSEBUTTONDOWN:
            if event.button == 4 and pl_y > pl_vel:
                pl_y -= pl_vel

            elif event.button == 5 and pl_y < screen_height - pl_width:
                pl_y += pl_vel

    if en_y == 0:
        en_y += en_yvel

    if en_y == screen_height - en_height:
        en_y -= en_yvel

    screen.fill((0, 0, 0))
    pygame.draw.rect(screen, (105, 255, 125), (pl_x, pl_y, pl_width, pl_height))
    pygame.display.update()

    pygame.draw.rect(screen, (255, 125, 115), (en_x, en_y, en_width, en_height))
    pygame.display.update()

pygame.quit()

Tags: eventgameifdisplaywidthscreenpygamerunning
1条回答
网友
1楼 · 发布于 2024-06-07 16:40:43

一旦敌人en_y击中窗口的顶部或底部,您必须反转en_yvel
此外,我建议分别使用^{}^{}来控制每秒的触发器

en_yvel = 10

screen = pygame.display.set_mode((screen_width, screen_height))
clock = pygame.time.Clock()

while game_running:
    clock.tick(10)

    for event in pygame.event.get():
        # [...]

    en_y += en_yvel
    if en_y <= 0 or en_y >= screen_height - en_height:
        en_yvel = -en_yvel

    # [...]

相关问题 更多 >

    热门问题