前言

棋需要一步一步下,人生需要一步一步走。千里之行,始于足下,九层之台,起于累土。

用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][n - 1] == 0:
                    shape[i][j][3] += 1
                if m - 1 >= 0 and n - 1 >= 0 and chesspad[m - 1][n - 1] == -color:
                    shape[i][j][3] -= 2
                m = i
                n = j
                # 如果右下方跟当前传入的颜色参数一致,那么加分到3位!
                while m + 1 < level  and n + 1 < level  and chesspad[m + 1][n + 1] == color:
                    m += 1
                    n += 1
                    shape[i][j][3] += grade
                if m + 1 < level  and n + 1 < level  and chesspad[m + 1][n + 1] == 0:
                    shape[i][j][3] += 1
                if m + 1 < level  and n + 1 < level  and chesspad[m + 1][n + 1] == -color:
                    shape[i][j][3] -= 2
    return shape def Sort(shape):
    for i in shape:
        for j in i:
            for x in range(5):
                for w in range(3, x - 1, -1):
                    if j[w - 1] < j[w]:
                        temp = j[w]
                        j[w - 1] = j[w]
                        j[w] = temp
    print("This Time Sort Done !")
    return shape def Evaluate(shape):
    for i in range(level):
        for j in range(level):             if shape[i][j][0] == 4:
                return i, j, MAX
            shape[i][j][4] = shape[i][j][0]*1000 + shape[i][j][1]*100 + shape[i][j][2]*10 + shape[i][j][3]
    max_x = 0
    max_y = 0
    max = 0
    for i in range(15):
        for j in range(15):
            if max < shape[i][j][4]:
                max = shape[i][j][4]
                max_x = i
                max_y = j
    print("the max is "+ str(max) + " at ( "+ str(max_x)+" , "+str(max_y)+" )")
    return max_x, max_y, max class chess(object):
    def __init__(self):
        self.a = [[0 for high in range(15)] for col in range(15)]      def fall(self, x, y, color):
        if (x < 0 or x > level - 1 or y < 0 or y > level - 1):
            return
        self.a[x][y] = color
        if Judge(x, y, color, self.a, 4):
            if color < 0:
                print("The Winner is White!!")            
