用python射击小游戏的代码
时间: 2023-11-12 21:44:58 浏览: 178
基于Python的小游戏代码
以下是一个简单的用 Python 编写的射击小游戏的代码示例:
```python
import pygame
import random
# 初始化 Pygame 库
pygame.init()
# 设置游戏窗口大小
width = 640
height = 480
screen = pygame.display.set_mode((width, height))
# 设置游戏标题
pygame.display.set_caption('射击小游戏')
# 加载游戏背景音乐
pygame.mixer.music.load('background_music.mp3')
pygame.mixer.music.play(-1)
# 加载游戏背景图像
background_image = pygame.image.load('background_image.jpg').convert()
# 加载玩家飞船图像和初始位置
player_image = pygame.image.load('player_ship.png').convert_alpha()
player_rect = player_image.get_rect()
player_rect.centerx = width // 2
player_rect.bottom = height - 10
# 加载子弹图像和速度
bullet_image = pygame.image.load('bullet.png').convert_alpha()
bullet_speed = 5
# 加载敌人飞船图像和初始位置
enemy_image = pygame.image.load('enemy_ship.png').convert_alpha()
enemy_rect = enemy_image.get_rect()
enemy_rect.centerx = random.randint(0, width)
enemy_rect.top = -enemy_rect.height
enemy_speed = 3
# 加载爆炸图像和音效
explosion_image = pygame.image.load('explosion.png').convert_alpha()
explosion_sound = pygame.mixer.Sound('explosion_sound.wav')
# 设置游戏时钟
clock = pygame.time.Clock()
# 初始化游戏结束标志
game_over = False
# 游戏循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
# 发射子弹
bullet_rect = bullet_image.get_rect()
bullet_rect.centerx = player_rect.centerx
bullet_rect.bottom = player_rect.top
bullets.append(bullet_rect)
# 移动玩家飞船
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_LEFT]:
player_rect.centerx -= 5
elif keys_pressed[pygame.K_RIGHT]:
player_rect.centerx += 5
# 移动子弹
for bullet_rect in bullets:
bullet_rect.top -= bullet_speed
if bullet_rect.top < 0:
bullets.remove(bullet_rect)
# 移动敌人飞船
enemy_rect.top += enemy_speed
if enemy_rect.top > height:
enemy_rect.centerx = random.randint(0, width)
enemy_rect.top = -enemy_rect.height
# 检测碰撞
for bullet_rect in bullets:
if bullet_rect.colliderect(enemy_rect):
bullets.remove(bullet_rect)
enemy_rect.centerx = random.randint(0, width)
enemy_rect.top = -enemy_rect.height
explosion_sound.play()
screen.blit(explosion_image, enemy_rect)
pygame.display.update()
if player_rect.colliderect(enemy_rect):
game_over = True
# 绘制游戏界面
screen.blit(background_image, (0, 0))
screen.blit(player_image, player_rect)
screen.blit(enemy_image, enemy_rect)
for bullet_rect in bullets:
screen.blit(bullet_image, bullet_rect)
pygame.display.update()
# 控制帧率
clock.tick(60)
# 退出游戏
pygame.quit()
```
注意:此代码仅作为示例,具体实现可以根据实际需要进行修改。
阅读全文