我正在用PYGAME创建一款使用PYTHON的游戏,两艘宇宙飞船(红色和黄色)相互emits 炮弹.当需要编写红色emits 代码时,我将射击键与键盘上的字母"u"绑定在一起.然而,当我按下"u"键时,射弹不会开火.

在后来的调试中,我注意到你必须按住"l"键(这会使红色向右移动),并且宇宙飞船必须有向右的速度才能emits 子弹.

我还下载了一些飞船图像和背景的文件,可以在这里找到(点击链接后,点击"代码",然后点击"下载ZIP",然后把它移到你的Python文件中):https://github.com/techwithtim/PygameForBeginners

代码:

import pygame
import os

WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Spaceship Game")

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)

FPS = 60
VEL = 5

BULLET_VEL = 7
MAX_BULLETS = 3

BORDER = pygame.Rect(WIDTH//2 - 5, 0, 10, HEIGHT)
SPACESHIP_WIDTH, SPACESHIP_HEIGHT = 55, 40

YELLOW_HIT = pygame.USEREVENT + 1
RED_HIT = pygame.USEREVENT + 2

YELLOW_SPACESHIP_IMAGE = pygame.image.load(
    os.path.join("Assets", "spaceship_yellow.png"))
YELLOW_SPACESHIP = pygame.transform.rotate(
    pygame.transform.scale(YELLOW_SPACESHIP_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT)), 90)

RED_SPACESHIP_IMAGE = pygame.image.load(
    os.path.join("Assets", "spaceship_red.png"))
RED_SPACESHIP = pygame.transform.rotate(pygame.transform.scale(RED_SPACESHIP_IMAGE, (55, 40)), 270)

SPACE = pygame.transform.scale(pygame.image.load(
    os.path.join("Assets", "space.png")), (WIDTH, HEIGHT))


def draw_window(red, yellow, red_bullets, yellow_bullets):
    WIN.blit(SPACE, (0, 0))

    pygame.draw.rect(WIN, BLACK, BORDER)
    WIN.blit(YELLOW_SPACESHIP, (yellow.x, yellow.y))
    WIN.blit(RED_SPACESHIP, (red.x, red.y))

    for bullet in red_bullets:
        pygame.draw.rect(WIN, RED, bullet)

    for bullet in yellow_bullets:
        pygame.draw.rect(WIN, YELLOW, bullet)

    pygame.display.update()


def yellow_handle_movement(keys_pressed, yellow):
    if keys_pressed[pygame.K_w] and yellow.y - VEL > 0:  # UP KEY YELLOW
        yellow.y -= VEL
    if keys_pressed[pygame.K_a] and yellow.x - VEL > 0:  # LEFT KEY YELLOW
        yellow.x -= VEL
    if keys_pressed[pygame.K_s] and yellow.y + VEL + yellow.height < HEIGHT - 15:  # DOWN KEY YELLOW
        yellow.y += VEL
    if keys_pressed[pygame.K_d] and yellow.x + VEL + yellow.width < BORDER.x:  # RIGHT KEY YELLOW
        yellow.x += VEL


def red_handle_movement(keys_pressed, red):
    if keys_pressed[pygame.K_i] and red.y - VEL > 0:  # UP KEY RED
        red.y -= VEL
    if keys_pressed[pygame.K_j] and red.x - VEL > BORDER.x + BORDER.width:  # LEFT KEY RED
        red.x -= VEL
    if keys_pressed[pygame.K_k] and red.y + VEL + red.height < HEIGHT - 15:  # DOWN KEY RED
        red.y += VEL
    if keys_pressed[pygame.K_l] and red.x + VEL + red.width < WIDTH:  # RIGHT KEY RED
        red.x += VEL


