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类参数self使用示例
Feb 17 Python
python numpy和list查询其中某个数的个数及定位方法
Jun 27 Python
python实现简易数码时钟
Feb 19 Python
python 实现将文件或文件夹用相对路径打包为 tar.gz 文件的方法
Jun 10 Python
Python 线程池用法简单示例
Oct 02 Python
Django restframework 框架认证、权限、限流用法示例
Dec 21 Python
python3.8.1+selenium实现登录滑块验证功能
May 22 Python
python使用自定义钉钉机器人的示例代码
Jun 24 Python
Django crontab定时任务模块操作方法解析
Sep 10 Python
python图片合成的示例
Nov 09 Python
Python获取江苏疫情实时数据及爬虫分析
Aug 02 Python
python 使用tkinter与messagebox写界面和弹窗
Mar 20 Python
python实现简易名片管理系统
Apr 11 #Python
python 自动化偷懒的四个实用操作
python Tkinter的简单入门教程
PyQt5 显示超清高分辨率图片的方法
用Python提取PDF表格的方法
用Python提取PDF表格的方法
python实现自动化群控的步骤
Apr 11 #Python
You might like
关于crontab的使用详解
2013/06/24 PHP
Codeigniter操作数据库表的优化写法总结
2014/06/12 PHP
PHP图片处理之使用imagecopyresampled函数裁剪图片例子
2014/11/19 PHP
php数组分页实现方法
2016/04/30 PHP
关于Aptana Studio生成自动备份文件的解决办法
2009/12/23 Javascript
第一个JavaScript入门基础 document.write输出
2010/02/22 Javascript
javascript 事件处理程序介绍
2012/06/27 Javascript
JS控件的生命周期介绍
2012/10/22 Javascript
jQuery登陆判断简单实现代码
2013/04/21 Javascript
jquery根据属性和index来查找属性值并操作
2014/07/25 Javascript
JSON格式化输出
2014/11/10 Javascript
jQuery的css()方法用法实例
2014/12/24 Javascript
JS获取一个未知DIV高度的方法
2016/08/09 Javascript
详解Vue中过度动画效果应用
2017/05/25 Javascript
vue全局自定义指令-元素拖拽的实现代码
2019/04/14 Javascript
node Buffer缓存区常见操作示例
2019/05/04 Javascript
微信小程序tabBar 返回tabBar不刷新页面
2019/07/25 Javascript
[02:20]DOTA2英雄基础教程 黑暗贤者
2013/12/19 DOTA
python实现推箱子游戏
2020/03/25 Python
Django框架之登录后自定义跳转页面的实现方法
2019/07/18 Python
python ubplot使用方法解析
2020/01/10 Python
python实现图像拼接功能
2020/03/23 Python
Python任务调度模块APScheduler使用
2020/04/15 Python
Python的Django框架实现数据库查询(不返回QuerySet的方法)
2020/05/19 Python
Python如何读取、写入CSV数据
2020/07/28 Python
python 中关于pycharm选择运行环境的问题
2020/10/31 Python
戴尔加拿大官网:Dell加拿大
2016/09/17 全球购物
销售自我评价
2013/10/22 职场文书
施工资料员的岗位职责
2013/12/22 职场文书
党的作风建设心得体会
2014/10/22 职场文书
2015年档案管理工作总结
2015/04/08 职场文书
2015年建筑工作总结报告
2015/05/04 职场文书
军训结束新闻稿
2015/07/17 职场文书
2016春节放假通知范文
2015/08/18 职场文书
Pytorch 实现变量类型转换
2021/05/17 Python
7个关于Python的经典基础案例
2021/11/07 Python