【汇智学堂】-python小游戏(太空阻击之五-无敌战机出现,横向射出子弹)

5.5无敌战机出现,横向射出子弹
飞碟入侵,战机出征。下面是我们要做的事情。
1、在固定坐标位置生成战机。
2、根据战机位置,修改后生成子弹的位置。
3、鼠标每次单击时,生成新子弹。
4、update时,更新子弹的位置坐标。

实现代码如下:

bullet = pygame.image.load(“resources/images/bullet1.png”)
player = pygame.image.load(“resources/images/hero1.png”)

positionPlayer=[100,400]
positionBullet=[positionPlayer[0]+50,positionPlayer[1]+40]
bullets=[]

while running:
screen.blit(background,(0,0))
screen.blit(player,positionPlayer)

for bulletx in bullets:
    bulletx[0]+=5
    screen.blit(bullet,(bulletx[0],bulletx[1]))

for event in pygame.event.get():
    if event.type==pygame.MOUSEBUTTONDOWN:
        bullets.append([150,440]) 

positionPlayer:战机的坐标点。
positionBullet:子弹的坐标点。

将代码整合起来,整合后完整代码如下:

import pygame
from pygame.locals import *
from sys import exit
import random

screen_width, screen_height = 480, 700
screen=pygame.display.set_mode((screen_width, screen_height))
background=pygame.image.load(“resources/images/background2.png”)
pygame.display.set_caption(‘雷雷的太空大战’)
pygame.init()

running=1
flyingsaucers=[]
enemy = pygame.image.load(“resources/images/flyingsaucer.png”)

b=0

bullet = pygame.image.load(“resources/images/bullet1.png”)
player = pygame.image.load(“resources/images/hero1.png”)

positionPlayer=[100,400]
positionBullet=[positionPlayer[0]+50,positionPlayer[1]+40]
bullets=[]

while running:
screen.blit(background,(0,0))
screen.blit(player,positionPlayer)

for bulletx in bullets:
    bulletx[0]+=5
    screen.blit(bullet,(bulletx[0],bulletx[1]))

for event in pygame.event.get():
    if event.type==pygame.MOUSEBUTTONDOWN:
        bullets.append([150,440]) 

if b<5:
    flyingsaucers.append([random.randint(0,400),random.randint(20,100)])
b+=1

for flyingsaucer in flyingsaucers:
    if flyingsaucer[1]<610:
        flyingsaucer[1]+=0.5
    screen.blit(enemy,flyingsaucer)
    pygame.display.update()
    #pygame.display.flip()

 #测试时关闭窗口用

for event in pygame.event.get():
    if event.type == KEYDOWN and event.key == K_ESCAPE:
            running = False
            pygame.display.quit()
    if event.type == pygame.QUIT:
        pygame.quit()
        exit()

运行这段代码,在画布上,出现我们的主角-无敌战机。当我们点击鼠标时,战机会发射子弹。见下图5-4。
【汇智学堂】-python小游戏(太空阻击之五-无敌战机出现,横向射出子弹)_第1张图片

图5-4

你可能感兴趣的:(【汇智学堂】-python小游戏(太空阻击之五-无敌战机出现,横向射出子弹))