You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.7 KiB

import pygame
import random
# 初始化Pygame库
pygame.init()
# 游戏窗口的宽度和高度
width = 800
height = 600
# 创建游戏窗口
window = pygame.display.set_mode((width, height))
pygame.display.set_caption("吃豆") #游戏窗口标题
# 定义各种颜色
black = (0, 0, 0)
white = (255, 255, 255)
yellow = (255, 255, 0)
red = (255, 0, 0)
# 定义吃豆人的初始位置和速度
pacman_x = width // 2
pacman_y = height // 2
pacman_speed = 5
# 定义豆子的数量和大小
dot_size = 10
dot_count = 100
# 创建豆子的列表
dots = []
for i in range(dot_count):
dot_x = random.randint(0, width - dot_size)
dot_y = random.randint(0, height - dot_size)
dots.append((dot_x, dot_y))
# 游戏主循环
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]:
pacman_x -= pacman_speed
if keys[pygame.K_RIGHT]:
pacman_x += pacman_speed
if keys[pygame.K_UP]:
pacman_y -= pacman_speed
if keys[pygame.K_DOWN]:
pacman_y += pacman_speed
# 碰撞检测
for dot in dots:
dot_x, dot_y = dot #将(x,y)坐标解包到单独的变量
if pacman_x < dot_x + dot_size and pacman_x + dot_size > dot_x and pacman_y < dot_y + dot_size and pacman_y + dot_size > dot_y:
dots.remove(dot)
# 渲染画面
window.fill(black)
pygame.draw.circle(window, yellow, (pacman_x, pacman_y), 20)
for dot in dots:
pygame.draw.rect(window, white, (dot[0], dot[1], dot_size, dot_size))
pygame.display.flip()
# 退出游戏
pygame.quit()