python小游戏飞机大战
定义到子弹发射的代码总是不能用
import pygame
import random
FPS=60
WHITE=(255,255,255)
GREEN=(0,255,0)
RED=(255,0,0)
YELLOW=(0,0,255)
WIDTH=500
HEIGHT=600
pygame.init()
screen=pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("飞机大战")
clock=pygame.time.Clock()
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image=pygame.Surface((50,40))
self.image.fill((0,255,0))
self.rect=self.image.get_rect()
self.rect.centerx=WIDTH/2
self.rect.bottom=HEIGHT-10
self.speedx=10
def update(self):
key_pressed=pygame.key.get_pressed()
if key_pressed[pygame.K_RIGHT]:
self.rect.x +=self.speedx
if key_pressed[pygame.K_LEFT]:
self.rect.x -=self.speedx
if self.rect.right>WIDTH:
self.rect.right=WIDTH
if self.rect.left<0:
self.rect.left=0
def shoot(self):
bullet=Bullet(self.rect.centerx,self.rect.top)
all_sprites.add(bullet)
class Bullet(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image=pygame.Surface((10,20))
self.image.fill(YELLOW)
self.rect=self.image.get_rect()
self.rect.centerx=x
self.rect.bottom=y
self.speedy=-10
def update(self):
self.rect.y+=self.speedy()
if self.rect.bottom<0:
self.kill()
class Rock(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image=pygame.Surface((30,40))
self.image.fill(RED)
self.rect=self.image.get_rect()
self.rect.x=random.randrange(0,WIDTH-self.rect.width)
self.rect.y=random.randrange(-100,-40)
self.speedy=random.randrange(2,10)
self.speedx=random.randrange(-3,3)
def update(self):
self.rect.y+=self.speedy
self.rect.x+=self.speedx
if self.rect.top>HEIGHT or self.rect.left>WIDTH or self.rect.right<0:
self.rect.x=random.randrange(0,WIDTH-self.rect.width)
self.rect.y=random.randrange(-100,-40)
self.speedy=random.randrange(2,10)
self.speedx=random.randrange(-3,3)
all_sprites=pygame.sprite.Group()
player=Player()
all_sprites.add(player)
rock=Rock()
all_sprites.add(rock)
for i in range(8):
r=Rock()
all_sprites.add(r)
running=True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
elif event.type==pygame.KEYDOWN:
if event.key==pygame.K_SPACE:
player.shoot()
all_sprites.update()
screen.fill(WHITE)
all_sprites.draw(screen)
pygame.display.update()
pygame.quit()
问题位置
if event.type==pygame.QUIT:
running=False
elif event.type==pygame.KEYDOWN:
if event.key==pygame.K_SPACE:
player.shoot()
运行只后按空格