Python吃豆豆游戏代码
时间: 2023-11-19 14:10:29 浏览: 60
关于吃豆人的游戏代码(python)
5星 · 资源好评率100%
以下是使用 Python 实现的吃豆豆游戏代码:
```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("吃豆豆游戏")
# 加载图片
player_image = pygame.image.load("player.png")
enemy_image = pygame.image.load("enemy.png")
food_image = pygame.image.load("food.png")
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# 定义字体
font = pygame.font.Font(None, 36)
# 定义玩家、敌人和食物类
class Player:
def __init__(self):
self.image = player_image
self.rect = self.image.get_rect()
self.rect.x = screen_width / 2
self.rect.y = screen_height / 2
self.speed = 5
self.score = 0
class Enemy:
def __init__(self):
self.image = enemy_image
self.rect = self.image.get_rect()
self.rect.x = random.randint(0, screen_width - self.rect.width)
self.rect.y = random.randint(0, screen_height - self.rect.height)
self.speed = 3
class Food:
def __init__(self):
self.image = food_image
self.rect = self.image.get_rect()
self.rect.x = random.randint(0, screen_width - self.rect.width)
self.rect.y = random.randint(0, screen_height - self.rect.height)
# 创建玩家、敌人和食物对象
player = Player()
enemy = Enemy()
food = Food()
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 移动玩家
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player.rect.x -= player.speed
if keys[pygame.K_RIGHT]:
player.rect.x += player.speed
if keys[pygame.K_UP]:
player.rect.y -= player.speed
if keys[pygame.K_DOWN]:
player.rect.y += player.speed
# 碰撞检测
if player.rect.colliderect(enemy.rect):
player.score -= 1
enemy.rect.x = random.randint(0, screen_width - enemy.rect.width)
enemy.rect.y = random.randint(0, screen_height - enemy.rect.height)
if player.rect.colliderect(food.rect):
player.score += 1
food.rect.x = random.randint(0, screen_width - food.rect.width)
food.rect.y = random.randint(0, screen_height - food.rect.height)
# 移动敌人
enemy_dx = random.randint(-enemy.speed, enemy.speed)
enemy_dy = random.randint(-enemy.speed, enemy.speed)
enemy.rect.x += enemy_dx
enemy.rect.y += enemy_dy
# 绘制界面
screen.fill(WHITE)
screen.blit(player.image, player.rect)
screen.blit(enemy.image, enemy.rect)
screen.blit(food.image, food.rect)
score_text = font.render("分数:" + str(player.score), True, BLACK)
screen.blit(score_text, (10, 10))
pygame.display.update()
# 退出 Pygame
pygame.quit()
```
该代码使用 Pygame 库实现了一个基本的吃豆豆游戏,玩家可以使用方向键控制角色的移动,吃到食物可以得分,碰到敌人则扣分。游戏界面包含分数显示,可以通过调整图片和颜色等参数来个性化游戏。
阅读全文