用pygame写一个射击游戏,并设置射击间隔
时间: 2024-06-12 13:04:36 浏览: 196
基于pygame的射击类小游戏
以下是一个简单的射击游戏示例,可以用pygame实现,其中设置了射击间隔:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 设置游戏窗口大小
screen_width = 600
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('射击游戏')
# 加载图片
player_img = pygame.image.load('player.png')
enemy_img = pygame.image.load('enemy.png')
bullet_img = pygame.image.load('bullet.png')
# 设置游戏参数
player_speed = 5
enemy_speed = 3
bullet_speed = 10
bullet_interval = 200 # 射击间隔(毫秒)
# 创建玩家
player_x = screen_width // 2
player_y = screen_height - player_img.get_height()
player_rect = player_img.get_rect()
player_rect.centerx = player_x
player_rect.bottom = player_y
# 创建敌人
enemy_x = random.randint(0, screen_width - enemy_img.get_width())
enemy_y = 0
enemy_rect = enemy_img.get_rect()
enemy_rect.centerx = enemy_x
enemy_rect.bottom = enemy_y
# 创建子弹
bullet_list = []
bullet_rect_list = []
# 游戏循环
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
# 移动玩家
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_rect.left > 0:
player_rect.move_ip(-player_speed, 0)
if keys[pygame.K_RIGHT] and player_rect.right < screen_width:
player_rect.move_ip(player_speed, 0)
# 移动敌人
enemy_rect.move_ip(0, enemy_speed)
if enemy_rect.top > screen_height:
enemy_x = random.randint(0, screen_width - enemy_img.get_width())
enemy_y = 0
enemy_rect.centerx = enemy_x
enemy_rect.bottom = enemy_y
# 射击子弹
if keys[pygame.K_SPACE]:
current_time = pygame.time.get_ticks()
if len(bullet_list) == 0 or current_time - bullet_list[-1][1] >= bullet_interval:
bullet_x = player_rect.centerx
bullet_y = player_rect.top
bullet_rect = bullet_img.get_rect()
bullet_rect.centerx = bullet_x
bullet_rect.bottom = bullet_y
bullet_list.append((bullet_rect, current_time))
bullet_rect_list.append(bullet_rect)
# 移动子弹
for bullet_rect in bullet_rect_list:
bullet_rect.move_ip(0, -bullet_speed)
if bullet_rect.bottom < 0:
bullet_rect_list.remove(bullet_rect)
# 检测碰撞
if player_rect.colliderect(enemy_rect):
game_over = True
for bullet_rect in bullet_rect_list:
if bullet_rect.colliderect(enemy_rect):
enemy_x = random.randint(0, screen_width - enemy_img.get_width())
enemy_y = 0
enemy_rect.centerx = enemy_x
enemy_rect.bottom = enemy_y
bullet_rect_list.remove(bullet_rect)
# 渲染图像
screen.fill((255, 255, 255))
screen.blit(player_img, player_rect)
screen.blit(enemy_img, enemy_rect)
for bullet_rect in bullet_rect_list:
screen.blit(bullet_img, bullet_rect)
pygame.display.update()
# 控制游戏帧率
clock.tick(60)
# 游戏结束
pygame.quit()
```
在上面的代码中,使用了`pygame.time.get_ticks()`函数来获取当前时间,用于控制射击间隔。具体来说,当按下空格键时,如果当前没有子弹或者距离上一次射击已经超过了设定的间隔时间,则创建新的子弹并加入列表。在移动子弹时,如果子弹已经超出了屏幕,就从列表中删除。在检测碰撞时,如果子弹和敌人发生碰撞,则重新生成敌人并将子弹从列表中删除。最后,使用`clock.tick(60)`函数来控制游戏帧率为60帧每秒。
阅读全文