def handle_bullets(yellow_bullets, red_bullets, yellow, red):
    for bullet in yellow_bullets:
        bullet.x += BULLET_VEL
        if yellow.colliderect(bullet):
            pygame.event.post(pygame.event.Event(RED_HIT))
            yellow_bullets.remove(bullet)
        elif bullet.x > WIDTH:
            yellow_bullets.remove(bullet)

    for bullet in red_bullets:
        bullet.x -= BULLET_VEL
        if red.colliderect(bullet):
            pygame.event.post(pygame.event.Event(YELLOW_HIT))
            red_bullets.remove(bullet)
        elif bullet.x < 0:
            red_bullets.remove(bullet)


def main():  # Main Game Loop
    red = pygame.Rect(700, 300, SPACESHIP_WIDTH, SPACESHIP_HEIGHT)
    yellow = pygame.Rect(100, 300, SPACESHIP_WIDTH, SPACESHIP_HEIGHT)

    red_bullets = []
    yellow_bullets = []

    clock = pygame.time.Clock()
    run = True
    while run:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q and len(yellow_bullets) < MAX_BULLETS:
                    bullet = pygame.Rect(yellow.x + yellow.width, yellow.y + yellow.height//2 - 2, 10, 5)
                    yellow_bullets.append(bullet)

                if event.key == pygame.K_u and len(red_bullets) < MAX_BULLETS:
                    bullet = pygame.Rect(red.x, red.y + red.height//2 - 2, 10, 5)
                    red_bullets.append(bullet)
        keys_pressed = pygame.key.get_pressed()
        yellow_handle_movement(keys_pressed, yellow)
        red_handle_movement(keys_pressed, red)

        handle_bullets(yellow_bullets, red_bullets, yellow, red)

        draw_window(red, yellow, red_bullets, yellow_bullets)


if __name__ == "__main__":  # Makes sure that the code won't run if imported 
    main() 

您可以运行代码并亲自查看问题所在,因为我的解释非常糟糕.

推荐答案

You have to check if the yellow bullet collides with the red spaceship and the red bullet collides with the yellow spaceship and not the other way around.
Read also How to remove items from a list while iterating? and iterate through a shallow copy of the bulleted lists.

def handle_bullets(yellow_bullets, red_bullets, yellow, red):
    for bullet in yellow_bullets[:]:                       # <---
        bullet.x += BULLET_VEL
        if red.colliderect(bullet):                        # <---
            pygame.event.post(pygame.event.Event(RED_HIT))
            yellow_bullets.remove(bullet)
        elif bullet.x > WIDTH:
            yellow_bullets.remove(bullet)

    for bullet in red_bullets[:]:                          # <---
        bullet.x -= BULLET_VEL
        if yellow.colliderect(bullet):                     # <---
            pygame.event.post(pygame.event.Event(YELLOW_HIT))
            red_bullets.remove(bullet)
        elif bullet.x < 0:
            red_bullets.remove(bullet)

Python相关问答推荐

使用新的类型语法正确注释ParamSecdecorator (3.12)

在Python中处理大量CSV文件中的数据

需要计算60,000个坐标之间的距离

Pandas 有条件轮班操作

如何制作10,000年及以后的日期时间对象?

当递归函数的返回值未绑定到变量时,非局部变量不更新:

无法连接到Keycloat服务器

我的字符串搜索算法的平均时间复杂度和最坏时间复杂度是多少?

Python Tkinter为特定样式调整所有ttkbootstrap或ttk Button填充的大小,适用于所有主题

(Python/Pandas)基于列中非缺失值的子集DataFrame

如何创建引用列表并分配值的Systemrame列

交替字符串位置的正则表达式

以异步方式填充Pandas 数据帧

Python类型提示:对于一个可以迭代的变量,我应该使用什么?

计算机找不到已安装的库'

Pandas 删除只有一种类型的值的行,重复或不重复

为什么在更新Pandas 2.x中的列时,数据类型不会更改,而在Pandas 1.x中会更改?

关于数字S种子序列内部工作原理的困惑

try 使用RegEx解析由标识多行文本数据的3行头组成的日志(log)文件

Sknowled线性回归()不需要迭代和学习率作为参数