用Python制作一个“吃金币”小游戏
时间: 2023-10-07 17:08:25 浏览: 210
好的,下面是一个简单的“吃金币”小游戏的代码:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 设置屏幕大小
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# 设置游戏标题
pygame.display.set_caption("吃金币小游戏")
# 定义金币类
class Coin(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface([10, 10])
self.image.fill(GOLD)
self.rect = self.image.get_rect()
def update(self):
self.rect.y += 1
if self.rect.y > SCREEN_HEIGHT:
self.rect.y = 0
self.rect.x = random.randrange(SCREEN_WIDTH)
# 定义玩家类
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface([20, 20])
self.image.fill(BLUE)
self.rect = self.image.get_rect()
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
elif keys[pygame.K_UP]:
self.rect.y -= 5
elif keys[pygame.K_DOWN]:
self.rect.y += 5
# 碰撞检测
coins_hit = pygame.sprite.spritecollide(self, coins_list, True)
for coin in coins_hit:
self.score += 1
# 创建精灵组
all_sprites_list = pygame.sprite.Group()
coins_list = pygame.sprite.Group()
# 创建玩家
player = Player()
player.rect.x = SCREEN_WIDTH // 2
player.rect.y = SCREEN_HEIGHT - 50
player.score = 0
# 添加玩家到精灵组
all_sprites_list.add(player)
# 添加金币到精灵组
for i in range(50):
coin = Coin()
coin.rect.x = random.randrange(SCREEN_WIDTH)
coin.rect.y = random.randrange(SCREEN_HEIGHT)
coins_list.add(coin)
all_sprites_list.add(coin)
# 设置游戏时钟
clock = pygame.time.Clock()
# 游戏循环
done = False
while not done:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# 更新精灵组
all_sprites_list.update()
# 绘制背景
screen.fill(WHITE)
# 绘制精灵组
all_sprites_list.draw(screen)
# 绘制分数
font = pygame.font.Font(None, 36)
text = font.render("Score: " + str(player.score), True, BLACK)
screen.blit(text, [10, 10])
# 更新屏幕
pygame.display.flip()
# 设置游戏帧率
clock.tick(60)
# 退出游戏
pygame.quit()
```
通过运行以上代码,即可启动“吃金币”小游戏。在游戏中,玩家需要通过键盘控制角色移动,吃到尽可能多的金币。游戏结束后,会显示玩家的得分。
阅读全文