python飞机大作战代码
以下是一个简单的Python飞机大作战的代码示例:
import random
import pygame
from pygame.locals import *
# 初始化游戏
pygame.init()
# 设置游戏窗口尺寸
screen_width, screen_height = 480, 800
screen = pygame.display.set_mode((screen_width, screen_height))
# 加载背景图片
background = pygame.image.load("background.png")
# 加载飞机图片
player_plane = pygame.image.load("player_plane.png")
player_rect = player_plane.get_rect()
player_plane_width, player_plane_height = player_rect.width, player_rect.height
player_plane_x = screen_width / 2 - player_plane_width / 2
player_plane_y = screen_height - player_plane_height - 20
# 加载子弹图片
bullet_plane = pygame.image.load("bullet.png")
bullet_rect = bullet_plane.get_rect()
bullet_plane_width, bullet_plane_height = bullet_rect.width, bullet_rect.height
bullet_plane_x, bullet_plane_y = [], []
bullet_plane_speed = 10
# 加载敌机图片
enemy_plane = pygame.image.load("enemy_plane.png")
enemy_rect = enemy_plane.get_rect()
enemy_plane_width, enemy_plane_height = enemy_rect.width, enemy_rect.height
enemy_plane_x, enemy_plane_y = [], []
enemy_plane_speed = 2
# 游戏循环
running = True
while running:
# 绘制背景
screen.blit(background, (0, 0))
# 处理事件
for event in pygame.event.get():
if event.type == QUIT:
running = False
elif event.type == KEYDOWN:
if event.key == K_SPACE:
bullet_plane_x.append(player_plane_x + player_plane_width / 2 - bullet_plane_width / 2)
bullet_plane_y.append(player_plane_y - bullet_plane_height)
# 移动子弹
for i in range(len(bullet_plane_x)):
bullet_plane_y[i] -= bullet_plane_speed
if bullet_plane_y[i] < 0:
del bullet_plane_x[i]
del bullet_plane_y[i]
break
# 移动敌机
for i in range(len(enemy_plane_x)):
enemy_plane_y[i] += enemy_plane_speed
if enemy_plane_y[i] > screen_height:
del enemy_plane_x[i]
del enemy_plane_y[i]
break
# 绘制子弹
for i in range(len(bullet_plane_x)):
screen.blit(bullet_plane, (bullet_plane_x[i], bullet_plane_y[i]))
# 绘制敌机
for i in range(len(enemy_plane_x)):
screen.blit(enemy_plane, (enemy_plane_x[i], enemy_plane_y[i]))
# 绘制玩家飞机
screen.blit(player_plane, (player_plane_x, player_plane_y))
# 更新屏幕
pygame.display.update()
# 退出游戏
pygame.quit()
请注意,此代码仅提供了一个简单的框架,需要根据自己的需求进一步完善和修改。同时,你还需要准备相应的图片资源以及处理碰撞、计分等功能
原文地址: http://www.cveoy.top/t/topic/ieq1 著作权归作者所有。请勿转载和采集!