广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python实现网络五子棋
  • 565
分享到

python实现网络五子棋

2024-04-02 19:04:59 565人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

本文实例为大家分享了python实现网络五子棋的具体代码,供大家参考,具体内容如下 服务器端: import os import Socket import threading

本文实例为大家分享了python实现网络五子棋的具体代码,供大家参考,具体内容如下

服务器端:


import os
import Socket
import threading

from tkinter import *
from tkinter.messagebox import *


def drawQiPan():
    for i in range(0, 15):
        cv.create_line(20, 20 + 40 * i, 580, 20 + 40 * i, width=2)
    for i in range(0, 15):
        cv.create_line(20 + 40 * i, 20, 20 + 40 * i, 580, width=2)
    cv.pack()


# 走棋函数
def callPos(event):
    global turn
    global MyTurn
    if MyTurn == -1:  # 第一次确认自己的角色
        MyTurn = turn
    else:
        if MyTurn != turn:
            showinfo(title="提示", message="还没轮到自己下棋")
            return
    # print("clicked at",event.x,event.y,true)
    x = event.x // 40
    y = event.y // 40
    print("clicked at", x, y, turn)
    if maps[x][y] != " ":
        showinfo(title="提示", message="已有棋子")
    else:
        img1 = images[turn]
        cv.create_image((x * 40 + 20, y * 40 + 20), image=img1)
        cv.pack()
        maps[x][y] = str(turn)
        pos = str(x) + "," + str(y)
        sendMessage("move|" + pos)
        print("服务器走的位置", pos)
        label1["text"] = "服务器走的位置" + pos
        # 输出输赢信息
        if win_lose():
            if turn == 0:
                showinfo(title="提示", message="黑方你赢了")
                sendMessage("over|黑方你赢了")
            else:
                showinfo(title="提示", message="白方你赢了")
                sendMessage("over|白方你赢了")
        # 换下一方走棋
        if turn == 0:
            turn = 1
        else:
            turn = 0


# 发送消息
def sendMessage(pos):
    global s
    global addr
    s.sendto(pos.encode(), addr)


# 退出函数
def callExit(event):
    pos = "exit|"
    sendMessage(pos)
    os.exit()


# 画对方棋子
def drawOtherChess(x, y):
    global turn
    img1 = images[turn]
    cv.create_image((x * 40 + 20, y * 40 + 20), image=img1)
    cv.pack()
    maps[x][y] = str(turn)
    # 换下一方走棋
    if turn == 0:
        turn = 1
    else:
        turn = 0


# 判断整个棋盘的输赢
def win_lose():
    a = str(turn)
    print("a=", a)
    for i in range(0, 11):
        for j in range(0, 11):
            if maps[i][j] == a and maps[i + 1][j + 1] == a and maps[i + 2][j + 2] == a and maps[i + 3][j + 3] == a and \
                    maps[i + 4][j + 4] == a:
                print("x=y轴上形成五子连珠")
                return True
    for i in range(4, 15):
        for j in range(0, 11):
            if maps[i][j] == a and maps[i - 1][j + 1] == a and maps[i - 2][j + 2] == a and maps[i - 3][j + 3] == a and \
                    maps[i - 4][j + 4] == a:
                print("x=-y轴上形成五子连珠")
                return True
    for i in range(0, 15):
        for j in range(4, 15):
            if maps[i][j] == a and maps[i][j - 1] == a and maps[i][j - 2] == a and maps[i][j - 2] == a and maps[i][
                j - 4] == a:
                print("Y轴上形成了五子连珠")
                return True
    for i in range(0, 11):
        for j in range(0, 15):
            if maps[i][j] == a and maps[i + 1][j] == a and maps[i + 2][j] == a and maps[i + 3][j] == a and maps[i + 4][
                j] == a:
                print("X轴形成五子连珠")
                return True
    return False


# 输出map地图
def print_map():
    for j in range(0, 15):
        for i in range(0, 15):
            print(maps[i][j], end=' ')
        print('w')