else:                
print("The Winner is Black!!")     def isEmpty(self, m, n):        
if self.a[m][n] != 0:            
return False        
else:            
return True def Judge(x, y, color, CHESSLOCATION, length):    
count1, count2, count3, count4 = 0, 0, 0, 0    # 横向判断     i = x - 1    
while (i >= 0):        if color == CHESSLOCATION[
i][y]:            count1 += 1            i -= 1        else:            break    i = x + 1    while i  < level:        
if CHESSLOCATION[i][y] == color:            
count1 += 1            
i += 1        
else:            
break    # 纵向判断     j = y - 1    
while (j >= 0):        if CHESSLOCATION[
x][j] == color:            count2 += 1            j -= 1        else:            break    j = y + 1    while j  < level:        
if CHESSLOCATION[x][j] == color:            
count2 += 1            
j += 1        
else:            
break    # 正对角线判断     i, j = x - 1, y - 1    
while (i >= 0 and j >= 0):        if CHESSLOCATION[
i][j] == color:            count3 += 1            i -= 1            j -= 1        else:            break    i, j = x + 1, y + 1    while (i  < level and j < level):        
if CHESSLOCATION[i][j] == color:            
count3 += 1            
i += 1            
j += 1        
else:            
break    # 反对角线判断     i, j = x + 1, y - 1    
while (i < level and j >= 0):        if CHESSLOCATION[
i][j] == color:            count4 += 1            i += 1            j -= 1        else:            break    i, j = x - 1, y + 1    while (i > 0 and j  < level):        
if CHESSLOCATION[i][j] == color:            
count4 += 1            
i -= 1            
j += 1        
else:            
break     if count1 >= length or count2 >= length or count3 >= length or count4 >= length:        return True    else:        return Falsedef Autoplay(ch, m, n):    a1 = [1,-1,1,-1,1,-1,0,0]    b1 = [1,-1,-1,1,0,0,1,-1]    rand = randint(0,7)    while m+a1[ rand]>=0 and m+a1[rand]<level and n+b1[rand]>=0 and n+b1[rand]<level and ch[m+a1[rand]][n+b1[rand]]!=0 :        
rand = randint(0,7)    
return m + a1[rand], n+b1[rand] def BetaGo(ch, m, n, color, times):    
if times < 2:        
return Autoplay(ch, m, n)    
else:        
shape_P = Scan(ch, -color)        
shape_C = Scan(ch,color)        
shape_P = Sort(shape_P)        
shape_C = Sort(shape_C)        
max_x_P, max_y_P, max_P = Evaluate(shape_P)        
max_x_C, max_y_C, max_C = Evaluate(shape_C)        
if max_P>max_C and max_C<MAX:            
return max_x_P,max_y_P        
else:            
return max_x_C,max_y_C def satrtGUI(ch):    
pygame.init()    
bg = 'bg.png'    
white_image = 'white.png'    
black_image = 'black.png'     screen = pygame.display.set_mode((750, 750), 0, 32)    
background = pygame.image.load(bg).convert()    
white = pygame.image.load(white_image).convert_alpha()    
black = pygame.image.load(black_image).convert_alpha()    
white = pygame.transform.smoothscale(white, (int(white.get_width() * 1.5), int(white.get_height() * 1.5)))    
black = pygame.transform.smoothscale(black, (int(black.get_width() * 1.5), int(black.get_height() * 1.5)))     screen.blit(background, (0, 0))    
font = pygame.font.SysFont("黑体", 40)     pygame.event.set_blocked([1, 4, KEYUP, JOYAXISMOTION, JOYBALLMOTION, JOYBUTTONDOWN, JOYBUTTONUP, JOYHATMOTION])    
pygame.event.set_allowed([MOUSEBUTTONDOWN, MOUSEBUTTONUP, 12, KEYDOWN])     dot_list = [(25 + i * 50 - white.get_width() / 2, 25 + j * 50 - white.get_height() / 2) for i in range(level) for                
j in range(level)]    
color = -1    
times = 0    
flag = False    
while not flag:        
for event in pygame.event.get():            
if event.type == QUIT:                
exit()            
elif event.type == MOUSEBUTTONDOWN:                
x, y = pygame.mouse.get_pos()                
if 25 <= x <= 725 and 25 <= y <= 725 and ((x - 25) % 50 <= level or (x - 25) % 50 >= 0) and (                        (y - 25) % 50 
<= level or (y - 25) % 50 >= 0):                    color = -1 * color                    m = int(round((x - 25) / 50))                    n = int(round((y - 25) / 50))                    if not ch.isEmpty(m, n):                        print("Black OverWrite~~")                        continue                    ch.fall(m, n, color)                    screen.blit(black, dot_list[level * m + n])                    if Judge(m, n, color, ch.a, 4):                        screen.blit(font.render('GAME OVER,Black is win!', True, (110, 210, 30)), (80, 650))                        break                    color = -1 * color                    sleep(0.1)                    x, y = BetaGo(ch.a, m, n, color, times)                    times += 1                    print("Predict:" + str(x) + " and " + str(y))                    ch.fall(x, y, color)                    screen.blit(white, dot_list[level * x + y])                    if Judge(x, y, color, ch.a, 4):                        screen.blit(font.render('GAME OVER,White is win!', True, (217, 20, 30)), (80, 650))                        break        pygame.display.update()        if flag:            sleep(5)now = chess()satrtGUI(now)

本文章为公总号转载的,帮作者打个广告:以后关于Python的源码,书籍以及一些学习资料,都会分享到本群群文件,提供给大家学习,可入群自行下载。

当然你觉得有意思的,好的源码之类的也可以上传至本群文件。

Python学习群:864573496



