前言
相关参考游戏:
像素飞机大战(含Python源码)-CSDN博客https://blog.csdn.net/weixin_64066303/article/details/147693018?spm=1001.2014.3001.5501使用DeepSeek定制Python小游戏——以“俄罗斯方块”为例-CSDN博客
https://blog.csdn.net/weixin_64066303/article/details/147686449?spm=1001.2014.3001.5501贪吃蛇(含Python源码)-CSDN博客
https://blog.csdn.net/weixin_64066303/article/details/147660127?spm=1001.2014.3001.5501外星人入侵(python)_外星人入侵python源代码-CSDN博客
https://blog.csdn.net/weixin_64066303/article/details/135963588?spm=1001.2014.3001.5501
DeepSeek
使用DeepSeek生成的游戏可以正常的使用,最开始是控制台的形式,还是需要向DeepSeek明确自己的需求。
import pygame
import random
import sys
# 颜色配置
COLORS = {
0: (205, 193, 180),
2: (238, 228, 218),
4: (237, 224, 200),
8: (242, 177, 121),
16: (245, 149, 99),
32: (246, 124, 95),
64: (246, 94, 59),
128: (237, 207, 114),
256: (237, 204, 97),
512: (237, 200, 80),
1024: (237, 197, 63),
2048: (237, 194, 46),
'bg': (187, 173, 160),
'text': (119, 110, 101),
'gameover': (255, 255, 255, 128)
}
# 游戏参数
WIDTH = 400
HEIGHT = 500
TILE_SIZE = 80
SPACING = 10
def initialize_board():
board = [[0] * 4 for _ in range(4)]
add_new_tile(board)
add_new_tile(board)
return board
def add_new_tile(board):
empty_cells = [(i, j) for i in range(4) for j in range(4) if board[i][j] == 0]
if not empty_cells:
return False
i, j = random.choice(empty_cells)
board[i][j] = 2 if random.random() < 0.9 else 4
return True
def move_row(row):
# 合并逻辑(同控制台版本)
compressed = [num for num in row if num != 0]
merged = []
skip = False
for i in range(len(compressed)):
if skip:
skip = False
continue
if i + 1 < len(compressed) and compressed[i] == compressed[i + 1]:
merged.append(compressed[i] * 2)
skip = True
else:
merged.append(compressed[i])
merged += [0] * (len(row) - len(merged))
return merged
def move(board, direction):
new_board = [row.copy() for row in board]
moved = False
if direction == 'left':
for i in range(4):
new_row = move_row(board[i])
if new_row != board[i]:
moved = True
new_board[i] = new_row
elif direction == 'right':
for i in range(4):
new_row = move_row(board[i][::-1])[::-1]
if new_row != board[i]:
moved = True
new_board[i] = new_row
elif direction == 'up':
for j in range(4):
column = [board[i][j] for i in range(4)]
new_col = move_row(column)
if new_col != column:
moved = True
for i in range(4):
new_board[i][j] = new_col[i]
elif direction == 'down':
for j in range(4):
column = [board[i][j] for i in range(4)][::-1]
new_col = move_row(column)[::-1]
if new_col != column[::-1]:
moved = True
for i in range(4):
new_board[i][j] = new_col[i]
return new_board, moved
def draw_board(screen, board, font):
screen.fill(COLORS['bg'])
# 绘制棋盘
for i in range(4):
for j in range(4):
value = board[i][j]
x = SPACING + j * (TILE_SIZE + SPACING)
y = SPACING + i * (TILE_SIZE + SPACING) + 100
pygame.draw.rect(screen, COLORS.get(value, COLORS[0]),
(x, y, TILE_SIZE, TILE_SIZE), 0, 3)
if value != 0:
text = font.render(str(value), True, COLORS['text'])
text_rect = text.get_rect(center=(x + TILE_SIZE // 2, y + TILE_SIZE // 2))
screen.blit(text, text_rect)
# 绘制分数
score = sum(sum(row) for row in board)
score_text = font.render(f"Score: {score}", True, COLORS['text'])
screen.blit(score_text, (20, 20))
def is_game_over(board):
# 同控制台版本判断逻辑
if any(0 in row for row in board):
return False
for i in range(4):
for j in range(4):
if (j < 3 and board[i][j] == board[i][j + 1]) or \
(i < 3 and board[i][j] == board[i + 1][j]):
return False
return True
def game_over_screen(screen, font):
overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
overlay.fill(COLORS['gameover'])
text = font.render("Game Over!", True, (255, 0, 0))
text_rect = text.get_rect(center=(WIDTH // 2, HEIGHT // 2))
overlay.blit(text, text_rect)
screen.blit(overlay, (0, 0))
pygame.display.update()
def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("2048")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 36)
board = initialize_board()
direction_keys = {
pygame.K_w: 'up',
pygame.K_a: 'left',
pygame.K_s: 'down',
pygame.K_d: 'right',
pygame.K_UP: 'up',
pygame.K_LEFT: 'left',
pygame.K_DOWN: 'down',
pygame.K_RIGHT: 'right'
}
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 in direction_keys:
direction = direction_keys[event.key]
new_board, moved = move(board, direction)
if moved:
board = new_board
add_new_tile(board)
elif event.key == pygame.K_r: # 按R重新开始
board = initialize_board()
draw_board(screen, board, font)
if is_game_over(board):
game_over_screen(screen, font)
pygame.display.flip()
clock.tick(30)
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
代码详解
这个暂时没有想出可以增加什么特色的功能,目前就是增加保留历史最高分数的功能。
干脆就不进行修改,还是整理一下代码的逻辑,不然感觉弄这个也没学到什么知识,玩这种小游戏也是图一个新鲜感,所以还是理解一下代码。
有了一门编程语言基础后,学习其他的语言还是比较快的,可以通过注解来理解代码的逻辑。
参数配置
颜色配置:通过在全局定义图形的颜色,颜色一般都是采用RGB(Red,Green,Blue)的方式来设置。
游戏参数:通过在全局定义窗口的大小、方块大小和间隔大小一般命名还是尽量见名知意,也避免使用拼音的命名方式。
# 颜色配置
COLORS = {
0: (205, 193, 180),
2: (238, 228, 218),
4: (237, 224, 200),
8: (242, 177, 121),
16: (245, 149, 99),
32: (246, 124, 95),
64: (246, 94, 59),
128: (237, 207, 114),
256: (237, 204, 97),
512: (237, 200, 80),
1024: (237, 197, 63),
2048: (237, 194, 46),
'bg': (187, 173, 160),
'text': (119, 110, 101),
'gameover': (255, 255, 255, 128)
}
# 游戏参数
WIDTH = 400
HEIGHT = 500
# 方块大小
TILE_SIZE = 80
# 间隔大小
SPACING = 10
核心逻辑模块
[ [0]*10 for i in range(4)]----Python列表解析-CSDN博客https://blog.csdn.net/wy_______/article/details/88716335在python中for i in range是什么意思-Python for i in range ()用法详解-CSDN博客
https://blog.csdn.net/weixin_37988176/article/details/109371269python中random.choice()函数与random.choices()函数-CSDN博客
https://blog.csdn.net/QDU_zty/article/details/138703821python常用random随机函数汇总,用法详解及函数之间的区别--一图了解python随机函数_python random函数-CSDN博客
https://blog.csdn.net/weixin_45914452/article/details/115264053Python---copy()、deepcopy()与赋值的区别_为什么元组不能用copy却可以赋值-CSDN博客
https://blog.csdn.net/u011630575/article/details/78604226Python内置函数any()详解 语法 参数 返回值 示例 使用场景 常见场景 检查列表中是否存在非零元素 检查字典中是否存在非空值 结合条件表达式使用 注意事项——《跟老吕学Python编程》_python any-CSDN博客
https://blog.csdn.net/molangmolang/article/details/137760053关于python中的[::-1],[:,:,::-1]的反转理解-CSDN博客
https://blog.csdn.net/wuxero/article/details/133858521[[0] * 4 for _ in range(4)]:创建4行4列的矩阵,用来表示棋盘。
[(i, j) for i in range(4) for j in range(4) if board[i][j] == 0]:筛选出board中所有值为0的元素,并将这些元素的坐标以元组形式收集到一个新的列表中。
random.choice(seq):从非空序列 seq中选择一个随机元素。
random.random(): 返回随机生成的一个浮点数,范围在[0,1)之间。
[num for num in row if num != 0]:过滤所有零元素,将有效元素左对齐。
使用 skip 标记避免连续合并(如处理 [2,2,2,2] → [4,4] 而非 [8])
if i + 1 < len(compressed) and compressed[i] == compressed[i + 1]:检测相邻相同元素。
[0] * (len(row) - len(merged)):在右侧补零,保持列表长度与原行一致。
[::-1])[::-1]:在一维数组中反转。
# 初始化棋盘
def initialize_board():
board = [[0] * 4 for _ in range(4)]
add_new_tile(board)
add_new_tile(board)
return board
# 方块生成
def add_new_tile(board):
# 查找空位并随机生成新方块
empty_cells = [(i, j) for i in range(4) for j in range(4) if board[i][j] == 0]
if not empty_cells:
return False
i, j = random.choice(empty_cells)
board[i][j] = 2 if random.random() < 0.9 else 4 # 如果小于0.9,则生成数字2;否则生成数字4
return True
# 单行合并逻辑
def move_row(row):
# 实现经典的2048合并算法
compressed = [num for num in row if num != 0]
merged = []
skip = False
for i in range(len(compressed)):
if skip:
skip = False
continue
if i + 1 < len(compressed) and compressed[i] == compressed[i + 1]:
merged.append(compressed[i] * 2)
skip = True
else:
merged.append(compressed[i])
merged += [0] * (len(row) - len(merged))
return merged
# 全盘移动
def move(board, direction):
# 处理四个方向的移动逻辑
new_board = [row.copy() for row in board]
moved = False
if direction == 'left':
for i in range(4):
new_row = move_row(board[i])
if new_row != board[i]:
moved = True
new_board[i] = new_row
elif direction == 'right':
for i in range(4):
new_row = move_row(board[i][::-1])[::-1]
if new_row != board[i]:
moved = True
new_board[i] = new_row
elif direction == 'up':
for j in range(4):
column = [board[i][j] for i in range(4)]
new_col = move_row(column)
if new_col != column:
moved = True
for i in range(4):
new_board[i][j] = new_col[i]
elif direction == 'down':
for j in range(4):
column = [board[i][j] for i in range(4)][::-1]
new_col = move_row(column)[::-1]
if new_col != column[::-1]:
moved = True
for i in range(4):
new_board[i][j] = new_col[i]
return new_board, moved
# 游戏结束判断
def is_game_over(board):
# 检测是否无有效移动
if any(0 in row for row in board):
return False
for i in range(4):
for j in range(4):
if (j < 3 and board[i][j] == board[i][j + 1]) or \
(i < 3 and board[i][j] == board[i + 1][j]):
return False
return True
界面渲染模块
pygame之font模块_font.render-CSDN博客https://blog.csdn.net/weixin_51371629/article/details/125182808Pygame Draw绘图函数——《Python游戏开发库Pygame》_pygame.draw.rect-CSDN博客
https://blog.csdn.net/molangmolang/article/details/139034445“screen.blit()函数的special_flags参数”——源自C知道-CSDN博客
https://blog.csdn.net/h5a5i5/article/details/135560978pygame库使用简介_pip install pygame-CSDN博客
https://blog.csdn.net/weixin_45369856/article/details/140609065Pygame Surface创建图像——《Python游戏开发库Pygame》-CSDN博客
https://blog.csdn.net/molangmolang/article/details/139034359render(text,antialias,color,background=None):文字区域转换为image surface的方法。
pygame.draw.rect(Surface, color, Rect, width=0):绘制矩形。
screen.blit(text, text_rect):将一个图像绘制到屏幕上。
pygame.display.update():更新显示。
pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA):Surface可以视为一个二维的像素数组,每个像素都可以被赋予颜色和其他属性。
# 绘制棋盘
def draw_board(screen, board, font, high_score):
# 棋盘网格绘制
# 方块数值渲染
# 分数/最高分显示
screen.fill(COLORS['bg'])
# 计算棋盘居中位置
grid_size = 4 * TILE_SIZE + 5 * SPACING # 总网格尺寸 (4方块+5间隔)
start_x = (WIDTH - grid_size) // 2 # 水平居中
start_y = 100 # 距离顶部固定间距
# 绘制棋盘
for i in range(4):
for j in range(4):
value = board[i][j]
# 修正坐标计算公式
x = start_x + j * (TILE_SIZE + SPACING)
y = start_y + i * (TILE_SIZE + SPACING)
# 绘制方块(添加阴影效果)
pygame.draw.rect(screen, COLORS.get(value, COLORS[0]),
(x, y, TILE_SIZE, TILE_SIZE), 0, 3)
# 添加数值文字
if value != 0:
text = font.render(str(value), True, COLORS['text'])
text_rect = text.get_rect(center=(x + TILE_SIZE // 2, y + TILE_SIZE // 2))
screen.blit(text, text_rect)
# 调整分数显示位置
score = sum(sum(row) for row in board)
score_text = font.render(f"Score: {score}", True, COLORS['text'])
high_text = font.render(f"High: {high_score}", True, COLORS['text'])
# 将分数信息放在棋盘上方居中
header_y = start_y - 40
screen.blit(score_text, (start_x, header_y)) # 左上对齐
screen.blit(high_text, (start_x + grid_size - high_text.get_width(), header_y)) # 右上对齐
# 游戏结束的屏幕
def game_over_screen(screen, font):
# 半透明遮罩层
# Game Over文字提示
overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
overlay.fill(COLORS['gameover'])
text = font.render("Game Over!", True, (255, 0, 0))
text_rect = text.get_rect(center=(WIDTH // 2, HEIGHT // 2))
overlay.blit(text, text_rect)
screen.blit(overlay, (0, 0))
pygame.display.update()
数据管理模块
Python学习16:open内置函数全方面讲解_python open-CSDN博客https://blog.csdn.net/JackMengJin/article/details/106555683【Python】json.dumps()函数详解和示例-CSDN博客
https://blog.csdn.net/qq_22734027/article/details/134989663深入浅出:Python `with` 语句详解-CSDN博客
https://blog.csdn.net/zhaoxilengfeng/article/details/144382104认为保留最高分在一定程度上还是能够吸引玩家继续来玩这个游戏,所以增加了加载和保存最高分的函数。
这里用到了open函数,"r"表示以只读方式打开文件,"w"表示打开一个文件只用于写入,如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
通过 with
语句打开文件,可以在文件使用完毕后自动关闭,无需显式调用 close()
方法。
数据保存到文件2048_high_score.json中,文件的命名最好也是见名知意的,命名要求符合操作系统的命名规范。
json.dumps()是Python中处理JSON数据的重要函数,它允许开发者将Python对象转换为JSON格式的字符串。
# 新增函数:加载和保存最高分
def load_high_score():
try:
with open("2048_high_score.json", "r") as f:
data = json.load(f)
return data.get("high_score", 0)
except (FileNotFoundError, json.JSONDecodeError):
return 0
def save_high_score(score):
with open("2048_high_score.json", "w") as f:
json.dump({"high_score": score}, f)
控制模块
Pygame 官方文档 - pygame.time_pygame.time.clock-CSDN博客https://blog.csdn.net/Enderman_xiaohei/article/details/88167762Pygame详解(四):event 模块-CSDN博客
https://blog.csdn.net/qq_41556318/article/details/86303039pygame 键盘事件_pygame键盘事件-CSDN博客
https://blog.csdn.net/weixin_45020839/article/details/117886708第 3 章:事件处理与用户交互-CSDN博客
https://blog.csdn.net/sdsdsdd__/article/details/145327602pygame.time.Clock():创建一个对象来帮助跟踪时间。
pygame.event.get(): 从队列中获取事件。
pygame.event.EventType:
- 事件本质上是一种封装后的数据类型(对象)
- EventType是Pygame的一个类,表示事件类型
- 事件类型只有属性,没有方法
- 用户可自定义新的事件类型
# 主函数
def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("2048")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 36)
# 初始化最高分
high_score = load_high_score() # 新增
current_high = high_score # 新增
board = initialize_board()
direction_keys = {
pygame.K_w: 'up',
pygame.K_a: 'left',
pygame.K_s: 'down',
pygame.K_d: 'right',
pygame.K_UP: 'up',
pygame.K_LEFT: 'left',
pygame.K_DOWN: 'down',
pygame.K_RIGHT: 'right'
}
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 in direction_keys:
direction = direction_keys[event.key]
new_board, moved = move(board, direction)
if moved:
board = new_board
add_new_tile(board)
# 更新最高分
current_score = sum(sum(row) for row in board)
if current_score > current_high:
current_high = current_score
save_high_score(current_high) # 实时保存
elif event.key == pygame.K_r:
board = initialize_board()
# 重置时保留最高分
current_high = max(current_high, load_high_score())
draw_board(screen, board, font, current_high) # 修改调用
if is_game_over(board):
game_over_screen(screen, font)
# 游戏结束时确保保存
save_high_score(current_high)
pygame.display.flip()
clock.tick(30)
# 退出时保存
save_high_score(current_high)
pygame.quit()
sys.exit()
完整代码
import pygame
import random
import sys
import json # 新增导入
# 颜色配置
COLORS = {
0: (205, 193, 180),
2: (238, 228, 218),
4: (237, 224, 200),
8: (242, 177, 121),
16: (245, 149, 99),
32: (246, 124, 95),
64: (246, 94, 59),
128: (237, 207, 114),
256: (237, 204, 97),
512: (237, 200, 80),
1024: (237, 197, 63),
2048: (237, 194, 46),
'bg': (187, 173, 160),
'text': (119, 110, 101),
'gameover': (255, 255, 255, 128)
}
# 游戏参数
WIDTH = 400
HEIGHT = 500
TILE_SIZE = 80
SPACING = 10
# 新增函数:加载和保存最高分
def load_high_score():
try:
with open("2048_high_score.json", "r") as f:
data = json.load(f)
return data.get("high_score", 0)
except (FileNotFoundError, json.JSONDecodeError):
return 0
def save_high_score(score):
with open("2048_high_score.json", "w") as f:
json.dump({"high_score": score}, f)
def initialize_board():
board = [[0] * 4 for _ in range(4)]
add_new_tile(board)
add_new_tile(board)
return board
def add_new_tile(board):
empty_cells = [(i, j) for i in range(4) for j in range(4) if board[i][j] == 0]
if not empty_cells:
return False
i, j = random.choice(empty_cells)
board[i][j] = 2 if random.random() < 0.9 else 4
return True
def move_row(row):
compressed = [num for num in row if num != 0]
merged = []
skip = False
for i in range(len(compressed)):
if skip:
skip = False
continue
if i + 1 < len(compressed) and compressed[i] == compressed[i + 1]:
merged.append(compressed[i] * 2)
skip = True
else:
merged.append(compressed[i])
merged += [0] * (len(row) - len(merged))
return merged
def move(board, direction):
new_board = [row.copy() for row in board]
moved = False
if direction == 'left':
for i in range(4):
new_row = move_row(board[i])
if new_row != board[i]:
moved = True
new_board[i] = new_row
elif direction == 'right':
for i in range(4):
new_row = move_row(board[i][::-1])[::-1]
if new_row != board[i]:
moved = True
new_board[i] = new_row
elif direction == 'up':
for j in range(4):
column = [board[i][j] for i in range(4)]
new_col = move_row(column)
if new_col != column:
moved = True
for i in range(4):
new_board[i][j] = new_col[i]
elif direction == 'down':
for j in range(4):
column = [board[i][j] for i in range(4)][::-1]
new_col = move_row(column)[::-1]
if new_col != column[::-1]:
moved = True
for i in range(4):
new_board[i][j] = new_col[i]
return new_board, moved
def draw_board(screen, board, font, high_score):
screen.fill(COLORS['bg'])
# 计算棋盘居中位置
grid_size = 4 * TILE_SIZE + 5 * SPACING # 总网格尺寸 (4方块+5间隔)
start_x = (WIDTH - grid_size) // 2 # 水平居中
start_y = 100 # 距离顶部固定间距
# 绘制棋盘
for i in range(4):
for j in range(4):
value = board[i][j]
# 修正坐标计算公式
x = start_x + j * (TILE_SIZE + SPACING)
y = start_y + i * (TILE_SIZE + SPACING)
# 绘制方块(添加阴影效果)
pygame.draw.rect(screen, COLORS.get(value, COLORS[0]),
(x, y, TILE_SIZE, TILE_SIZE), 0, 3)
# 添加数值文字
if value != 0:
text = font.render(str(value), True, COLORS['text'])
text_rect = text.get_rect(center=(x + TILE_SIZE // 2, y + TILE_SIZE // 2))
screen.blit(text, text_rect)
# 调整分数显示位置
score = sum(sum(row) for row in board)
score_text = font.render(f"Score: {score}", True, COLORS['text'])
high_text = font.render(f"High: {high_score}", True, COLORS['text'])
# 将分数信息放在棋盘上方居中
header_y = start_y - 40
screen.blit(score_text, (start_x, header_y)) # 左上对齐
screen.blit(high_text, (start_x + grid_size - high_text.get_width(), header_y)) # 右上对齐
def is_game_over(board):
if any(0 in row for row in board):
return False
for i in range(4):
for j in range(4):
if (j < 3 and board[i][j] == board[i][j + 1]) or \
(i < 3 and board[i][j] == board[i + 1][j]):
return False
return True
def game_over_screen(screen, font):
overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
overlay.fill(COLORS['gameover'])
text = font.render("Game Over!", True, (255, 0, 0))
text_rect = text.get_rect(center=(WIDTH // 2, HEIGHT // 2))
overlay.blit(text, text_rect)
screen.blit(overlay, (0, 0))
pygame.display.update()
def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("2048")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 36)
# 初始化最高分
high_score = load_high_score() # 新增
current_high = high_score # 新增
board = initialize_board()
direction_keys = {
pygame.K_w: 'up',
pygame.K_a: 'left',
pygame.K_s: 'down',
pygame.K_d: 'right',
pygame.K_UP: 'up',
pygame.K_LEFT: 'left',
pygame.K_DOWN: 'down',
pygame.K_RIGHT: 'right'
}
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 in direction_keys:
direction = direction_keys[event.key]
new_board, moved = move(board, direction)
if moved:
board = new_board
add_new_tile(board)
# 更新最高分
current_score = sum(sum(row) for row in board)
if current_score > current_high:
current_high = current_score
save_high_score(current_high) # 实时保存
elif event.key == pygame.K_r:
board = initialize_board()
# 重置时保留最高分
current_high = max(current_high, load_high_score())
draw_board(screen, board, font, current_high) # 修改调用
if is_game_over(board):
game_over_screen(screen, font)
# 游戏结束时确保保存
save_high_score(current_high)
pygame.display.flip()
clock.tick(30)
# 退出时保存
save_high_score(current_high)
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
总结
如果存在什么问题,还希望各位大佬能够指正。