概述
import time
import pygame
import sys
import random
from pygame.locals import *
# 子弹类
class Bullet(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("D:/bullets.png")
width, height = self.image.get_size()
self.image = pygame.transform.smoothscale(self.image, (width // 3, height // 3))
self.rect = self.image.get_rect()
def update(self, speed=10):
self.rect.y -= speed
if self.rect.y < 0:
self.kill()
# 玩家类
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("D:/player.png")
width, height = self.image.get_size()
self.image = pygame.transform.smoothscale(self.image, (width // 3, height // 3))
self.rect = self.image.get_rect()
self.rect.x = 180
self.rect.y = 540
self.bullets = pygame.sprite.Group()
def fire(self):
self.bullet = Bullet()
self.bullet.rect.x = self.rect.x
self.bullet.rect.y = self.rect.y
self.bullets.add(self.bullet)
# 敌机类
class Enemy(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("D:/enemy.png")
width, height = self.image.get_size()
self.image = pygame.transform.smoothscale(self.image, (width // 3, height // 3))
self.rect = self.image.get_rect()
self.rect.x = 100
self.rect.y = 300
def update(self):
if pygame.sprite.spritecollide(enemy, player.bullets, False):
self.kill()
else:
self.rect.y += 0
if random.randint(0, 1) == 0:
self.rect.x -= 0
else:
self.rect.x += 0
if self.rect.y > 600 or self.rect.x > 400 or self.rect.x < 0:
self.kill()
pygame.init()
# 初始化界面
screen = pygame.display.set_mode((400, 600))
pygame.display.set_caption('Pygame 飞机大战')
screen.fill((250, 250, 250))
# 初始化玩家
player = Player()
a_speed, w_speed, s_speed, d_speed = 0, 0, 0, 0
# 初始化敌机
enemy = Enemy()
enemies = pygame.sprite.Group()
enemies.add(enemy)
# 走循环
while True:
screen.fill((255, 255, 255))
screen.blit(player.image, (player.rect.x, player.rect.y))
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# 玩家移动
elif event.type == KEYDOWN:
if event.key == pygame.K_w:
w_speed = -1
elif event.key == pygame.K_s:
s_speed = -1
elif event.key == pygame.K_a:
a_speed = -1
elif event.key == pygame.K_d:
d_speed = -1
elif event.type == KEYUP:
if event.key == K_w:
w_speed = 0
elif event.key == K_s:
s_speed = 0
elif event.key == K_a:
a_speed = 0
elif event.key == K_d:
d_speed = 0
elif event.key == K_j:
player.fire()
player.bullets.update()
player.bullets.draw(screen)
enemy.update()
enemies.draw(screen)
player.rect.x = player.rect.x + a_speed - d_speed
player.rect.y = player.rect.y + w_speed - s_speed
# 结束
time.sleep(0.01)
pygame.display.update()
最后
以上就是轻松大山为你收集整理的Python+Pygame飞机大战(待完善)的全部内容,希望文章能够帮你解决Python+Pygame飞机大战(待完善)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复