【转】Python实现智能五子棋的更多相关文章

  1. python实现智能语音天气预报

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者: 飞奔的帅帅 PS:如有需要Python学习资料的小伙伴可以加点击下 ...

  2. Python&Selenium智能等待方法封装

    摘要:本篇博文用几行代码展示Python和Selenium做自动化测试时常见的显示等待和封装 # 用于实现智能等待页面元素的出现 # encoding = utf-8 ""&quo ...

  3. Python 代码智能感知 —— 类型标注与特殊的注释(献给所有的Python人)

    [原文地址:https://xiaokang2022.blog.csdn.net/article/details/126936985] ​ 一个不会写好的类型标注和注释的Python程序员,是让使用T ...

  4. Python 3 智能发音

    真是十分神奇.. import win32com.client import time s = win32com.client.Dispatch("SAPI.SpVoice") s ...

  5. Python——pyqt5——智能提示(lineEdit/conmbobox)

    一.文本框智能补全 completer = QtWidgets.QCompleter(data) completer.setCompletionMode(QtWidgets.QCompleter.Po ...

  6. 利用Python开发智能阅卷系统

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者: 机器学习与统计学 PS:如有需要Python学习资料的小伙伴可以加 ...

  7. 吴裕雄 PYTHON 人工智能——智能医疗系统后台智能分诊模块及系统健康养生公告简约版代码展示

    #coding:utf-8 import sys import cx_Oracle import numpy as np import pandas as pd import tensorflow a ...

  8. 吴裕雄 python 人工智能——智能医疗系统后台用户复诊模块简约版代码展示

    #复诊 import sys import os import time import operator import cx_Oracle import numpy as np import pand ...

  9. 吴裕雄 python 人工智能——智能医疗系统后台用户注册、登录和初诊简约版代码展示

    #用户注册.登录模块 #数据库脚本 CREATE TABLE usertable( userid number(8) primary key not null , username varchar(5 ...

随机推荐

  1. 【MySQL】(二)InnoDB存储引擎

    InnoDB是事务安全的MySQL存储引擎,设计上采用了类似于Oracel数据库的架构.通常来说,InnoDB存储引擎是OLTP应用中核心表的首选存储引擎.同时,也正是因为InnoDB的存在,才使My ...

  2. 序列化Serializable接口

    一.序列化 1.什么是序列化? 序列化就是将对象的状态存储到特定存储介质中的过程,也就是将对象状态转换为可保持或传输格式的过程. 在序列化过程中,会将对象的公有成员.私有成员(包括类名),转换为字节流 ...

  3. 【iOS】copy 关键字

    以前没注意过 iOS 的 copy, nonatomic, assign, weak, strong 等关键字. 偏偏今天遇到了一个问题,恰恰是关键字的问题,如图: 之前用的是 assign, 没有用 ...

  4. Linux 常用命令及使用方法

    1.  type   :查询命令 是否属于shell解释器 2.  help  : 帮助命令3.  man : 为所有用户提供在线帮助4.  ls  : 列表显示目录内的文件及目录 -l    以长格 ...

  5. Mysql的行级锁与表级锁

    在计算机科学中,锁是在执行多线程时用于强行限制资源访问的同步机制,即用于在并发控制中保证对互斥要求的满足. 在DBMS中,可以按照锁的粒度把数据库锁分为行级锁(INNODB引擎).表级锁(MYISAM ...

  6. swift 分享share页面封装(功能按钮不同)

    关于分享功能的页面应该有很多,写这篇swift版本的分享页面,根据不同模块可能分享的功能按钮不一样,引言: 想必大家都使用微博右上角更多按钮,会弹出如下的界面: 在开发中,可能针对同一个app的不同按 ...

  7. JS和C#.NET获取客户端IP

    我们经常在项目中会遇到这种需要获取客户端真实IP的需求,其实在网上也能随便就能查到各种获取的方法,我也是在网上查了加上了自己的实践,说一下自己在实践后的感受,基本上网上大部分都是用JS的方法来获取客户 ...

  8. JAVA基础知识(三):input.nextLine() 和input.next()

    next()方法在读取内容时,会过滤掉有效字符前面的无效字符,对输入有效字符之前遇到的空格键.Tab键或Enter键等结束符,next()方法会自动将其过滤掉:只有在读取到有效字符之后,next()方 ...

  9. Netty学习(一)-为什么选择Netty

    前面我们简单学习了NIO.我们知道java的I/O模型一共有四种,分别是:传统的BIO,伪异步I/O,NIO和AIO.为了澄清概念和分清区别,我们还是先简单的介绍一下他们的概念,然后再去比较优劣.以及 ...

  10. n的阶乘 -牛客

    题目描述 输入一个整数n,输出n的阶乘(每组测试用例可能包含多组数据,请注意处理) 输入描述: 一个整数n(1<=n<=20) 输出描述: n的阶乘 解题思路 采用递归求解,也可以使用循环 ...