pygame小游戏代码
时间: 2023-07-09 09:49:22 浏览: 74
基于Python pygame简易版斗兽棋小游戏源代码
5星 · 资源好评率100%
下面是一个简单的 Pygame 小游戏的代码示例,这个游戏是一个飞机射击游戏:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 定义常量
WINDOW_WIDTH = 600
WINDOW_HEIGHT = 800
ENEMY_SIZE = 50
ENEMY_SPEED = 5
BULLET_SPEED = 10
# 创建窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("飞机射击游戏")
# 加载图片
player_img = pygame.image.load("player.png").convert_alpha()
enemy_img = pygame.image.load("enemy.png").convert_alpha()
bullet_img = pygame.image.load("bullet.png").convert_alpha()
# 定义游戏对象
class Player:
def __init__(self, x, y):
self.x = x
self.y = y
self.img = player_img
self.width = self.img.get_width()
self.height = self.img.get_height()
self.speed = 10
def move_left(self):
if self.x > 0:
self.x -= self.speed
def move_right(self):
if self.x < WINDOW_WIDTH - self.width:
self.x += self.speed
def shoot(self):
return Bullet(self.x + self.width / 2 - BULLET_SPEED / 2, self.y - BULLET_SPEED)
class Enemy:
def __init__(self, x, y):
self.x = x
self.y = y
self.img = enemy_img
self.width = self.img.get_width()
self.height = self.img.get_height()
self.speed = ENEMY_SPEED
def move(self):
self.y += self.speed
class Bullet:
def __init__(self, x, y):
self.x = x
self.y = y
self.img = bullet_img
self.width = self.img.get_width()
self.height = self.img.get_height()
self.speed = BULLET_SPEED
def move(self):
self.y -= self.speed
# 定义游戏逻辑
def run_game():
# 创建玩家对象
player = Player(WINDOW_WIDTH / 2 - player_img.get_width() / 2, WINDOW_HEIGHT - player_img.get_height())
# 创建敌人列表
enemies = []
# 创建子弹列表
bullets = []
# 游戏主循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
# 移动玩家对象
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player.move_left()
if keys[pygame.K_RIGHT]:
player.move_right()
# 射击子弹
if keys[pygame.K_SPACE]:
bullets.append(player.shoot())
# 移动敌人对象
if len(enemies) < 10:
enemies.append(Enemy(random.randint(0, WINDOW_WIDTH - ENEMY_SIZE), -ENEMY_SIZE))
for enemy in enemies:
enemy.move()
# 移动子弹对象
for bullet in bullets:
bullet.move()
# 检测碰撞
for enemy in enemies:
for bullet in bullets:
if (bullet.x > enemy.x and bullet.x < enemy.x + enemy.width and bullet.y > enemy.y and bullet.y < enemy.y + enemy.height):
enemies.remove(enemy)
bullets.remove(bullet)
# 渲染游戏对象
window.fill((255, 255, 255))
for enemy in enemies:
window.blit(enemy.img, (enemy.x, enemy.y))
for bullet in bullets:
window.blit(bullet.img, (bullet.x, bullet.y))
window.blit(player.img, (player.x, player.y))
pygame.display.update()
# 启动游戏
run_game()
```
请注意,这个代码仅用于演示 Pygame 的使用方法,实际游戏中可能需要更多的功能和优化。
阅读全文