# 接受消息
def receiveMessage():
    global s
    while True:  # 接受客户端发送的消息
        global addr
        data, addr = s.recvfrom(1024)
        data = data.decode('utf-8')
        a = data.split("|")
        if not data:
            print('client has exited!')
            break
        elif a[0] == 'join':  # 连接服务器的请求
            print('client 连接服务器!')
            label1["text"] = 'client连接服务器成功,请你走棋!'
        elif a[0] == 'exit':
            print('client对方退出!')
            label1["text"] = 'client对方退出,游戏结束!'
        elif a[0] == 'over':
            print('对方赢信息!')
            label1["text"] = data.split("|")[0]
            showinfo(title="提示", message=data.split("1")[1])
        elif a[0] == 'move':
            print('received:', data, 'from', addr)
            p = a[1].split(",")
            x = int(p[0])
            y = int(p[1])
            print(p[0], p[1])
            label1["text"] = "客户端走的位置" + p[0] + p[1]
            drawOtherChess(x, y)
    s.close()


def startNewThread():  # 启动新线程来接受客户端消息
    thread = threading.Thread(target=receiveMessage, args=())
    thread.setDaemon(True)
    thread.start()


if __name__ == '__main__':
    root = Tk()
    root.title("网络五子棋v2.0-服务器端")
    images = [PhotoImage(file='./images/BlackStone.png'), PhotoImage(file='./images/WhiteStone.png')]
    turn = 0
    MyTurn = -1
    maps = [[" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "] for y in range(15)]
    cv = canvas(root, bg='green', width=610, height=610)
    drawQiPan()
    cv.bind("<Button-1>", callPos)
    cv.pack()
    label1 = Label(root, text="服务器端...")
    label1.pack()
    button1 = Button(root, text="退出游戏")
    button1.bind("<Button-1>", callExit)
    button1.pack()
    # 创建UDP SOCKET
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind(('localhost', 8000))
    addr = ('localhost', 8000)
    startNewThread()
    root.mainloop()

客户端:


from tkinter import *
from tkinter.messagebox import *
import socket
import threading
import os

# 主程序
root = Tk()
root.title("网络五子棋v2.0--UDP客户端")
imgs = [PhotoImage(file='./images/BlackStone.png'), PhotoImage(file='./images/WhiteStone.png')]
turn = 0
MyTurn = -1


# 画对方棋子
def drawOtherChess(x, y):
    global turn
    img1 = imgs[turn]
    cv.create_image((x * 40 + 20, y * 40 + 20), image=img1)
    cv.pack()
    maps[x][y] = str(turn)
    # 换下一方走棋
    if turn == 0:
        turn = 1
    else:
        turn = 0


# 发送消息
def sendMessage(position):
    global s
    s.sendto(position.encode(), (host, port))


# 退出函数
def callExit(event):
    position = "exit|"
    sendMessage(position)
    os.exit()


# 走棋函数
def callback(event):
    global turn
    global MyTurn
    if MyTurn == -1:
        MyTurn = turn
    else:
        if MyTurn != turn:
            showinfo(title="提示", message="还没轮到自己走棋")
            return
    # print("clicked at",event.x,event.y)
    x = event.x // 40
    y = event.y // 40
    print("clicked at", x, y, turn)
    if maps[x][y] != " ":
        showinfo(title="提示", message="已有棋子")
    else:
        img1 = imgs[turn]
        cv.create_image((x * 40 + 20, y * 40 + 20), image=img1)
        cv.pack()
        maps[x][y] = str(turn)
        position = str(x) + ',' + str(y)
        sendMessage("move|" + position)
        print("客户端走的位置", position)
        label1["text"] = "客户端走的位置" + position
        # 输出输赢信息
        if win_lose():
            if turn == 0:
                showinfo(title="提示", message="黑方你赢了")
                sendMessage("over|黑方你赢了!")
            else:
                showinfo(title="提示", message="白方你赢了!")
                sendMessage("over|白方你赢了!")
        # 换下一方走棋:
        if turn == 0:
            turn = 1
        else:
            turn = 0


# 画棋盘
def drawQiPan():  # 画棋盘
    for i in range(0, 15):
        cv.create_line(20, 20 + 40 * i, 580, 20 + 40 * i, width=2)
    for i in range(0, 15):
        cv.create_line(20 + 40 * i, 20, 20 + 40 * i, 580, width=2)
    cv.pack()


