Python小游戏14——雷霆战机

python

import pygame

import sys

import random

 

# 初始化Pygame

pygame.init()

 

# 设置屏幕大小

screen_width = 800

screen_height = 600

screen = pygame.display.set_mode((screen_width, screen_height))

pygame.display.set_caption("雷霆战机")

 

# 颜色定义

WHITE = (255, 255, 255)

BLACK = (0, 0, 0)

 

# 加载飞机图像

player_img = pygame.image.load("player.png") # 确保你有一个名为player.png的飞机图像文件

player_img = pygame.transform.scale(player_img, (50, 50))

player_x = screen_width // 2

player_y = screen_height - 100

player_x_change = 0

 

# 子弹定义

bullet_img = pygame.image.load("bullet.png") # 确保你有一个名为bullet.png的子弹图像文件

bullet_img = pygame.transform.scale(bullet_img, (10, 20))

bullet_x = 0

bullet_y = player_y

bullet_x_change = 0

bullet_y_change = 10

bullet_state = "ready" # "ready"表示子弹未发射,"fire"表示子弹已发射

 

# 游戏主循环

running = True

while running:

    # 背景填充

    screen.fill(BLACK)

 

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            running = False

 

        # 检测按键

        if event.type == pygame.KEYDOWN:

            if event.key == pygame.K_LEFT:

                player_x_change = -5

            if event.key == pygame.K_RIGHT:

                player_x_change = 5

            if event.key == pygame.K_SPACE and bullet_state == "ready":

                bullet_x = player_x + 20

                bullet_state = "fire"

 

        if event.type == pygame.KEYUP:

            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:

                player_x_change = 0

 

    # 更新飞机位置

    player_x += player_x_change

    if player_x <= 0:

        player_x = 0

    elif player_x >= screen_width - 50:

        player_x = screen_width - 50

 

    # 更新子弹位置

    if bullet_state == "fire":

        fire_bullet(screen, bullet_x, bullet_y, bullet_img, bullet_x_change, bullet_y_change)

        bullet_y -= bullet_y_change

    if bullet_y <= 0:

        bullet_y = player_y

        bullet_state = "ready"

 

    # 绘制飞机

    screen.blit(player_img, (player_x, player_y))

 

    # 更新屏幕

    pygame.display.update()

 

# 退出Pygame

pygame.quit()

sys.exit()

 

def fire_bullet(screen, x, y, bullet_img, x_change, y_change):

    bullet_rect = bullet_img.get_rect()

    bullet_rect.topleft = (x, y)

    screen.blit(bullet_img, bullet_rect)

上一篇:Java学习十六—掌握注解:让编程更简单-四、示例


下一篇:WPS电信定制版 v12.8.2.18205 自带 VBA无广告