键盘事件 - Pygame

时间:2014-03-25 16:53:48

标签: events python-3.x keyboard pygame

有没有人知道如何制作它所以我的代码只会在按下空格键时发射子弹?现在任何一把钥匙都让我的角色射中了一颗子弹,但是如果可能的话我想改变它,到目前为止我的代码是:

import pygame, sys, random

pygame.init()

screen_width = 800
screen_height = 600
screen = pygame.display.set_mode([screen_width, screen_height])
all_sprites_list = pygame.sprite.Group()
block_list = pygame.sprite.Group()
bullet_list = pygame.sprite.Group()
BLACK    = (   0,   0,   0)
WHITE    = ( 255, 255, 255)
background = pygame.image.load('space.jpg')
pygame.display.set_caption("Alien Invasion!")
explosion = pygame.mixer.Sound('explosion.wav')
score = 0

class Block(pygame.sprite.Sprite):
    def __init__(self, color):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.image.load("spaceship.png")
        self.rect = self.image.get_rect()

class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

        self.x=0
        self.y=0
        self.image = pygame.image.load("alien.png")
        self.rect = self.image.get_rect()

    def update(self):

        pos = pygame.mouse.get_pos()
        self.rect.x = pos[0]

    def render(self):

        if (self.currentImage==0):
            screen.blit(self.image, (self.x, self.y))

class Bullet(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("bullet.png")
        self.rect = self.image.get_rect()

    def update(self):

        self.rect.y -= 3

for i in range(30):
    block = Block(BLACK)
    block.rect.x = random.randrange(screen_width)
    block.rect.y = random.randrange(330)
    block_list.add(block)
    all_sprites_list.add(block)

player = Player()

all_sprites_list.add(player)

done = False

clock = pygame.time.Clock()

player.rect.y = 480

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

        elif event.type == pygame.KEYDOWN:
            bullet = Bullet()
            bullet.rect.x = player.rect.x
            bullet.rect.y = player.rect.y
            all_sprites_list.add(bullet)
            bullet_list.add(bullet)

    all_sprites_list.update()

    for bullet in bullet_list:

        block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True)

        for block in block_hit_list:
            explosion.play()
            bullet_list.remove(bullet)
            all_sprites_list.remove(bullet)
            score += 10

        if bullet.rect.y < -10:
            bullet_list.remove(bullet)
            all_sprites_list.remove(bullet)

    font = pygame.font.Font(None, 36)
    text = font.render("Score: " + str(score), True, WHITE)
    textpos = text.get_rect(centerx=screen.get_width()/12)

    screen.blit(background, (0,0))

    screen.blit(text, textpos)

    all_sprites_list.draw(screen)

    pygame.display.update()

    clock.tick(80)

pygame.quit()

另外,如果可能的话,我想让它一旦按下退出键,游戏退出。为此,我有这个代码:

    if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):

然而,由于某些原因它似乎无法正常工作:(我是python的新手,所以任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:4)

右键!首先是第一件事!

要按空格键来发射子弹,您需要添加以下内容:

elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
    bullet = Bullet()
    bullet.rect.x = player.rect.x
    bullet.rect.y = player.rect.y
    all_sprites_list.add(bullet)
    bullet_list.add(bullet)    

上述解决方案将通过按空格键

生成项目符号

如果您想通过按空格键来激活单个子弹,那么您需要 创建一个k_space变量,该变量将在上述事件中设置为True,并在循环结束时设置为False

所以为了做到这一点你必须改变一些东西:)

k_space = False #---- Initialize the boolean for the space key here
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

        elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            k_space = True #----- Set it to true here

    if k_space: #---- create a bullet when the k_space variable is set to True
        bullet = Bullet()
        bullet.rect.x = player.rect.x
        bullet.rect.y = player.rect.y
        all_sprites_list.add(bullet)
        bullet_list.add(bullet)   

    k_space = False #------ Reset it here

    all_sprites_list.update()

    for bullet in bullet_list:

        block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True)

        for block in block_hit_list:
            explosion.play()
            bullet_list.remove(bullet)
            all_sprites_list.remove(bullet)
            score += 10

        if bullet.rect.y < -10:
            bullet_list.remove(bullet)
            all_sprites_list.remove(bullet)

    font = pygame.font.Font(None, 36)
    text = font.render("Score: " + str(score), True, WHITE)
    textpos = text.get_rect(centerx=screen.get_width()/12)

    screen.blit(background, (0,0))

    screen.blit(text, textpos)

    all_sprites_list.draw(screen)

    pygame.display.update()

    clock.tick(80)

更改上面的代码会使每个空格键只弹出one子弹! 如果你想通过按空格键来产生多个子弹,只需坚持我提出的第一个改变:)

最后,如果你想通过按下转义键来关闭程序,那么你只需要更改循环中的第一个事件:

而不是:

if event.type == pygame.QUIT:
    done = True

您可以将其更改为:

if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
    done = True

这应该安全地退出你的程序:)

希望有所帮助!

干杯,

亚历

(编辑)

奥莱特!只拆分两个退出事件,它应该顺利运行:)

    #code above
    if event.type == pygame.QUIT:
        pygame.quit()
        sys.exit()
    if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
        pygame.quit()
        sys.exit()
    #code below

最后:)如果你想让子弹完全从宇宙飞船的中间产卵, 只需在k_space检查中添加此代码:

    if k_space:
        bullet = Bullet()
        bullet.rect.x = player.rect.center[0] - bullet.rect.width/2
        bullet.rect.y = player.rect.center[1] - bullet.rect.height/2
        all_sprites_list.add(bullet)
        bullet_list.add(bullet)

唷!希望能帮助交配:)

干杯!