# 输赢判断
def win_lose():
    a = str(turn)
    print("a=", a)
    for i in range(0, 11):
        for j in range(0, 11):
            if maps[i][j] == a and maps[i + 1][j + 1] == a and maps[i + 2][j + 2] == a and maps[i + 3][j + 3] == a and \
                    maps[i + 4][j + 4] == a:
                print("x=y轴上形成五子连珠")
                return True
    for i in range(4, 15):
        for j in range(0, 11):
            if maps[i][j] == a and maps[i - 1][j + 1] == a and maps[i - 2][j + 2] == a and maps[i - 3][j + 3] == a and \
                    maps[i - 4][j + 4] == a:
                print("x=-y轴上形成五子连珠")
                return True
    for i in range(0, 15):
        for j in range(4, 15):
            if maps[i][j] == a and maps[i][j - 1] == a and maps[i][j - 2] == a and maps[i][j - 2] == a and maps[i][
                j - 4] == a:
                print("Y轴上形成了五子连珠")
                return True
    for i in range(0, 11):
        for j in range(0, 15):
            if maps[i][j] == a and maps[i + 1][j] == a and maps[i + 2][j] == a and maps[i + 3][j] == a and maps[i + 4][
                j] == a:
                print("X轴形成五子连珠")
                return True
    return False


# 接受消息
def receiveMessage():  # 接受消息
    global s
    while True:
        data = s.recv(1024).decode('utf-8')
        a = data.split("|")
        if not data:
            print('server has exited!')
            break
        elif a[0] == 'exit':
            print('对方退出!')
            label1["text"] = '对方退出!游戏结束!'
        elif a[0] == 'over':
            print('对方赢信息!')
            label1["text"] = data.split("|")[0]
            showinfo(title="提示", message=data.split("|")[1])
        elif a[0] == 'move':
            print('received:', data)
            p = a[1].split(",")
            x = int(p[0])
            y = int(p[1])
            print(p[0], p[1])
            label1["text"] = "服务器走的位置" + p[0] + p[1]
            drawOtherChess(x, y)
    s.close()


# 启动线程接受客户端消息
def startNewThread():
    thread = threading.Thread(target=receiveMessage, args=())
    thread.setDaemon(True)
    thread.start()


if __name__ == '__main__':
    # 主程序
    maps = [[" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "] for y in range(15)]
    cv = Canvas(root, bg='green', width=610, height=610)
    drawQiPan()
    cv.bind("<Button-1>", callback)
    cv.pack()
    label1 = Label(root, text="客户端...")
    label1.pack()
    button1 = Button(root, text="退出游戏")
    button1.bind("<Button-1>", callExit)
    button1.pack()
    # 创建UDP
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    port = 8000
    host = 'localhost'
    pos = 'join|'
    sendMessage(pos)
    startNewThread()
    root.mainloop()

游戏执行页面:

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

--结束END--

本文标题: python实现网络五子棋

