python实现网络五子棋


Posted in Python onApril 11, 2021

本文实例为大家分享了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()

游戏执行页面:

python实现网络五子棋

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

Python 相关文章推荐
python实现的解析crontab配置文件代码
Jun 30 Python
python使用MySQLdb访问mysql数据库的方法
Aug 03 Python
python实现黑客字幕雨效果
Jun 21 Python
python爬虫的数据库连接问题【推荐】
Jun 25 Python
Python实现聊天机器人的示例代码
Jul 09 Python
在Python中关于使用os模块遍历目录的实现方法
Jan 03 Python
Python向excel中写入数据的方法
May 05 Python
pyqt 实现在Widgets中显示图片和文字的方法
Jun 13 Python
Python数据可视化 pyecharts实现各种统计图表过程详解
Aug 15 Python
python防止随意修改类属性的实现方法
Aug 21 Python
详细介绍python类及类的用法
May 31 Python
pandas时间序列之pd.to_datetime()的实现
Jun 16 Python
python实现简易名片管理系统
Apr 11 #Python
python 自动化偷懒的四个实用操作
python Tkinter的简单入门教程
PyQt5 显示超清高分辨率图片的方法
用Python提取PDF表格的方法
用Python提取PDF表格的方法
python实现自动化群控的步骤
Apr 11 #Python
You might like
DC四月将推出百页特刊漫画 纪念小丑诞生80周年
2020/04/09 欧美动漫
php在线打包程序源码
2008/07/27 PHP
PHP array_multisort()函数的使用札记
2011/07/03 PHP
基于php上传图片重命名的6种解决方法的详细介绍
2013/04/28 PHP
浅析php中如何在有限的内存中读取大文件
2013/07/02 PHP
PHP读取mssql json数据中文乱码的解决办法
2016/04/11 PHP
php实现的二分查找算法示例
2017/06/20 PHP
laravel5.4利用163邮箱发送邮件的步骤详解
2017/09/22 PHP
laravel框架 laravel-admin上传图片到oss的方法
2019/10/13 PHP
网页源代码保护(禁止右键、复制、另存为、查看源文件)
2012/05/23 Javascript
require.js的用法详解
2015/10/20 Javascript
jQuery validate插件功能与用法详解
2016/12/15 Javascript
Node.JS中事件轮询(Event Loop)的解析
2017/02/25 Javascript
移动端刮刮乐的实现方式(js+HTML5)
2017/03/23 Javascript
canvas绘制一个常用的emoji表情
2017/03/30 Javascript
js字符串与Unicode编码互相转换
2017/05/17 Javascript
使用javaScript实现鼠标拖拽事件
2020/04/03 Javascript
js实现控制文件拖拽并获取拖拽内容功能
2018/02/17 Javascript
Vue数字输入框组件使用方法详解
2020/02/10 Javascript
python中精确输出JSON浮点数的方法
2014/04/18 Python
使用Python中的线程进行网络编程的入门教程
2015/04/15 Python
python输出当前目录下index.html文件路径的方法
2015/04/28 Python
Python编写生成验证码的脚本的教程
2015/05/04 Python
python使用MySQLdb访问mysql数据库的方法
2015/08/03 Python
python爬虫获取淘宝天猫商品详细参数
2020/06/23 Python
python交换两个变量的值方法
2019/01/12 Python
解决pycharm运行程序出现卡住scanning files to index索引的问题
2019/06/27 Python
Python高并发解决方案实现过程详解
2020/07/31 Python
Lulu & Georgia官方网站:购买地毯、家具、抱枕、壁纸、床上用品等
2018/03/19 全球购物
顶丰TOPPIK台湾官网:增发纤维假发,告别秃发困扰
2018/06/13 全球购物
英国在线定制百叶窗网站:Swift Direct Blinds
2020/02/25 全球购物
PHP如何自定义函数
2016/09/16 面试题
剪枝的学问教学反思
2014/02/07 职场文书
青春演讲稿范文
2014/05/08 职场文书
心理咨询承诺书
2014/05/20 职场文书
2014和解协议书范文
2014/09/15 职场文书