Python五子棋小游戏实例分享

 更新时间:2021年09月06日 15:30:23   作者:Maggie晨曦  
这篇文章主要为大家详细介绍了Python五子棋小游戏实例,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Python实现五子棋小游戏的具体代码,供大家参考,具体内容如下

使用的库

pygame、pyautogui

流程简述

1.画棋盘

设置网格间隔40px ,留白 80 px ,与网格横竖线数量 ,初定19 × 19 。

2.鼠标点击

鼠标点击取得坐坐标(x0 , y0),再获得最近的网格上的点(x1 , y1),再将每次动作获得的(x1 , y1 )放入列表 chess_location 中。

再通过:

chess_location_b = chess_location[0::2]
chess_location_w = chess_location[1::2]

分别获得黑棋和白棋所走过的坐标。

3.判断胜负

这一块网上有很多不同的方法,我为了让大家读懂尽量写的详细了。
首先 ,我们要知道连五有四个方向:竖直 ,水平 ,右上左下 , 右下左上 。
每次将新落下的子分别进行4个方向的判断,判断是否出现连五及以上。
我使用的方法是:

def result(x): # x 为 chess_location_b 或者 chess_location_w
    # 竖直
    score = []
    for i in range(cell_num): #cell_num = 19
        if [x[-1][0], i ] in x:
            score.append([x[-1][0], i ])
            if score.__len__() >= 5:
                return 1
        else:
            score =[]

大概意思就是最新落下的(x1 , y1)中的竖直方向从上往下检查如果出现黑(白)棋 ,则将出现棋子的坐标加入列表 score 中 , 如果出现异色棋子或者没有棋子,则清空 score 中的元素 ,如果列表 score 中的元素数量大于等于5个 ,则分胜负 。
如果棋子填满棋盘但是仍没有分出胜负 ,则平局 。

代码及结果

代码

import pygame,pyautogui
from pygame.locals import *
# 初始参数
cell_size = 40
space = 80
cell_num = 19
grid_size = (cell_num - 1)*cell_size + space*2
screen = pygame.display.set_mode([grid_size,grid_size],0,32)
chess_location , chess_location_w , chess_location_b = [] , [] , []
# 画棋盘
def grid():
    screen.fill([208,173,108])
    font = pygame.font.SysFont("arial", 20)
    i = 0
    for x in range(0, cell_size * cell_num , cell_size):
        i += 1
        text_surface = font.render("{}".format(i), True, (0, 0, 0))
        screen.blit(text_surface,[(space - font.get_height()) - 10,(space - font.get_height()/2) + cell_size*(i -1 )])
        pygame.draw.line(screen, (0, 0, 0), (x + space, 0 + space), (x + space, cell_size * (cell_num - 1) + space), 2)
    i = 0
    for y in range(0, cell_size * cell_num, cell_size):
        i += 1
        text_surface = font.render("{}".format(chr(64 + i)), True, (0, 0, 0))
        screen.blit(text_surface,[(space + cell_size * (i - 1)) -5, (space - font.get_height() / 2) - 20])
        pygame.draw.line(screen, (0,0,0), (0 + space, y + space),(cell_size * (cell_num - 1) + space, y + space), 2)
# 分胜负
def result(x):
    # 竖直
    score = []
    for i in range(cell_num):
        if [x[-1][0], i ] in x:
            score.append([x[-1][0], i ])
            if score.__len__() >= 5:
                return 1
        else:
            score =[]
    # 水平
    score = []
    for i in range(cell_num):
        if [i , x[-1][1]] in x:
            score.append([i , x[-1][1]])
            if score.__len__() >= 5:
                return 1
        else:
            score = []
    # 右上左下
    score = []
    for i in range(cell_num):
        if [i,x[-1][0] + x[-1][1] - i] in x:
            score.append([i,x[-1][0] + x[-1][1] - i])
            if score.__len__() >= 5:
                return 1
        else:
            score = []
    # 右下左上
    score = []
    for i in range(cell_num):
        if [x[-1][0] - x[-1][1] + i,i] in x:
            score.append([x[-1][0] - x[-1][1] + i,i])
            if score.__len__() >= 5:
                return 1
        else:
            score = []
    # 平局
    if chess_location.__len__() == cell_num * cell_num :
        return 2
