python+pygame实现简易五子棋小游戏的三种方式

Python
298
0
0
2023-09-06
标签   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("五子棋游戏")                  #窗口名字
w = Canvas(root, width=600,height=600,background='chocolate')
w.pack()
 
for i in range(, 15):
    w.create_line(i * 40 + 20, 20, i * 40 + 20, 580)
    w.create_line(20, i * 40 + 20, 580, i * 40 + 20)
w.create_oval(135, 135, 145, 145,fill='black')
w.create_oval(135, 455, 145, 465,fill='black')
w.create_oval(465, 135, 455, 145,fill='black')
w.create_oval(455, 455, 465, 465,fill='black')
w.create_oval(295, 295, 305, 305,fill='black')
 
num=
A=np.full((,15),0)
B=np.full((,15),'')
def callback(event):
    global num ,A
    for j in range (,15):
        for i in range (,15):
            if (event.x - - 40 * i) ** 2 + (event.y - 20 - 40 * j) ** 2 <= 2 * 20 ** 2:
                break
        if (event.x - - 40 * i) ** 2 + (event.y - 20 - 40 * j) ** 2 <= 2*20 ** 2:
            break
    if num % == 0 and A[i][j] != 1:
        w.create_oval(40*i+5, 40*j+5, 40*i+35, 40*j+35,fill='black')
        A[i][j] =
        B[i][j] = 'b'
        num +=
    if num % != 0 and A[i][j] != 1 :
        w.create_oval(40*i+5, 40*j+5, 40*i+35, 40*j+35,fill='white')
        A[i][j] =.
        B[i][j] = 'w'
        num +=
 
    f = [[-, 0], [-1, 1], [0, 1], [1, 1]]
    for z in range(, 4):
        a, b = f[z][], f[z][1]
        count, count2 = 0, 0
        x, y = i, j
        while B[x][y] == B[i][j]:
            count += 1
            if x + a >= 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]:
            count += 1
            if x - a < 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 count + count2 == 6:
            if B[i][j] == 'b':
                tkinter.messagebox.showinfo('提示', '黑棋获胜')
            else:
                tkinter.messagebox.showinfo('提示', '白棋获胜')
 
w.bind("<Button -1>",callback)
w.pack()
def quit():
    root.quit()
 
u=Button(root,text="退出",width=,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
#窗口大小为x670
screen = pygame.display.set_mode((,670))
screen_color=[,154,73]#设置画布颜色,[238,154,73]对应为棕黄色
line_color = [,0,0]#设置线条颜色,[0,0,0]对应黑色
  
def check_win(over_pos):#判断五子连心
    mp=np.zeros([,15],dtype=int)
    for val in over_pos:
        x=int((val[][0]-27)/44)
        y=int((val[][1]-27)/44)
        if val[]==white_color:
            mp[x][y]=#表示白子
        else:
            mp[x][y]=#表示黑子
  
    for i in range():
        pos=[]
        pos=[]
        for j in range():
            if mp[i][j]==:
                pos.append([i,j])
            else:
                pos=[]
            if mp[i][j]==:
                pos.append([i,j])
            else:
                pos=[]
            if len(pos)>=5:#五子连心
                return [,pos1]
            if len(pos)>=5:
                return [,pos2]
  
    for j in range():
        pos=[]
        pos=[]
        for i in range():
            if mp[i][j]==:
                pos.append([i,j])
            else:
                pos=[]
            if mp[i][j]==:
                pos.append([i,j])
            else:
                pos=[]
            if len(pos)>=5:
                return [,pos1]
            if len(pos)>=5:
                return [,pos2]
    for i in range():
        for j in range():
            pos=[]
            pos=[]
            for k in range():
                if i+k>= or j+k>=15:
                    break
                if mp[i+k][j+k]==:
                    pos.append([i+k,j+k])
                else:
                    pos=[]
                if mp[i+k][j+k]==:
                    pos.append([i+k,j+k])
                else:
                    pos=[]
                if len(pos)>=5:
                    return [,pos1]
                if len(pos)>=5:
                    return [,pos2]
    for i in range():
        for j in range():
            pos=[]
            pos=[]
            for k in range():
                if i+k>= or j-k<0:
                    break
                if mp[i+k][j-k]==:
                    pos.append([i+k,j-k])
                else:
                    pos=[]
                if mp[i+k][j-k]==:
                    pos.append([i+k,j-k])
                else:
                    pos=[]
                if len(pos)>=5:
                    return [,pos1]
                if len(pos)>=5:
                    return [,pos2]
    return [,[]]
  
def find_pos(x,y):#找到显示的可以落子的位置
    for i in range(,670,44):
        for j in range(,670,44):
            L=i-22
            L=i+22
            R=j-22
            R=j+22
            if x>=L 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]==x and val[0][1]==y:
            return False
    return True#表示没有落子
flag=False
tim=
  
