欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python实现网络五子棋

程序员文章站 2023-01-24 21:29:54
本文实例为大家分享了python实现网络五子棋的具体代码,供大家参考,具体内容如下服务器端:import osimport socketimport threadingfrom tkinter imp...

本文实例为大家分享了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 五子棋