一、安装第三方库
在开始做五子棋之前,我们得先下载第三方库。这个项目要用到pygame和numpy这两个第三方库。
已经安装好这两个库的同学,可以跳过这一段。
打开cmd,输入:
pip install pygame -i “https://pypi.doubanio.com/simple”
pip install numpy -i “https://pypi.doubanio.com/simple”
等待一小会儿,就安装好了。
二、库和常量
创建文件FIR.py,先导入所有库,然后初始化pygame,然后创建窗口,再设置一些变量。代码如下:
import pygame
import sys
import numpy as np
from pygame.locals import QUIT, KEYDOWN
pygame.init()
screen = pygame.display.set_mode([670, 670])
bg = "Tan3" # 背景颜色
black = [0, 0, 0] # 黑色
white = [255, 255, 255] # 白色
over_pos = [] # 保存下过的棋
flag = False # 标记延时
tim = 0 # 鼠标左键延时
三、判断胜利
创建函数check_win(over_pos),用于判断胜利。这个函数里面,首先需要创建一个“地图”,然后扫描一遍棋盘,如果检测到五子连心就返回颜色、坐标。代码如下:
def check_win(over_pos):
mp = np.zeros([15, 15], dtype=int) # 创建一个15*15的所有元素为零的嵌套列表
for val in over_pos: # 遍历列表
x = int((val[0][0] - 27) / 44) # 获取到x坐标
y = int((val[0][1] - 27) / 44) # 获取到y坐标
mp[y][x] = 1 if val[1] == black else 2 # 按照x、y坐标改变数值
for i in range(15): # i是y坐标
pos1 = []
pos2 = []
for j in range(15): # j是x坐标
if mp[i][j] == 1:
pos1.append([i, j])
else:
pos1 = []
if mp[i][j] == 2:
pos2.append([i, j])
else:
pos2 = []
if len(pos1) == 5: # 长度为5,五子连心
return 1, pos1
if len(pos2) == 5:
return 2, pos2
for j in range(15):
pos1 = []
pos2 = []
for i in range(15):
if mp[i][j] == 1:
pos1.append([i, j])
else:
pos1 = []
if mp[i][j] == 2:
pos2.append([i, j])
else:
pos2 = []
if len(pos1) == 5:
return 1, pos1
if len(pos2) == 5:
return 2, pos2
for i in range(15):
for j in range(15):
pos1 = []
pos2 = []
for k in range(15):
if i + k >= 15 or j + k >= 15:
break
if mp[i + k][j + k] == 1:
"""
假设棋盘上:
1 2 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 2 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 2 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 2 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
第一次循环,i = 0, j = 0, k = 0, break语句不会被执行。
i + k = 0, j + k = 0, mp[0][0] = 1, pos1会加上
[i