python实现简易五子棋小游戏(三种方式)

Posted ASS-ASH

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python实现简易五子棋小游戏(三种方式)相关的知识,希望对你有一定的参考价值。

tkinter库:Python的标准Tk GUI工具包的接口

示例:

from tkinter import *
root = Tk()
#你的ui代码
Label(root,text = 'hello world!').pack()
root.mainloop()

弹窗结果: 

 

五子棋小游戏实现(一): 

from tkinter import *
import tkinter.messagebox  # 弹窗库
import numpy as np

root = Tk()                                 #创建窗口
root.title("五子棋游戏")                  #窗口名字
w1 = Canvas(root, width=600,height=600,background='chocolate')
w1.pack()

for i in range(0, 15):
    w1.create_line(i * 40 + 20, 20, i * 40 + 20, 580)
    w1.create_line(20, i * 40 + 20, 580, i * 40 + 20)
w1.create_oval(135, 135, 145, 145,fill='black')
w1.create_oval(135, 455, 145, 465,fill='black')
w1.create_oval(465, 135, 455, 145,fill='black')
w1.create_oval(455, 455, 465, 465,fill='black')
w1.create_oval(295, 295, 305, 305,fill='black')

num=0
A=np.full((15,15),0)
B=np.full((15,15),'')
def callback(event):
    global num ,A
    for j in range (0,15):
        for i in range (0,15):
            if (event.x - 20 - 40 * i) ** 2 + (event.y - 20 - 40 * j) ** 2 <= 2 * 20 ** 2:
                break
        if (event.x - 20 - 40 * i) ** 2 + (event.y - 20 - 40 * j) ** 2 <= 2*20 ** 2:
            break
    if num % 2 == 0 and A[i][j] != 1:
        w1.create_oval(40*i+5, 40*j+5, 40*i+35, 40*j+35,fill='black')
        A[i][j] = 1
        B[i][j] = 'b'
        num += 1
    if num % 2 != 0 and A[i][j] != 1 :
        w1.create_oval(40*i+5, 40*j+5, 40*i+35, 40*j+35,fill='white')
        A[i][j] = 1.
        B[i][j] = 'w'
        num += 1

    f = [[-1, 0], [-1, 1], [0, 1], [1, 1]]
    for z in range(0, 4):
        a, b = f[z][0], f[z][1]
        count1, count2 = 0, 0
        x, y = i, j
        while B[x][y] == B[i][j]:
            count1 += 1
            if x + a >= 0 and y + b >= 0 and x + a < 15 and y + b < 15 and B[x + a][y + b] == B[i][j]:
                [x, y] = np.array([x, y]) + np.array([a, b])
            else:
                x, y = i, j
                break
        while B[x][y] == B[i][j]:
            count2 += 1
            if x - a < 15 and y - b < 15 and x - a >= 0 and y - b >= 0 and B[x - a][y - b] == B[i][j]:
                [x, y] = np.array([x, y]) - np.array([a, b])
            else:
                break
        if count1 + count2 == 6:
            if B[i][j] == 'b':
                tkinter.messagebox.showinfo('提示', '黑棋获胜')
            else:
                tkinter.messagebox.showinfo('提示', '白棋获胜')

w1.bind("<Button -1>",callback)
w1.pack()
def quit():
    root.quit()

u=Button(root,text="退出",width=10,height=1,command=quit,font=('楷体',15))
u.pack()

mainloop()

运行结果:

 

 

                    此程序确定胜利后会继续在同一棋盘上继续下棋,没有刷新棋盘

 w1 = Canvas(root, width=600,height=600,background='chocolate')可根据参数background改变棋盘颜色

 

 五子棋小游戏实现(二): 

#调用pygame库
import pygame
import sys
#调用常用关键字常量
from pygame.locals import QUIT,KEYDOWN
import numpy as np
#初始化pygame
pygame.init()
#获取对显示系统的访问,并创建一个窗口screen
#窗口大小为670x670
screen = pygame.display.set_mode((670,670))
screen_color=[238,154,73]#设置画布颜色,[238,154,73]对应为棕黄色
line_color = [0,0,0]#设置线条颜色,[0,0,0]对应黑色
  
