最近看了个不错的人机五子棋游戏,所以就做了写学习笔记
python_pygame五子棋人机游戏
思路
游戏屏幕
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
pygame.display.set_caption('五子棋')
-
pygme.init() 初始化display 模块
-
pygame.display.set_mode() 初始化一个准备显示的窗口或屏幕
-
SIZE = 30 # 棋盘每个点时间的间隔 Line_Points = 19 # 棋盘每行/每列点数 Outer_Width = 20 # 棋盘外宽度 Border_Width = 4 # 边框两侧总宽度 Inside_Width = 4 # 边框跟实际的棋盘之间的间隔
-
棋盘大小为19*19,棋盘中每个小格子大小为30*30。棋盘外两边宽度均为20,棋盘外边框的两边宽度均为4,棋盘边框实际到棋盘的间隔均为4
-
SCREEN_HEIGHT = SIZE * (Line_Points - 1) + Outer_Width * 2 + Border_Width + Inside_Width * 2 # 游戏屏幕的高 SCREEN_WIDTH = SCREEN_HEIGHT + 200 # 游戏屏幕的宽
-
棋盘右方显示黑棋白棋,所以游戏屏幕的款要在高的基础上再加上200
-
- pygame.display.set_caption() 设置屏幕标题
棋盘绘制
SIZE = 30 # 棋盘每个点时间的间隔
Line_Points = 19 # 棋盘每行/每列点数
Border_Width = 4 # 边框两侧总宽度
Inside_Width = 4 # 边框跟实际的棋盘之间的间隔
Border_Length = SIZE * (Line_Points - 1) + Inside_Width * 2 + Border_Width # 边框线的长度
- Border_Length:屏幕高度的基础上减去棋盘两侧外宽度即可
Outer_Width = 20 # 棋盘外宽度
Start_X = Start_Y = Outer_Width + int(Border_Width / 2) + Inside_Width # 网格线起点(左上角)坐标
- Start_x和Start_Y:棋盘网格线(左上角)的坐标
Checkerboard_Color = (0xE3, 0x92, 0x65) # 棋盘颜色
BLACK_COLOR = (0, 0, 0)
WHITE_COLOR = (255, 255, 255)
RED_COLOR = (200, 30, 30)
BLUE_COLOR = (30, 30, 200)
填充棋盘背景色
# 填充棋盘背景色
screen.fill(Checkerboard_Color)
- screen.fill(color) 填充背景颜色
绘制棋盘边框
-
pygame.draw.rect(screen, BLACK_COLOR, (Outer_Width, Outer_Width, Border_Length, Border_Length), Border_Width)
- 在游戏屏幕上绘制黑色的矩形边框
- 所绘制矩形的区域:(Outer_Width, Outer_Width, Border_Length, Border_Length)
- 绘制矩形左上角的坐标为:(Outer_Width, Outer_Width)
- 矩形宽度和高度为:(Border_Length, Border_Length)
- 线条粗细为:Border_Width
知识点
- pygame.draw.rect(Surface,color,Rect,width=0)
- 绘制矩形,第二个参数为线条的颜色
- 第三个参数表示所绘制矩形的区域,(x,y,width,height)
- (x,y)表示该矩形左上角的坐标
- (width,height)表示矩形的宽度和高度
- 第四个参数表示线条的粗细
网格线
# 画网格线
for i in range(Line_Points):
pygame.draw.line(screen, BLACK_COLOR,
(Start_Y, Start_Y + SIZE * i),
(Start_Y + SIZE * (Line_Points - 1), Start_Y + SIZE * i),
1)
for j in range(Line_Points):
pygame.draw.line(screen, BLACK_COLOR,
(Start_X + SIZE * j, Start_X),
(Start_X + SIZE * j, Start_X + SIZE * (Line_Points - 1)),
1)
-
通过遍历的方法分别画出所有行和列
-
在游戏屏幕上绘制黑色的直线
-
直线起始点坐标: (Start_Y, Start_Y + SIZE * i)
-
直线终止点坐标: (Start_Y + SIZE * (Line_Points - 1), Start_Y + SIZE * i)
-
1:线条宽度为1
知识点
- pygame.draw.line(Surface,color,start_pos,end_pos,wirth=1)
- 绘制直线段
- start_pos和end_pos分别表示起始点和终止点,用坐标表示
- width为线条宽度,默认为1
棋盘中心及几处交叉点突出显示
# 画棋盘上中心位置和其他某些交点处交点
for i in (3, 9, 15):
for j in (3, 9, 15):
if i == j == 9:
radius = 5
else:
radius = 3
pygame.gfxdraw.aacircle(screen, Start_X + SIZE * i, Start_Y + SIZE * j, radius, BLACK_COLOR)
pygame.gfxdraw.filled_circle(screen, Start_X + SIZE * i, Start_Y + SIZE * j, radius, BLACK_COLOR)
- 在棋盘(3,3)、(3,9)、(3,15)、(9,3)、(9,9)、(9,15)、(15,3)、(15,9)、(15,15)处用黑色圆点突出显示。
- 如果是(9,9),则黑圆点的半径为5;否则半径为3。
- (9,9)为棋盘的中心位置
知识点
- pygame.gfxdraw.aacircle(surface,x,y,r,color)
- 绘制一个平滑(抗锯齿)的圆形
如果用pygame.draw.circle()的话,画出来的圆形有明显的锯齿状。
- pygame.gfxdraw.filled_circle(surface,x,y,r,color)
- 绘制填充的圆形
棋子绘制
Stone_Radius = SIZE // 2 - 3 # 棋子半径
# 画棋子
def _draw_chessman(screen, point, stone_color):
pygame.gfxdraw.aacircle(screen, Start_X + SIZE * point.X, Start_Y + SIZE * point.Y, Stone_Radius, stone_color)
pygame.gfxdraw.filled_circle(screen, Start_X + SIZE * point.X, Start_Y + SIZE * point.Y, Stone_Radius, stone_color)
落子
落子需要判断鼠标事件,当鼠标左键点击,获取鼠标点击的位置,然后根据棋盘的位置,计算出棋子落在棋盘的位置。
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == MOUSEBUTTONDOWN:#MOUSEBUTTONDOWN 鼠标按下
if winner is None:
pressed_array = pygame.mouse.get_pressed()
if pressed_array[0]:
mouse_pos = pygame.mouse.get_pos()
click_point = _get_clickpoint(mouse_pos)#调用函数_get_clickpoint返回坐标
- for event in pygame.event.get(): 获取键盘、鼠标事件
- event.type == MOUSEBUTTONDOWN
- MOUSEBUTTONDOWN 鼠标按下
知识点
鼠标事件
- MOUSEMOTION:鼠标移动
- MOUSEBUTTONDOWN:鼠标按下
- MOUSEBUTTONUP:鼠标抬起
键盘事件
-
KEYDOWN 键盘按下
- K_LEFT 左
- K_RIGHT 右
- K_UP 上
- K_DOWN 下
- K_RETURN return
- K_SPACE space
- …
-
KEYUP 键盘抬起
根据鼠标点击位置,返回游戏区坐标
def _get_clickpoint(click_pos):
# print('起点坐标',Start_X, Start_Y)
pos_x = click_pos[0] - Start_X
pos_y = click_pos[1] - Start_Y
if pos_x < -Inside_Width or pos_y < -Inside_Width:
return None
x = pos_x // SIZE
y = pos_y // SIZE
if pos_x % SIZE > Stone_Radius:
x += 1
if pos_y % SIZE > Stone_Radius:
y += 1
if x >= Line_Points or y >= Line_Points:
return None
return Point(x, y)
- **通过鼠标点击处的坐标,减去左上角的起点坐标,**则得到现在棋子在棋盘上的坐标位置。即(pos_x,pos_y)。
- 如果点击位置与棋盘格大小比例大于棋子的半径,则棋子落下+1的位置上。
胜负判定
当某一子落下的时候,如果出现了5连,则落下的这颗子必定在这条5连线上。这时候就无需全盘扫描,只需要在落子位置上8个方向扫描一下,判断是否出现5连线即可。
class Checkerboard:
def __init__(self, line_points):
self._line_points = line_points
self._checkerboard = [[0] * line_points for _ in range(line_points)]
def _get_checkerboard(self):
return self._checkerboard
checkerboard = property(_get_checkerboard)
# 判断是否可落子
def can_drop(self, point):
return self._checkerboard[point.Y][point.X] == 0
def drop(self, chessman, point):
"""
落子
:param chessman:
:param point:落子位置
:return:若该子落下之后即可获胜,则返回获胜方,否则返回 None
"""
print(f'{chessman.Name} ({point.X}, {point.Y})')
self._checkerboard[point.Y][point.X] = chessman.Value
if self._win(point):
print(f'{chessman.Name} Win')
return chessman
# 判断是否赢了
def _win(self, point):
cur_value = self._checkerboard[point.Y][point.X]
for os in offset:
if self._get_count_on_direction(point, cur_value, os[0], os[1]):
return True
def _get_count_on_direction(self, point, value, x_offset, y_offset):
count = 1
for step in range(1, 5):
x = point.X + step * x_offset
y = point.Y + step * y_offset
if 0 <= x < self._line_points and 0 <= y < self._line_points and self._checkerboard[y][x] == value:
count += 1
else:
break
for step in range(1, 5):
x = point.X - step * x_offset
y = point.Y - step * y_offset
if 0 <= x < self._line_points and 0 <= y < self._line_points and self._checkerboard[y][x] == value:
count += 1
else:
break
return count >= 5
- 定义一个 Checkerboard棋盘类。
- 类中实例化一个19*19的二维数组,且初始化全为0,表示空。
- 函数 _get_count_on_direction(),不同的偏移量表示不同的方向,判断不同方向上的棋子数量
电脑落子
遍历棋盘上的空位,计算每个位置其8个方向上是否有我方的子,有一个就加10分,最后选得分最高的位置落子。
五子棋的几种基本棋形
五子棋的几种基本棋形:连五、活四、冲四、活三、眠三、活二、眠二。
- 连五
- 五颗同色棋子连在一起。
- 活四
- 四颗同色棋子连在一起,并且左右两边都没有对方棋子阻挡。
- 有两个连五点
- 冲四
- 四颗同色棋子连在一起,并且一边有对方棋子阻挡
- 或者四颗棋子不是连着的,当中有空档
- 只有一个连五点
- 活三
- 三颗同色棋子连在一起
- 跳活三
- 中间隔了一个空格的活三
- 眠三
- 一边被对方棋子阻挡
- 当中有两个空格
- 活二和眠二
打分机制
- 首选,不可能出现连五情形。因为当出现连五的时候胜负就已经定了。所以只要棋局还在进行中,就不会出现连五
- 其次是对方的“四”。
- 如果对方已经是活四,那此时不管你防还是不防,都一样是输。
- 如果对方是冲四,你就必须得防守。
- 再次是我方的活三或冲四,对方必须防守
- 再次是对方的活三或冲四。
右侧信息显示
def _draw_right_info(screen, font, cur_runner, black_win_count, white_win_count):
_draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, Start_X + Stone_Radius2), BLACK_CHESSMAN.Color)
_draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, Start_X + Stone_Radius2 * 4), WHITE_CHESSMAN.Color)
print_text(screen, font, RIGHT_INFO_POS_X, Start_X + 3, 'Player', BLUE_COLOR)
print_text(screen, font, RIGHT_INFO_POS_X, Start_X + Stone_Radius2 * 3 + 3, 'Computer', BLUE_COLOR)
print_text(screen, font, SCREEN_HEIGHT, SCREEN_HEIGHT - Stone_Radius2 * 8, 'Battle situation:', BLUE_COLOR)
_draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, SCREEN_HEIGHT - int(Stone_Radius2 * 4.5)), BLACK_CHESSMAN.Color)
_draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, SCREEN_HEIGHT - Stone_Radius2 * 2), WHITE_CHESSMAN.Color)
print_text(screen, font, RIGHT_INFO_POS_X, SCREEN_HEIGHT - int(Stone_Radius2 * 5.5) + 3, f'{black_win_count} Win', BLUE_COLOR)
print_text(screen, font, RIGHT_INFO_POS_X, SCREEN_HEIGHT - Stone_Radius2 * 3 + 3, f'{white_win_count} Win', BLUE_COLOR)
其余知识点
元组
collections.nametuple('typename','field_names',verbose=false,rename=false)
- typename:元组名称
- field_names:元组内部元素的名称
- rename:如果元组元素名称中包含python的关键字,就必须设置为rename=true
- verbose:默认值
原文代码:
from collections import namedtuple
Chessman = namedtuple('Chessman', 'Name Value Color')
Point = namedtuple('Point', 'X Y')
打了n局,就赢了1次,悲哀啊~