Python实现智能五子棋
Posted 糟了是心动的感觉
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python实现智能五子棋相关的知识,希望对你有一定的参考价值。
前言
棋需要一步一步下,人生需要一步一步走。千里之行,始于足下,九层之台,起于累土。
用Python五子棋小游戏。
基本环境配置
版本:Python3
相关模块:
本文所做工作如下:
(1) 五子棋界面实现;
(2) 智能判定棋盘走势;
(3) 改进了棋盘扫描方式;
(4) 改良了系统评分表评估方式;
(5) 实现了基于点评分表估值找出最佳落子方式。
实现效果图
emmmm,系统是执白子,小编是执黑子,结果显示,系统赢了,哈哈哈哈....尴尬,不要在在意这些细节,咱们看代码,看代码~~~~
代码实现
from time import sleep
import pygame
from pygame.locals import *
from random import randint
level = 15
grade = 10
MAX = 1008611
def Scan(chesspad, color):
shape = [[[0 for high in range(5)] for col in range(15)] for row in range(15)]
# 扫描每一个点,然后在空白的点每一个方向上做出价值评估!!
for i in range(15):
for j in range(15):
# 如果此处为空 那么就可以开始扫描周边
if chesspad[i][j] == 0:
m = i
n = j
# 如果上方跟当前传入的颜色参数一致,那么加分到0位!
while n - 1 >= 0 and chesspad[m][n - 1] == color:
n -= 1
shape[i][j][0] += grade
if n-1>=0 and chesspad[m][n - 1] == 0:
shape[i][j][0] += 1
if n-1 >= 0 and chesspad[m][n - 1] == -color:
shape[i][j][0] -= 2
m = i
n = j
# 如果下方跟当前传入的颜色参数一致,那么加分到0位!
while (n + 1 < level and chesspad[m][n + 1] == color):
n += 1
shape[i][j][0] += grade
if n + 1 < level and chesspad[m][n + 1] == 0:
shape[i][j][0] += 1
if n + 1 < level and chesspad[m][n + 1] == -color:
shape[i][j][0] -= 2
m = i
n = j
# 如果左边跟当前传入的颜色参数一致,那么加分到1位!
while (m - 1 >= 0 and chesspad[m - 1][n] == color):
m -= 1
shape[i][j][1] += grade
if m - 1 >= 0 and chesspad[m - 1][n] == 0:
shape[i][j][1] += 1
if m - 1 >= 0 and chesspad[m - 1][n] == -color:
shape[i][j][1] -= 2
m = i
n = j
# 如果右边跟当前传入的颜色参数一致,那么加分到1位!
while (m + 1 < level and chesspad[m + 1][n] == color):
m += 1
shape[i][j][1] += grade
if m + 1 < level and chesspad[m + 1][n] == 0:
shape[i][j][1] += 1
if m + 1 < level and chesspad[m + 1][n] == -color:
shape[i][j][1] -= 2
m = i
n = j
# 如果左下方跟当前传入的颜色参数一致,那么加分到2位!
while (m - 1 >= 0 and n + 1 < level and chesspad[m - 1][n + 1] == color):
m -= 1
n += 1
shape[i][j][2] += grade
if m - 1 >= 0 and n + 1 < level and chesspad[m - 1][n + 1] == 0:
shape[i][j][2] += 1
if m - 1 >= 0 and n + 1 < level and chesspad[m - 1][n + 1] == -color:
shape[i][j][2] -= 2
m = i
n = j
# 如果右上方跟当前传入的颜色参数一致,那么加分到2位!
while (m + 1 < level and n - 1 >= 0 and chesspad[m + 1][n - 1] == color):
m += 1
n -= 1
shape[i][j][2] += grade
if m + 1 < level and n - 1 >= 0 and chesspad[m + 1][n - 1] == 0:
shape[i][j][2] += 1
if m + 1 < level and n - 1 >= 0 and chesspad[m + 1][n - 1] == -color:
shape[i][j][2] -= 2
m = i
n = j
# 如果左上方跟当前传入的颜色参数一致,那么加分到3位!
while (m - 1 >= 0 and n - 1 >= 0 and chesspad[m - 1][n - 1] == color):
m -= 1
n -= 1
shape[i][j][3] += grade
if m - 1 >= 0 and n - 1 >= 0 and chesspad[m - 1][