python实现网络五子棋

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

游戏执行页面:

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

(0)

相关推荐

  • python实现五子棋小游戏

    本文实例为大家分享了python实现五子棋小游戏的具体代码,供大家参考,具体内容如下 暑假学了十几天python,然后用pygame模块写了一个五子棋的小游戏,代码跟有缘人分享一下. import numpy as np import pygame import sys import traceback import copy from pygame.locals import * pygame.init() pygame.mixer.init() #颜色 background=(201,202

  • python实现五子棋小程序

    本文实例为大家分享了python实现五子棋小程序的具体代码,供大家参考,具体内容如下 一.结合书上例子,分三段编写: wuziqi.py #coding:utf-8 from win_notwin import * from show_qipan import * maxx=10 #10行10列 maxy=10 qipan=[[0,0,0,0,1,0,0,2,0,0],[0,1,2,1,1,0,2,0,0,0],[0,0,0,0,1,1,0,2,0,0],[0,0,0,0,2,0,0,1,0,0

  • python实现五子棋游戏

    本文实例为大家分享了python实现五子棋游戏的具体代码,供大家参考,具体内容如下 话不多说,直接上代码: 全部工程文件,在GitHub:五子棋 效果预览: #!/usr/bin/env python3 #-*- coding:utf-8 -*- import pygame from pygame.locals import * from sys import exit import numpy background_image = 'qipan.png' white_image = 'whit

  • python使用minimax算法实现五子棋

    这是一个命令行环境的五子棋程序.使用了minimax算法. 除了百度各个棋型的打分方式,所有代码皆为本人所撸.本程序结构与之前的井字棋.黑白棋一模一样. 有一点小问题,没时间弄了,就这样吧. 一.效果图 (略) 二.完整代码 from functools import wraps import time import csv ''' 五子棋 Gobang 作者:hhh5460 时间:20181213 ''' #1.初始化棋盘 #------------ def init_board(): '''

  • python pygame实现五子棋小游戏

    今天学习了如何使用pygame来制作小游戏,下面是五子棋的代码,我的理解都写在注释里了 import pygame # 导入pygame模块 print(pygame.ver) # 检查pygame的版本,检查pygame有没有导入成功 EMPTY = 0 BLACK = 1 WHITE = 2 # 定义三个常量函数,用来表示白棋,黑棋,以及 空 black_color = [0, 0, 0] # 定义黑色(黑棋用,画棋盘) white_color = [255, 255, 255] # 定义白

  • python五子棋游戏的设计与实现

    这个python的小案例是五子棋游戏的实现,在这个案例中,我们可以实现五子棋游戏的两个玩家在指定的位置落子,画出落子后的棋盘,并且根据函数判断出输赢的功能. 这个案例的思路如下所示: 首先,根据棋盘的样子画出棋盘 然后,对棋盘进行初始化,将可以落子的位置进行统一化处理 接下来,就是进入游戏的环节,双方轮流落子,落子后,并将棋盘画出 最后,根据落子的位置判断选手的的输赢情况,游戏结束 五子棋游戏的设计和实现 代码如下: def main(): print("五子棋游戏".center(5

  • python实现简单五子棋游戏

    本文实例为大家分享了python实现简单五子棋游戏的具体代码,供大家参考,具体内容如下 from graphics import * from math import * import numpy as np def ai(): """ AI计算落子位置 """ maxmin(True, DEPTH, -99999999, 99999999) return next_point[0], next_point[1] def maxmin(is_ai

  • 使用python实现简单五子棋游戏

    用python实现五子棋简单人机模式的练习过程,供大家参考,具体内容如下 第一次写博客,我尽力把它写好. 最近在初学python,今天就用自己的一些粗浅理解,来记录一下这几天的python简单人机五子棋游戏的练习,下面是实现过程的理解(是在cmd中运行的): 主要流程: *重点内容* - 首先是模块及类的划分 - 棋子类和棋盘类的方法 - 对策略类里的功能进行细分,调用棋子类和棋盘类 - 写出判断输赢的方法 - 用main函数进行整个游戏进度的控制 模块及类的划分 类的划分涉及到了面向对象的内容

  • python实现五子棋游戏(pygame版)

    本文实例为大家分享了python五子棋游戏的具体代码,供大家参考,具体内容如下 目录 简介 实现过程 结语 简介 使用python实现pygame版的五子棋游戏: 环境:Windows系统+python3.8.0 游戏规则: 1.分两位棋手对战,默认黑棋先下:当在棋盘点击左键,即在该位置绘制黑棋: 2.自动切换到白棋,当在棋盘点击左键,即在该位置绘制白棋: 3.轮流切换棋手下棋,当那方先形成5子连线者获胜(横.竖.斜.反斜四个方向都可以). 游戏运行效果如下: 实现过程 1.新建文件settin

  • python版本五子棋的实现代码

    正文之前 前阵子做了个<人工智能> 的课程作业,然后写了个人工智障...大概就是个可以跟你下五子棋的傻儿子...下面是代码和效果 正文 1. 摘要 机器博弈是人工智能领域的重要分支,它的研究对象多以复杂的棋牌类智力游戏为主,已经得到解决的棋类游戏,几乎全部都应归功于机器博弈近半个世纪的发展.计算机解决问题的优势在于能把不易解析的问题,借助于现代计算机的运算速度优势枚举出所有的合理情形而得解;然而,博弈问题的复杂程度决定了它不能过度依赖机器的计算能力.许多待解决的或已经解决的棋类,其状态空间复杂

随机推荐