def check_win(over_pos):#判断五子连心
    mp=np.zeros([15,15],dtype=int)
    for val in over_pos:
        x=int((val[0][0]-27)/44)
        y=int((val[0][1]-27)/44)
        if val[1]==white_color:
            mp[x][y]=2#表示白子
        else:
            mp[x][y]=1#表示黑子
  
    for i in range(15):
        pos1=[]
        pos2=[]
        for j 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 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:
                    pos1.append([i+k,j+k])
                else:
                    pos1=[]
                if mp[i+k][j+k]==2:
                    pos2.append([i+k,j+k])
                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<0:
                    break
                if mp[i+k][j-k]==1:
                    pos1.append([i+k,j-k])
                else:
                    pos1=[]
                if mp[i+k][j-k]==2:
                    pos2.append([i+k,j-k])
                else:
                    pos2=[]
                if len(pos1)>=5:
                    return [1,pos1]
                if len(pos2)>=5:
                    return [2,pos2]
    return [0,[]]
  
def find_pos(x,y):#找到显示的可以落子的位置
    for i in range(27,670,44):
        for j in range(27,670,44):
            L1=i-22
            L2=i+22
            R1=j-22
            R2=j+22
            if x>=L1 and x<=L2 and y>=R1 and y<=R2:
                return i,j
    return x,y
  
def check_over_pos(x,y,over_pos):#检查当前的位置是否已经落子
    for val in over_pos:
        if val[0][0]==x and val[0][1]==y:
            return False
    return True#表示没有落子
flag=False
tim=0
  
over_pos=[]#表示已经落子的位置
white_color=[255,255,255]#白棋颜色
black_color=[0,0,0]#黑棋颜色
  
while True:#不断训练刷新画布
  
    for event in pygame.event.get():#获取事件,如果鼠标点击右上角关闭按钮,关闭
        if event.type in (QUIT,KEYDOWN):
            sys.exit()
  
    screen.fill(screen_color)#清屏
    for i in range(27,670,44):
        #先画竖线
        if i==27 or i==670-27:#边缘线稍微粗一些
            pygame.draw.line(screen,line_color,[i,27],[i,670-27],4)
        else:
            pygame.draw.line(screen,line_color,[i,27],[i,670-27],2)
        #再画横线
        if i==27 or i==670-27:#边缘线稍微粗一些
            pygame.draw.line(screen,line_color,[27,i],[670-27,i],4)
        else:
            pygame.draw.line(screen,line_color,[27,i],[670-27,i],2)
  
    #在棋盘中心画个小圆表示正中心位置
    pygame.draw.circle(screen, line_color,[27+44*7,27+44*7], 8,0)
  
    for val in over_pos:#显示所有落下的棋子
        pygame.draw.circle(screen, val[1],val[0], 20,0)
  
    #判断是否存在五子连心
    res=check_win(over_pos)
    if res[0]!=0:
        for pos in res[1]:
            pygame.draw.rect(screen,[238,48,167],[pos[0]*44+27-22,pos[1]*44+27-22,44,44],2,1)
        pygame.display.update()#刷新显示
        continue#游戏结束,停止下面的操作
    #获取鼠标坐标信息
    x,y = pygame.mouse.get_pos()
  
    x,y=find_pos(x,y)
    if check_over_pos(x,y,over_pos):#判断是否可以落子,再显示
        pygame.draw.rect(screen,[0 ,229 ,238 ],[x-22,y-22,44,44],2,1)
  
    keys_pressed = pygame.mouse.get_pressed()#获取鼠标按键信息
    #鼠标左键表示落子,tim用来延时的,因为每次循环时间间隔很断,容易导致明明只按了一次左键,却被多次获取,认为我按了多次
    if keys_pressed[0] and tim==0:
        flag=True
        if check_over_pos(x,y,over_pos):#判断是否可以落子,再落子
            if len(over_pos)%2==0:#黑子
                over_pos.append([[x,y],black_color])
            else:
                over_pos.append([[x,y],white_color])
  
    #鼠标左键延时作用
    if flag:
        tim+=1
    if tim%50==0:#延时200ms
        flag=False
        tim=0
  
    pygame.display.update()#刷新显示

 Pygame是一个跨平台Python库,包含图像、声音。建立在SDL基础上,允许实时电子游戏研发而无需被低级语言(如机器语言汇编语言)束缚。基于这样一个设想,所有需要的游戏功能和理念都(主要是图像方面)都完全简化为游戏逻辑本身,所有的资源结构都可以由高级语言提供,如Python

运行结果:

此程序会以红框方式显示胜利,但无法刷新棋盘,游戏过程中任何键盘按键触碰都会导致游戏退出

 五子棋小游戏实现(三): 

同样依赖于Pygame库

