pygame枪战游戏编程代码
时间: 2023-08-19 14:06:53 浏览: 193
好的,下面是一个简单的 Pygame 枪战游戏编程代码,您可以参考一下:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏窗口大小
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Gun Game")
# 游戏需要的颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 玩家
player_width = 50
player_height = 50
player_x = 325
player_y = 450
player_speed = 5
# 敌人
enemy_width = 50
enemy_height = 50
enemy_x = random.randint(0, 650)
enemy_y = random.randint(0, 150)
enemy_speed = 3
# 子弹
bullet_width = 5
bullet_height = 15
bullet_x = 0
bullet_y = 0
bullet_speed = 10
bullet_state = "ready"
# 得分
score = 0
font = pygame.font.Font(None, 36)
# 游戏结束
game_over = False
# 游戏循环
while not game_over:
# 监听事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 玩家移动
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_x -= player_speed
if event.key == pygame.K_RIGHT:
player_x += player_speed
# 发射子弹
if event.key == pygame.K_SPACE:
if bullet_state == "ready":
bullet_x = player_x + (player_width // 2) - (bullet_width // 2)
bullet_y = player_y
bullet_state = "fire"
# 移动敌人
enemy_y += enemy_speed
if enemy_y > 500:
enemy_x = random.randint(0, 650)
enemy_y = random.randint(0, 150)
score += 1
# 移动子弹
if bullet_state == "fire":
bullet_y -= bullet_speed
if bullet_y < 0:
bullet_state = "ready"
# 碰撞检测
if bullet_state == "fire":
if bullet_x > enemy_x and bullet_x < enemy_x + enemy_width and bullet_y > enemy_y and bullet_y < enemy_y + enemy_height:
enemy_x = random.randint(0, 650)
enemy_y = random.randint(0, 150)
bullet_state = "ready"
score += 10
# 重绘游戏界面
screen.fill(WHITE)
pygame.draw.rect(screen, BLACK, [player_x, player_y, player_width, player_height])
pygame.draw.rect(screen, RED, [enemy_x, enemy_y, enemy_width, enemy_height])
if bullet_state == "fire":
pygame.draw.rect(screen, BLACK, [bullet_x, bullet_y, bullet_width, bullet_height])
score_text = font.render("Score: " + str(score), True, BLACK)
screen.blit(score_text, [10, 10])
# 更新游戏界面
pygame.display.flip()
# 退出 Pygame
pygame.quit()
```
这个游戏中,玩家可以左右移动,通过空格键发射子弹击败敌人并得分。如果敌人离开屏幕,则会重新生成一个新的敌人。游戏结束后,退出 Pygame。
希望这个代码对您有所帮助。
阅读全文
相关推荐
















