用python写一个射击游戏
时间: 2024-05-29 16:03:56 浏览: 271
好的,以下是一个简单的射击游戏的Python代码:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 定义游戏窗口大小
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
# 创建游戏窗口
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("射击游戏")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 加载图像
background = pygame.image.load("background.jpg")
player = pygame.image.load("player.png")
bullet = pygame.image.load("bullet.png")
enemy = pygame.image.load("enemy.png")
# 获取图像大小
player_width, player_height = player.get_size()
bullet_width, bullet_height = bullet.get_size()
enemy_width, enemy_height = enemy.get_size()
# 设置字体
font = pygame.font.SysFont(None, 48)
# 初始化游戏变量
player_x = WINDOW_WIDTH // 2 - player_width // 2
player_y = WINDOW_HEIGHT - player_height - 10
player_speed = 5
bullet_speed = 10
enemy_speed = 3
score = 0
clock = pygame.time.Clock()
# 定义函数:绘制文本
def draw_text(text, color, x, y):
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
text_rect.center = (x, y)
screen.blit(text_surface, text_rect)
# 定义函数:绘制玩家
def draw_player(x, y):
screen.blit(player, (x, y))
# 定义函数:绘制子弹
def draw_bullet(x, y):
screen.blit(bullet, (x, y))
# 定义函数:绘制敌人
def draw_enemy(x, y):
screen.blit(enemy, (x, y))
# 定义函数:检测碰撞
def is_collision(x1, y1, w1, h1, x2, y2, w2, h2):
if x1 + w1 >= x2 and x1 <= x2 + w2 and y1 + h1 >= y2 and y1 <= y2 + h2:
return True
else:
return False
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_x -= player_speed
elif event.key == pygame.K_RIGHT:
player_x += player_speed
elif event.key == pygame.K_SPACE:
bullet_x = player_x + player_width // 2 - bullet_width // 2
bullet_y = player_y - bullet_height
bullet_active = True
# 绘制背景
screen.blit(background, (0, 0))
# 绘制玩家
draw_player(player_x, player_y)
# 移动子弹
if bullet_active:
bullet_y -= bullet_speed
draw_bullet(bullet_x, bullet_y)
if bullet_y < -bullet_height:
bullet_active = False
# 绘制敌人并移动
draw_enemy(enemy_x, enemy_y)
enemy_y += enemy_speed
if enemy_y > WINDOW_HEIGHT:
enemy_x = random.randint(0, WINDOW_WIDTH - enemy_width)
enemy_y = -enemy_height
score += 1
# 检测碰撞
if is_collision(bullet_x, bullet_y, bullet_width, bullet_height, enemy_x, enemy_y, enemy_width, enemy_height):
bullet_active = False
enemy_x = random.randint(0, WINDOW_WIDTH - enemy_width)
enemy_y = -enemy_height
score += 10
elif is_collision(player_x, player_y, player_width, player_height, enemy_x, enemy_y, enemy_width, enemy_height):
running = False
# 显示分数
draw_text("Score: " + str(score), WHITE, WINDOW_WIDTH // 2, 50)
# 更新屏幕
pygame.display.update()
# 控制帧率
clock.tick(60)
# 退出游戏
pygame.quit()
```
请注意,这只是一个简单的示例代码,您可以根据自己的需要进行修改和扩展。
阅读全文