over_pos=[]#表示已经落子的位置
white_color=[,255,255]#白棋颜色
black_color=[,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(,670,44):
        #先画竖线
        if i== or i==670-27:#边缘线稍微粗一些
            pygame.draw.line(screen,line_color,[i,],[i,670-27],4)
        else:
            pygame.draw.line(screen,line_color,[i,],[i,670-27],2)
        #再画横线
        if i== or i==670-27:#边缘线稍微粗一些
            pygame.draw.line(screen,line_color,[,i],[670-27,i],4)
        else:
            pygame.draw.line(screen,line_color,[,i],[670-27,i],2)
  
    #在棋盘中心画个小圆表示正中心位置
    pygame.draw.circle(screen, line_color,[+44*7,27+44*7], 8,0)
  
    for val in over_pos:#显示所有落下的棋子
        pygame.draw.circle(screen, val[],val[0], 20,0)
  
    #判断是否存在五子连心
    res=check_win(over_pos)
    if res[]!=0:
        for pos in res[]:
            pygame.draw.rect(screen,[,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,[ ,229 ,238 ],[x-22,y-22,44,44],2,1)
  
    keys_pressed = pygame.mouse.get_pressed()#获取鼠标按键信息
    #鼠标左键表示落子,tim用来延时的,因为每次循环时间间隔很断,容易导致明明只按了一次左键,却被多次获取,认为我按了多次
    if keys_pressed[] and tim==0:
        flag=True
        if check_over_pos(x,y,over_pos):#判断是否可以落子,再落子
            if len(over_pos)%==0:#黑子
                over_pos.append([[x,y],black_color])
            else:
                over_pos.append([[x,y],white_color])
  
    #鼠标左键延时作用
    if flag:
        tim+=
    if tim%==0:#延时200ms
        flag=False
        tim=
  
    pygame.display.update()#刷新显示

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

运行结果:

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

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

同样依赖于Pygame库

#coding:utf-
import sys
import pygame
import random
def do():
    def black(x, y):
        a =
        b =
        c =
        d =
        for i in range():
            pygame.draw.circle(screen, (a, b, c), [.5 + 32 * x, 19.5 + 32 * y], (10/(d-5)+10)*1.6)
            a +=
            b +=
            c +=
            d +=.08
        pygame.display.update()
 
    def white(x, y):
        a =
        b =
        c =
        d =
        for i in range():
            pygame.draw.circle(screen, (a, b, c), [.5 + 32 * x, 19.5 + 32 * y], (10/(d-5)+10)*1.6)
            a +=
            b +=
            c +=
            d +=.08
        pygame.display.update()
    pygame.init()
    screen = pygame.display.set_mode((, 615))
    pygame.display.set_caption('五子棋')
    screen.fill("#DDF")
    a = pygame.Surface((, 603), flags=pygame.HWSURFACE)
    a.fill(color='#')
    b = pygame.Surface((, 585), flags=pygame.HWSURFACE)
    b.fill(color="#DDF")
    c = pygame.Surface((, 579), flags=pygame.HWSURFACE)
    c.fill(color='#')
    d = pygame.Surface((, 576), flags=pygame.HWSURFACE)
    d.fill(color="#DDF")
    e = pygame.Surface((, 31), flags=pygame.HWSURFACE)
    e.fill(color="#DDF")
    screen.blit(a, (.5, 6.5))
    screen.blit(b, (, 15))
    screen.blit(c, (, 18))
    for j in range():
        for i in range():
            screen.blit(e, ( + 32 * i, 20 + 32 * j))
    alist = []
    for j in range():
        alistone = []
        for i in range():
            alistone.append()
        alist.append(alistone)
    pygame.draw.circle(screen, '#', [307.5, 307.5], 5)
    pygame.draw.circle(screen, '#', [115.5, 307.5], 5)
    pygame.draw.circle(screen, '#', [499.5, 307.5], 5)
    pygame.draw.circle(screen, '#', [115.5, 499.5], 5)
    pygame.draw.circle(screen, '#', [499.5, 499.5], 5)
    pygame.draw.circle(screen, '#', [115.5, 115.5], 5)
    pygame.draw.circle(screen, '#', [499.5, 115.5], 5)
    pygame.draw.circle(screen, '#', [307.5, 499.5], 5)
    pygame.draw.circle(screen, '#', [307.5, 115.5], 5)
    pygame.display.flip()
    wb = "black"
    font = 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 -.5) / 32)
                y = round((y -.5) / 32)
                if x <:
                    x =
                if x >:
                    x =
                if y <:
                    y =
                if y >:
                    y =
                z = False
                if alist[x][y] ==:
                    eval(wb + "({},{})".format(x, y))
                    if wb == "black":
                        alist[x][y] =
                        wb = "黑棋"
                        wb = "white"
                    elif wb == "white":
                        alist[x][y] =
                        wb = "白棋"
                        wb = "black"
                    xx = x
                    yy = y
                    while True:
                        if xx ==:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            xx +=
                            break
                        else:
                            xx -=
                    num =
                    while True:
                        if xx ==:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            break
                        else:
                            xx +=
                            num +=
                    if num >=:
                        pygame.font.init()
                        text = font.render("{}赢了".format(wb1), True, (0, 0, 0))
                        textRect = text.get_rect()
                        textRect.center = (.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 ==:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            yy +=
                            break
                        else:
                            yy -=
                    num =
                    while True:
                        if yy ==:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            break
                        else:
                            yy +=
                            num +=
                    if num >=:
                        pygame.font.init()
                        text = font.render("{}赢了".format(wb1), True, (0, 0, 0))
                        textRect = text.get_rect()
                        textRect.center = (.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 ==:
                            break
                        elif yy ==:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            xx +=
                            yy +=
                            break
                        else:
                            xx -=
                            yy -=
                    num =
                    while True:
                        if xx ==:
                            break
                        elif yy ==:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            break
                        else:
                            xx +=
                            yy +=
                            num +=
                    if num >=:
                        pygame.font.init()
                        text = font.render("{}赢了".format(wb1), True, (0, 0, 0))
                        textRect = text.get_rect()
                        textRect.center = (.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 ==:
                            break
                        elif yy ==:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            xx +=
                            yy -=
                            break
                        else:
                            xx -=
                            yy +=
                    num =
                    while True:
                        if xx ==:
                            break
                        elif yy ==:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            break
                        else:
                            xx +=
                            yy -=
                            num +=
                    if num >=:
                        pygame.font.init()
                        text = font.render("{}赢了".format(wb1), True, (0, 0, 0))
                        textRect = text.get_rect()
                        textRect.center = (.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()

 运行结果:

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

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