以pygame为引擎的黄金矿工游戏代码
时间: 2024-03-03 07:26:13 浏览: 163
python,pygame自制黄金矿工小游戏
以下是以 Pygame 为引擎的黄金矿工游戏代码:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 游戏窗口大小
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# 设置窗口标题
pygame.display.set_caption("黄金矿工")
# 加载游戏素材
background_image = pygame.image.load("background.jpg")
miner_image = pygame.image.load("miner.png")
rock_image = pygame.image.load("rock.png")
gold_image = pygame.image.load("gold.png")
# 设置游戏字体
font = pygame.font.SysFont("Arial", 30)
# 定义游戏对象类
class GameObject:
def __init__(self, image, x, y):
self.image = image
self.rect = image.get_rect()
self.rect.x = x
self.rect.y = y
def draw(self, screen):
screen.blit(self.image, self.rect)
# 定义矿工类
class Miner(GameObject):
def __init__(self, image, x, y):
super().__init__(image, x, y)
self.score = 0
def update(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.rect.x -= 5
elif keys[pygame.K_RIGHT]:
self.rect.x += 5
# 定义石头类
class Rock(GameObject):
def __init__(self, image, x, y):
super().__init__(image, x, y)
# 定义金块类
class Gold(GameObject):
def __init__(self, image, x, y):
super().__init__(image, x, y)
self.value = random.randint(1, 10)
# 初始化游戏对象
miner = Miner(miner_image, SCREEN_WIDTH // 2, SCREEN_HEIGHT - 100)
rocks = []
golds = []
# 游戏循环
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_ESCAPE:
running = False
elif event.key == pygame.K_SPACE:
# 生成金块
x = random.randint(0, SCREEN_WIDTH - gold_image.get_width())
gold = Gold(gold_image, x, 0)
golds.append(gold)
# 更新游戏对象
miner.update()
for rock in rocks:
rock.rect.y += 1
if rock.rect.y > SCREEN_HEIGHT:
rocks.remove(rock)
for gold in golds:
gold.rect.y += 1
if gold.rect.y > SCREEN_HEIGHT:
golds.remove(gold)
elif gold.rect.colliderect(miner.rect):
miner.score += gold.value
golds.remove(gold)
# 绘制游戏画面
screen.blit(background_image, (0, 0))
miner.draw(screen)
for rock in rocks:
rock.draw(screen)
for gold in golds:
gold.draw(screen)
score_text = font.render("Score: " + str(miner.score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
pygame.display.update()
# 退出Pygame
pygame.quit()
```
注意:此代码仅为示例,需要自行准备游戏素材。
阅读全文