python实现网络五子棋
作者:XXXOT 发布时间:2021-10-16 23:58:17
标签: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()
游戏执行页面:
来源:https://blog.csdn.net/weixin_53776140/article/details/115548090


猜你喜欢
- 示例标准线程多进程,生产者/消费者示例:Worker越多,问题越大# -*- coding: utf8 -*-import osimport
- 一、连接MYSQL。 格式: mysql -h主机地址 -u用户名 -p用户密码&nbs
- 最近看JavaScript高级程序设计,大有收获,接下来几天写一下读书笔记。之前写了一篇Ajax初步理解的随笔,里面有个函数用来创建XmlH
- 1.在pycham官网下载安装软件https://www.jetbrains.com/pycharm/download/2.我下载的是64位
- 打开一个Project在导航区带出多个Project将会影响PyCharm的运行速度,解决这个问题的方式只打开一个即可。有时候打开一个Pro
- MySql5.0以后均支持存储过程,最近有空,研究了一把这个。格式:以下为引用的内容:CREATE PROCEDURE
- 最近真的感觉到了python生态的强大(倒吸一口凉气)现在介绍一个可以生成动态二维码的库(myqr)效果如图:第一步要安装myqr库在cmd
- 1.安装下载网址:http://phantomjs.org/download.html选择合适的版本。然后解压即可。环境变量的配置:进入解压
- Python的绘图库也允许用户创建优雅的图形,本章给大家介绍的是关于ggplot绘制画图的技巧,ggplot2建立在grid系统上,这个系统
- 目录range函数的使用第一种创建方式第二种创建方式第三种创建方式判断指定的数有没有在当前序列中循环结构总结range函数的使用作为循环遍历
- 方法1: 单文件模块直接把文件拷贝到 $python_dir/Lib方法2: 多文件模块,文件内有setup.py文件在官网或者GitHub
- 目录结构:只需在自己的python项目下随便创建一个文件夹(下图中为:daka),然后将下载的chromedriver.exe、ask_fo
- 替换print?print怎么了?print 可能是所有学习Python语言的人第一个接触的东西。它最主要的功能就是往控制台 打印一段信息,
- 但是有时候,可以视看处进逻辑程度,可以把三者写成一个触发器,只是在其中稍作判断而已。 你可以根据从下面方法判断触发器是是处理了插入,删除还是
- mysql误删数据使用delete语句误删数据行使用drop table或者truncate table误删数据表使用drop databa
- 概述函数是基本的代码块,用于执行一个任务语法函数定义func 函数名称( 参数列表] ) (返回值列表]){ 执行语句}一.函数
- 2.彻底弄懂CSS盒子模式二(导航栏实例) 3.彻底弄懂CSS盒子模式三(浮动的表演和清除的自述) 4.彻底弄懂CSS盒子模式四(绝对定位和
- SecureFile功能是oracle 11g中对大对象(LOB)存储格式的完全重新设计实现,原来的LOB存储格式现在通称为BASIXFIL
- 最近在看流畅的python,在看第14章节的itertools模块,对其itertools中的相关函数实现的逻辑的实现其中在zip_long
- 1、前言由于笔者并未系统地学习过Python,对Python某些底层的实现细节一概不清楚,以至于在实际使用的时候会写出一些奇奇怪怪的Bug(