#coding:utf-8
import sys
import pygame
import random
def do():
    def black(x, y):
        a = 20
        b = 20
        c = 20
        d = 0
        for i in range(50):
            pygame.draw.circle(screen, (a, b, c), [19.5 + 32 * x, 19.5 + 32 * y], (10/(d-5)+10)*1.6)
            a += 1
            b += 1
            c += 1
            d += 0.08
        pygame.display.update()

    def white(x, y):
        a = 170
        b = 170
        c = 170
        d = 0
        for i in range(50):
            pygame.draw.circle(screen, (a, b, c), [19.5 + 32 * x, 19.5 + 32 * y], (10/(d-5)+10)*1.6)
            a += 1
            b += 1
            c += 1
            d += 0.08
        pygame.display.update()
    pygame.init()
    screen = pygame.display.set_mode((615, 615))
    pygame.display.set_caption('五子棋')
    screen.fill("#DD954F")
    a = pygame.Surface((603, 603), flags=pygame.HWSURFACE)
    a.fill(color='#121010')
    b = pygame.Surface((585, 585), flags=pygame.HWSURFACE)
    b.fill(color="#DD954F")
    c = pygame.Surface((579, 579), flags=pygame.HWSURFACE)
    c.fill(color='#121010')
    d = pygame.Surface((576, 576), flags=pygame.HWSURFACE)
    d.fill(color="#DD954F")
    e = pygame.Surface((31, 31), flags=pygame.HWSURFACE)
    e.fill(color="#DD954F")
    screen.blit(a, (6.5, 6.5))
    screen.blit(b, (15, 15))
    screen.blit(c, (18, 18))
    for j in range(18):
        for i in range(18):
            screen.blit(e, (20 + 32 * i, 20 + 32 * j))
    alist = []
    for j in range(19):
        alistone = []
        for i in range(19):
            alistone.append(0)
        alist.append(alistone)
    pygame.draw.circle(screen, '#121010', [307.5, 307.5], 5)
    pygame.draw.circle(screen, '#121010', [115.5, 307.5], 5)
    pygame.draw.circle(screen, '#121010', [499.5, 307.5], 5)
    pygame.draw.circle(screen, '#121010', [115.5, 499.5], 5)
    pygame.draw.circle(screen, '#121010', [499.5, 499.5], 5)
    pygame.draw.circle(screen, '#121010', [115.5, 115.5], 5)
    pygame.draw.circle(screen, '#121010', [499.5, 115.5], 5)
    pygame.draw.circle(screen, '#121010', [307.5, 499.5], 5)
    pygame.draw.circle(screen, '#121010', [307.5, 115.5], 5)
    pygame.display.flip()
    wb = "black"
    font1 = pygame.font.SysFont('stxingkai', 70)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                x, y = pygame.mouse.get_pos()
                x = round((x - 19.5) / 32)
                y = round((y - 19.5) / 32)
                if x < 0:
                    x = 0
                if x > 18:
                    x = 18
                if y < 0:
                    y = 0
                if y > 18:
                    y = 18
                z = False
                if alist[x][y] == 0:
                    eval(wb + "(,)".format(x, y))
                    if wb == "black":
                        alist[x][y] = 1
                        wb1 = "黑棋"
                        wb = "white"
                    elif wb == "white":
                        alist[x][y] = 2
                        wb1 = "白棋"
                        wb = "black"
                    xx = x
                    yy = y
                    while True:
                        if xx == 0:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            xx += 1
                            break
                        else:
                            xx -= 1
                    num = 0
                    while True:
                        if xx == 18:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            break
                        else:
                            xx += 1
                            num += 1
                    if num >= 5:
                        pygame.font.init()
                        text = font1.render("赢了".format(wb1), True, (0, 0, 0))
                        textRect = text.get_rect()
                        textRect.center = (307.5, 307.5)
                        screen.blit(text, textRect)
                        pygame.display.flip()
                        while True:
                            for event in pygame.event.get():
                                if event.type == pygame.QUIT:
                                    pygame.quit()
                                    sys.exit()
                                if event.type == pygame.MOUSEBUTTONDOWN:
                                    do()
                    xx = x
                    yy = y
                    while True:
                        if yy == 0:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            yy += 1
                            break
                        else:
                            yy -= 1
                    num = 0
                    while True:
                        if yy == 18:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            break
                        else:
                            yy += 1
                            num += 1
                    if num >= 5:
                        pygame.font.init()
                        text = font1.render("赢了".format(wb1), True, (0, 0, 0))
                        textRect = text.get_rect()
                        textRect.center = (307.5, 307.5)
                        screen.blit(text, textRect)
                        pygame.display.flip()
                        while True:
                            for event in pygame.event.get():
                                if event.type == pygame.QUIT:
                                    pygame.quit()
                                    sys.exit()
                                if event.type == pygame.MOUSEBUTTONDOWN:
                                    do()
                    xx = x
                    yy = y
                    while True:
                        if xx == 0:
                            break
                        elif yy == 0:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            xx += 1
                            yy += 1
                            break
                        else:
                            xx -= 1
                            yy -= 1
                    num = 0
                    while True:
                        if xx == 18:
                            break
                        elif yy == 18:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            break
                        else:
                            xx += 1
                            yy += 1
                            num += 1
                    if num >= 5:
                        pygame.font.init()
                        text = font1.render("赢了".format(wb1), True, (0, 0, 0))
                        textRect = text.get_rect()
                        textRect.center = (307.5, 307.5)
                        screen.blit(text, textRect)
                        pygame.display.flip()
                        while True:
                            for event in pygame.event.get():
                                if event.type == pygame.QUIT:
                                    pygame.quit()
                                    sys.exit()
                                if event.type == pygame.MOUSEBUTTONDOWN:
                                    do()
                    xx = x
                    yy = y
                    while True:
                        if xx == 0:
                            break
                        elif yy == 18:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            xx += 1
                            yy -= 1
                            break
                        else:
                            xx -= 1
                            yy += 1
                    num = 0
                    while True:
                        if xx == 18:
                            break
                        elif yy == 0:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            break
                        else:
                            xx += 1
                            yy -= 1
                            num += 1
                    if num >= 5:
                        pygame.font.init()
                        text = font1.render("赢了".format(wb1), True, (0, 0, 0))
                        textRect = text.get_rect()
                        textRect.center = (307.5, 307.5)
                        screen.blit(text, textRect)
                        pygame.display.flip()
                        while True:
                            for event in pygame.event.get():
                                if event.type == pygame.QUIT:
                                    pygame.quit()
                                    sys.exit()
                                if event.type == pygame.MOUSEBUTTONDOWN:
                                    do()
