pythonV3V4/第19讲火眼金睛(二)/课堂成果/课后作业-作品优化 .py
sairate 2cd753d3d9 feat(第7讲 字母卡牌): 实现记忆游戏并添加开始界面
- 新增 jiyi.py 文件,实现字母翻牌记忆游戏功能
- 添加 youxijiemian.py 文件,创建游戏开始界面
- 使用 turtle 和 tkinter 模块分别实现游戏和界面
- 支持选择不同难度的游戏模式
2025-06-29 09:06:19 +08:00

89 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'''作品优化 —— 增大游戏难度
提示:
1. 增加关卡数量
2. 减小基础色和异色的区别'''
import pgzrun
import random
import time
WIDTH = 1000 # 窗口的宽度
HEIGHT = 725 # 窗口的高度
def draw():
screen.blit('火眼金睛.png', (0, 0))
if win:
screen.blit('游戏成功.png', (0, 0))
screen.draw.text(f"{total_t:.1f}", center=(520, 570), fontsize=90, color="yellow")
else:
screen.draw.text(f"{t:.1f} s", center=(900, 662), fontsize=40, color="yellow")
for grid in grids:
screen.draw.filled_rect(Rect(grid['pos'], (side, side)), grid['color'])
def update():
"""更新函数,用于实时更新游戏状态相关信息,这里主要更新总耗时"""
global t
t = time.time() - start_t
def base_color():
"""生成随机基础颜色"""
return (random.randint(0, 255),
random.randint(0, 255),
random.randint(0, 255))
def dif_color(base):
"""
参数:
base表示基础颜色的元组格式为r,g,b
"""
r = min(base[0] + random.randint(20, 25), 255)
g = min(base[1] + random.randint(20, 25), 255)
b = min(base[2] + random.randint(20, 25), 255)
return (r, g, b)
def game():
global grids, side, dc
# 根据格子数量计算格子边长和间距
side = 700 // n * 0.9
space = 700 // n * 0.1
# 创建列表grids后面存储每个方格信息
grids = []
# 获取基础色和异色
bc = base_color()
dc = dif_color(bc)
# 记录方格编号
i = 1
# 随机选择一个位置的方格设置略微不同的颜色
dif_index = random.randint(1, n * n)
for row in range(n):
for col in range(n):
info = {
'pos': (space + col * (side + space),
space + row * (side + space)),
'color': dc if i == dif_index else bc
}
grids.append(info)
i += 1
def on_mouse_down(pos):
global n, win, total_t
for grid in grids:
grid_rect = Rect(grid['pos'], (side, side))
if grid_rect.collidepoint(pos) and grid['color'] == dc:
if n > 20:
win = True
total_t = t
else:
n += 1 # 进入下一关
game()
# 初始化游戏参数
n = 3 # 初始为3×3的矩阵
win = False # 记录游戏成功状态
start_t = time.time() # 记录开始时间
game()
# 启动游戏
pgzrun.go()