pygame开发:马赛逻辑小游戏的代码实现

二、核心代码解析

```def get_line_remind(_line):  # 输出一行或一列的提示
remind = []  # 一行或一列的提示记录
num = 0  # 提示值
def fun(line):
nonlocal remind, num
flag = 0  # 位移
if len(line) > 1:
if line[0] == 0 and line[1] == 1:
flag += 1
elif line[0] == line[1] == 0:
flag += 2
elif line[0] == 1 and line[1] == 0:
num += 1
remind.append(num)
num = 0
flag += 2
elif line[0] == line[1] == 1:
num += 1
flag += 1
fun(line[flag:])
elif len(line) and line[0]:
if num:
remind.append(num + 1)
else:
remind.append(1)
fun(_line)
return remind
```

三、pygame开发流程

1、从创建窗口到棋盘绘制

```import pygame
import sys
# 参数设置 ----------------------------------
blue = (159, 197, 232)  # 被选中方格的颜色
gray = (217, 217, 217)  # 棋盘网格线颜色
gold = (255, 215, 0)  # 游戏记录文字颜色
black = (0, 0, 0)
white = (255, 255, 255)
start_x = 240  # 棋盘左上角位置
start_y = 150
size = 2  # 一行/列的方块个数
square = 320  # 棋盘边长
length = int(square / size)  # 每个方块的边长
# 游戏初始化 ----------------------------------
pygame.init()
screen = pygame.display.set_mode((780, 520))  # 创建窗口
font = pygame.font.Font(r'./data/msyh.ttf', 20)  # 提示字体
# 主循环 ----------------------------------
while True:
screen.fill(white)  # 背景填充
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()  # 退出pygame
sys.exit()  # 安全退出系统
pygame.display.flip()  # 更新全部显示
```

```class Item:  # 自定义方块类
def __init__(self, pos_x, pos_y, leng):
self.rect = pygame.draw.rect(screen, gray, [pos_x, pos_y, leng, leng], 0)
self.state = False
```

```def create_chessboard():  # 创建棋盘
item_lst = []
for v in range(size):
for h in range(size):
rect = Item(start_x + h*length, start_y + v*length, length)
item_lst.append(rect)
return item_lst
```

```def draw_line():  # 绘制网格线
for n in range(size+1):
start = (start_x, start_y + n * length)
end = (start_x + square, start_y + n * length)
pygame.draw.line(screen, gray, start, end, 2)
for n in range(size+1):
start = (start_x + n * length, start_y)
end = (start_x + n * length, start_y + square)
pygame.draw.line(screen, gray, start, end, 2)
```

```## 前文参数、初始化略
......
items = create_chessboard()  # 创建棋盘
while True:
screen.fill(white)  # 背景填充
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()  # 退出pygame
sys.exit()  # 安全退出系统
draw_line()  # 绘制棋盘网格线
pygame.display.flip()  # 更新全部显示
```

2、点击方格改变颜色

2.1、点击事件

``` if event.type == pygame.MOUSEBUTTONDOWN:  # 鼠标点击事件
x, y = event.pos
```

2.2、碰撞检测

```def check_click(item_lst, pos_x, pos_y):  # 更新每个方块的点击状态
for i in item_lst:
if i.rect.collidepoint(pos_x, pos_y):
i.state = bool(1 - i.state)
```

2.3、方格变色

```def change_color(item_lst):  # 根据状态改变方块颜色
for i in item_lst:
if i.state:
pygame.draw.rect(screen, blue, i.rect, 0)
else:
pygame.draw.rect(screen, white, i.rect, 0)
```

2.4、阵列转换

```def create_answer_array():  # 创建答案矩阵
lst = [1 if random() > 0.5 else 0 for _ in range(size*size)]
if list(set(lst))[0] == 0:
lst[0] = 1
return lst
```

```def create_answer_array():  # 创建答案矩阵
lst = [1 if random() > 0.5 else 0 for _ in range(size*size)]
if list(set(lst))[0] == 0:
lst[0] = 1
return lst
```

2.5、效果初见

```## 前文参数、初始化略
......
answer = create_answer_array()  # 创建答案矩阵
# 主循环 ----------------------------------
while True:
screen.fill(white)  # 背景填充
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()  # 退出pygame
sys.exit()  # 安全退出系统
if event.type == pygame.MOUSEBUTTONDOWN:  # 鼠标点击事件
x, y = event.pos
check_click(items, x, y)  # 检查选中的方格，修改状态
result = get_player_array(items)  # 获取方格操作矩阵
print(result)
if result == answer:
print("YOU WIN!")
change_color(items)  # 根据方格状态修改颜色
draw_line()  # 绘制棋盘网格线
pygame.display.flip()  # 更新全部显示
```

3、显示提示信息

```def get_w_remind(answer_lst):  # 根据答案矩阵输出提示列表
h_remind = []
v_remind = []
h_array = [answer_lst[i: i+size] for i in range(0, len(answer_lst), size)]  # 横向矩阵
for h in h_array:
h_remind.append(get_line_remind(h))
v_array = list(map(list, zip(*h_array)))  # 纵向矩阵
for v in v_array:
v_remind.append(get_line_remind(v))
return h_remind, v_remind
```

```def show_remind(answer_lst):  # 在棋盘两侧对应位置显示每行/列的提示
h_remind, v_remind = get_w_remind(answer_lst)
for i, h in enumerate(h_remind):
for j, num in enumerate(h[::-1]):
text = font.render(f"{num}", True, black)
screen.blit(text, (start_x - 20 * (j + 1), start_y + i * length + length / 2 - 10))
for i, v in enumerate(v_remind):
for j, num in enumerate(v[::-1]):
text = font.render(f"{num}", True, black)
screen.blit(text, (start_x + i * length + length / 2 - 5, start_y - 30 * (j + 1)))
```