do()

 运行结果:

 显示某方棋子胜利之后,鼠标点击即可刷新棋盘重新开始

 

 以实际效果来看,目前 五子棋小游戏实现(三)实现效果最优

详细参考以下:

基于Python实现五子棋_壹屋安源的博客-CSDN博客_python五子棋

https://www.jb51.net/article/246676.htm

Python双人五子棋 - GodForever - 博客园

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 (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 (1 >= 0 and n + 1 level  and chesspad[1][n + 1] == color):
                    -= 1
                    n += 1
                    shape[i][j][2] += grade
                if 1 >= 0 and n + 1 level  and chesspad[1][n + 1] == 0:
                    shape[i][j][2] += 1
                if 1 >= 0 and n + 1 level  and chesspad[1][n + 1] == -color:
                    shape[i][j][2] -= 2
                m = i
                n = j
                # 如果右上方跟当前传入的颜色参数一致,那么加分到2位!
                while (m + 1 < level  and 1 >= 0 and chesspad[m + 1][n - 1] == color):
                    m += 1
                    n -= 1
                    shape[i][j][2] += grade
                if m + 1 level  and 1 >= 0 and chesspad[m + 1][n - 1] == 0:
                    shape[i][j][2] += 1
                if m + 1 level  and 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 in shape:
        for in i:
            for in range(5):
                for in range(3, 1, -1):
                    if j[1] < j[w]:
                        temp = j[w]
                        j[1] = j[w]
                        j[w] = temp
    print("This Time Sort Done !")
    return shape


def Evaluate(shape):
    for in range(level):
        for 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 in range(15):
        for 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 < or x > level - 1 or y 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 = 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 = 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 = 1, 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, 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            
-= 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]]!=:        
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 in range(level) for                
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 ((25) % 50 <= level or (25) % 50 >= 0) and (                        (y - 25) % 50 
<level or (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实现简易五子棋小游戏(三种方式)的主要内容,如果未能解决你的问题,请参考以下文章

Python实现智能五子棋

Python游戏开发,pygame模块,Python实现五子棋联机对战小游戏

python小游戏 五子棋小游戏设计与实现

Python游戏开发,pygame模块,Python实现乒乓球小游戏

1000行Python代码实现俄罗斯方块/扫雷/五子棋/贪吃蛇

使用pygame实现一个简单的五子棋游戏