python实现吃豆人游戏的代码
时间: 2023-10-11 10:04:29 浏览: 204
Python吃豆人、吃豆豆游戏源代码
5星 · 资源好评率100%
以下是一个简单的Python实现吃豆人游戏的代码,使用了Pygame库:
```python
import pygame
import random
# 初始化Pygame库
pygame.init()
# 游戏窗口大小
WINDOW_WIDTH = 480
WINDOW_HEIGHT = 640
# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 创建游戏窗口
WINDOW = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("吃豆人游戏")
# 加载吃豆人图片
PACMAN_IMAGE = pygame.image.load("pacman.png")
# 定义吃豆人类
class Pacman:
def __init__(self):
self.image = PACMAN_IMAGE
self.rect = self.image.get_rect()
self.rect.x = (WINDOW_WIDTH - self.rect.width) // 2
self.rect.y = (WINDOW_HEIGHT - self.rect.height) // 2
self.speed = 5
def move_left(self):
self.rect.x -= self.speed
def move_right(self):
self.rect.x += self.speed
def move_up(self):
self.rect.y -= self.speed
def move_down(self):
self.rect.y += self.speed
# 加载豆子图片
DOT_IMAGE = pygame.image.load("dot.png")
# 定义豆子类
class Dot:
def __init__(self, x, y):
self.image = DOT_IMAGE
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# 创建豆子列表
DOTS = []
for i in range(10):
x = random.randint(0, WINDOW_WIDTH - DOT_IMAGE.get_width())
y = random.randint(0, WINDOW_HEIGHT - DOT_IMAGE.get_height())
dot = Dot(x, y)
DOTS.append(dot)
# 加载大豆子图片
BIG_DOT_IMAGE = pygame.image.load("big_dot.png")
# 定义大豆子类
class BigDot:
def __init__(self, x, y):
self.image = BIG_DOT_IMAGE
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# 创建大豆子列表
BIG_DOTS = []
for i in range(2):
x = random.randint(0, WINDOW_WIDTH - BIG_DOT_IMAGE.get_width())
y = random.randint(0, WINDOW_HEIGHT - BIG_DOT_IMAGE.get_height())
big_dot = BigDot(x, y)
BIG_DOTS.append(big_dot)
# 创建吃豆人对象
pacman = Pacman()
# 游戏循环
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_LEFT:
pacman.move_left()
elif event.key == pygame.K_RIGHT:
pacman.move_right()
elif event.key == pygame.K_UP:
pacman.move_up()
elif event.key == pygame.K_DOWN:
pacman.move_down()
# 绘制背景
WINDOW.fill(BLACK)
# 绘制豆子
for dot in DOTS:
WINDOW.blit(dot.image, dot.rect)
# 绘制大豆子
for big_dot in BIG_DOTS:
WINDOW.blit(big_dot.image, big_dot.rect)
# 绘制吃豆人
WINDOW.blit(pacman.image, pacman.rect)
# 检测吃豆人是否碰到豆子
for dot in DOTS:
if pacman.rect.colliderect(dot.rect):
DOTS.remove(dot)
# 检测吃豆人是否碰到大豆子
for big_dot in BIG_DOTS:
if pacman.rect.colliderect(big_dot.rect):
BIG_DOTS.remove(big_dot)
# 更新窗口
pygame.display.update()
# 退出游戏
pygame.quit()
```
请注意,此示例代码仅实现了基本的游戏功能,您可以对其进行更多的扩展和改进。
阅读全文