本文链接: https://www.lsjlt.com/news/123301.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python实现网络五子棋
    本文实例为大家分享了python实现网络五子棋的具体代码,供大家参考,具体内容如下 服务器端: import os import socket import threading ...
    99+
    2022-11-12
  • python实现网络五子棋的方法
    这篇文章主要介绍了python实现网络五子棋的方法,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。具体内容如下服务器端:import osimport so...
    99+
    2023-06-14
  • python实现五子棋算法
    python五子棋原创算法,供大家参考,具体内容如下 我们都见过五子棋,但是在我看来五子棋单机游戏中,逻辑赢法很重要,经常用到的算法是五子连珠算法,但是很多五子连珠算法很不全面,不是...
    99+
    2022-11-10
  • 用python实现五子棋实例
    本文实例为大家分享了用python实现五子棋的具体代码,供大家参考,具体内容如下 # 制作一个棋盘 """ ++++++++++ ++++++++++ ++++++++++ ++++...
    99+
    2022-11-10
  • js+html实现网页五子棋
    本文实例为大家分享了js+html实现网页五子棋的具体代码,供大家参考,具体内容如下 最终效果图: 废话不多说,上源码: <!doctype html> <ht...
    99+
    2022-11-13
  • 怎么用python实现五子棋
    本篇内容介绍了“怎么用python实现五子棋”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!具体代码如下# 制作一个棋盘"...
    99+
    2023-06-30
  • 基于Python实现五子棋游戏
    本文实例为大家分享了Python实现五子棋游戏的具体代码,供大家参考,具体内容如下 了解游戏的规则是我们首先需要做的事情,如果不知晓规则,那么我们肯定寸步难行。 五子棋游戏规则: 1...
    99+
    2022-11-10
  • python代码实现五子棋游戏
    本文实例为大家分享了python实现五子棋游戏的具体代码,供大家参考,具体内容如下 先上代码  #调用pygame库 import pygame import sys #调...
    99+
    2022-11-10
  • Python实现双人五子棋对局
    本文实例为大家分享了Python实现双人五子棋对局的具体代码,供大家参考,具体内容如下 效果: 自己需要两个棋子: 服务器玩家全部代码: # 案列使用TCP连接 # 这是服务器端...
    99+
    2022-11-10
  • python实现五子棋双人对弈
    本文实例为大家分享了python实现五子棋双人对弈的具体代码,供大家参考,具体内容如下 我用的是pygame模块来制作窗口 代码如下: # 1、引入pygame 和 pygame.l...
    99+
    2022-11-10
  • Python实现简易五子棋游戏
    本文实例为大家分享了Python实现五子棋游戏的具体代码,供大家参考,具体内容如下 class CheckerBoard():     '''棋盘类'''     def __ini...
    99+
    2022-11-10
  • python怎么实现五子棋算法
    本文小编为大家详细介绍“python怎么实现五子棋算法”,内容详细,步骤清晰,细节处理妥当,希望这篇“python怎么实现五子棋算法”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。if (j+4<n...
    99+
    2023-06-30
  • JavaScript实现网页版五子棋游戏
    本文实例为大家分享了JavaScript实现网页版五子棋游戏的具体代码,供大家参考,具体内容如下 学习js的第三天,跟着老师完成的五子棋小游戏,记录学习成果欢迎大佬们一起分享经验,批...
    99+
    2022-11-12
  • js实现网页五子棋进阶版
    本文实例为大家分享了js实现网页五子棋进阶版的具体代码,供大家参考,具体内容如下 对比上一版本增加了音效和计时器两个模块。 代码如下 <!doctype html> &...
    99+
    2022-11-13
  • JavaScript实现网页五子棋小游戏
    本文实例为大家分享了JavaScript实现网页五子棋小游戏的具体代码,供大家参考,具体内容如下 设计思路如下: 1.先采用的Math.random()方法决定哪一方先行; 2.设置...
    99+
    2022-11-13
  • python pygame实现五子棋双人联机
    本文实例为大家分享了python pygame实现五子棋双人联机的具体代码,供大家参考,具体内容如下 同一局域网内,服务端开启时,另一机器将IP地址HOST改为服务端对应的IP地址、...
    99+
    2022-11-10
  • python实现简单五子棋小游戏
    用python实现五子棋简单人机模式的练习过程,供大家参考,具体内容如下 最近在初学python,今天就用自己的一些粗浅理解,来记录一下这几天的python简单人机五子棋游戏的练习,...
    99+
    2022-11-11
  • Python+Pygame实现彩色五子棋游戏
    目录项目简介项目背后的故事项目扩展思路运行截图安装依赖运行游戏项目简介 之前学python的时候 写了个游戏来练手 用的是 pygame 没有别的依赖 只用了一两百行的代码就实现了 ...
    99+
    2023-02-10
    Python Pygame彩色五子棋游戏 Python Pygame五子棋游戏 Python Pygame 游戏
  • Java实现五子棋游戏
    本文实例为大家分享了Java实现五子棋游戏的具体代码,供大家参考,具体内容如下 一、功能分析 五子棋的实现还是较为简单的,通过下期的流程我们可以知道大概要实现一下功能: 1、格界面 ...
    99+
    2022-11-12
  • java实现五子棋大战
    本文实例为大家分享了java实现五子棋大战的具体代码,供大家参考,具体内容如下 这是我接近一年前的项目了,以前没有养成写博客的习惯,打算陆续把以前做过的项目补上来。 一、介绍 主要实...
    99+
    2022-11-13
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作