# 主循环
def running():
    global chess_location_w , chess_location_b
    while True:
        grid()
        for event in pygame.event.get():
            if event.type == QUIT:
                exit()
            # 落子
            if event.type == MOUSEBUTTONDOWN:
                x0 , y0 = pygame.mouse.get_pos()
                if x0 > space and y0 > space and x0 < space + cell_size*(cell_num - 1) and y0 < space + cell_size * (cell_num - 1):
                    x1 = round((x0 - space) / cell_size)
                    y1 = round((y0 - space) / cell_size)
                    if [x1 , y1] not in chess_location:
                        chess_location.append([x1 , y1])
            # 悔棋
            elif event.type == KEYDOWN:
                if event.key == K_LEFT:
                    chess_location.pop(-1)
        chess_location_b = chess_location[0::2]
        chess_location_w = chess_location[1::2]
        # 黑棋
        for i in chess_location_b:
            pygame.draw.circle(screen, [ 0 , 0 , 0 ], [i[0]* cell_size + space, i[1]* cell_size + space], 15, 0)
        # 白棋
        for i in chess_location_w:
            pygame.draw.circle(screen, [255,255,255], [i[0]* cell_size + space, i[1]* cell_size + space], 15, 0)
        # 判断胜负
        if chess_location_b and result(chess_location_b) == 1:
            pyautogui.alert(text='黑棋胜',title='游戏结束')
            exit()
        elif chess_location_w and result(chess_location_w) == 1:
            pyautogui.alert(text='白棋胜',title='游戏结束')
            exit()
        elif chess_location_b and chess_location_w:
            if result(chess_location_b) or result(chess_location_w) == 2:
                pyautogui.alert(text='平局', title='游戏结束')
                exit()
        pygame.display.update()


if __name__ == '__main__':
    pygame.init()
    running()

输出

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • 浅谈Python中函数的参数传递

    浅谈Python中函数的参数传递

    下面小编就为大家带来一篇浅谈Python中函数的参数传递。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-06-06
  • 详解Python如何生成词云的方法

    详解Python如何生成词云的方法

    这篇文章主要介绍了详解Python如何生成词云的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-06-06
  • 一文详解NumPy数组迭代与合并

    一文详解NumPy数组迭代与合并

    NumPy 数组迭代是访问和处理数组元素的重要方法,它允许您逐个或成组地遍历数组元素,NumPy 提供了多种函数来合并数组,用于将多个数组的内容连接成一个新数组,本文给大家详细介绍了NumPy数组迭代与合并,需要的朋友可以参考下
    2024-05-05
  • Python Matplotlib基本用法详解

    Python Matplotlib基本用法详解

    Matplotlib 是Python中类似 MATLAB 的绘图工具,熟悉 MATLAB 也可以很快的上手 Matplotlib,这篇文章主要介绍了Python Matplotlib基本用法,需要的朋友可以参考下
    2023-03-03
  • Python内置函数locals和globals对比

    Python内置函数locals和globals对比

    这篇文章主要介绍了Python内置函数locals和globals对比,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-04-04
  • Python深度学习pytorch神经网络图像卷积运算详解

    Python深度学习pytorch神经网络图像卷积运算详解

    这篇文章主要介绍了Python深度学习关于pytorch神经网络图像卷积的运算示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助
    2021-10-10
  • python实现windows壁纸定期更换功能

    python实现windows壁纸定期更换功能

    这篇文章主要为大家详细介绍了python实现windows壁纸定期更换功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-01-01
  • Python IndexError报错分析及解决方法

    Python IndexError报错分析及解决方法

    在Python编程中,IndexError是一种常见的异常类型,它通常发生在尝试访问序列(如列表、元组或字符串)中不存在的索引时,本文将深入分析IndexError的成因、表现形式,并提供相应的解决办法,同时附带详细的代码示例,需要的朋友可以参考下
    2024-07-07
  • 浅谈python 四种数值类型(int,long,float,complex)

    浅谈python 四种数值类型(int,long,float,complex)

    下面小编就为大家带来一篇浅谈python 四种数值类型(int,long,float,complex)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-06-06
  • Python 如何实时向文件写入数据(附代码)

    Python 如何实时向文件写入数据(附代码)

    这篇文章主要介绍了Python 如何实时向文件写入数据(附代码),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-07-07

最新评论