python pygame实现五子棋双人联机
作者:-小黄怪- 发布时间:2022-04-12 22:41:04
标签:python,pygame,五子棋
本文实例为大家分享了python pygame实现五子棋双人联机的具体代码,供大家参考,具体内容如下
同一局域网内,服务端开启时,另一机器将IP地址HOST改为服务端对应的IP地址、端口号与服务端的保持一致即可实现双人联机。(IP地址查询方式:菜单栏输入cmd,cmd窗口输入ipconfig找到无线网络下的IPv4地址)
服务端:
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 8 14:03:09 2021
@author: Administrator
"""
import pygame
import sys
from pygame.locals import *
from collections import Counter
from socket import *
from time import ctime
import json
import select
import socket
#界面初始化
screen=pygame.display.set_mode((400,450))
pygame.display.set_caption('五子棋')
pygame.init()
#图片导入
img_board=pygame.image.load('F:/images/五子棋/chess_board.png')
img_bchess=pygame.image.load('F:/images/五子棋/black_chess.jpg')
img_wchess=pygame.image.load('F:/images/五子棋/white_chess.jpg')
#颜色
white=(255,255,255)
black=(0,0,0)
#用于传送的数据
msg=[]
#棋盘定义
chess_board=[[]]
def set_chess_board():
x,y=0,0
while True:
if x==400:
x=0
y+=40
if y<400:
chess_board.append([])
if y==400:
break
chess_board[-1].append([x,y])
x+=40
set_chess_board()
#棋盘格子是否落子
chess_exist=[[0 for i in range(10)]for j in range(10)]
#黑白棋子初始化
black_chess,white_chess=[],[]
#棋子类型
chess_kind=1 #1为黑棋,0为白棋
wcx,wcy,bcx,bcy=[],[],[],[] #white_chess_x
def draw_board():
for i in chess_board:
for j in i:
screen.blit(img_board,(j[0],j[1]))
pygame.display.update()
#默认棋子类型为1
def set_chess():
if event.type==MOUSEBUTTONDOWN:
pos=pygame.mouse.get_pos()
for i in range(len(chess_board)):
for j in range(len(chess_board[i])):
if chess_board[i][j][0]<pos[0]<chess_board[i][j][0]+40 and chess_board[i][j][1]<pos[1]<chess_board[i][j][1]+40:
if chess_exist[i][j]==0:
black_chess.append([i,j])
bcx.append(black_chess[-1][0])
bcy.append(black_chess[-1][1])
msg.extend((i,j))
chess_exist[i][j]=1
pygame.display.update()
return 1
def draw_chess():
for i in white_chess:
screen.blit(img_wchess,(i[1]*40,i[0]*40))
for i in black_chess:
screen.blit(img_bchess,(i[1]*40,i[0]*40))
pygame.display.update()
def row_column_win(x,m,n,chess):
for i in x:
if x[i]>=5:
xy=[]
for j in chess:
if j[m]==i:
xy.append(j[n])
xy.sort()
count=0
for j in range(len(xy)-1):
if xy[j]+1==xy[j+1]:
count+=1
else:
count=0
if count>=4:
return 1
def xiejiao_win(chess):
x,y=[],[]
chess.sort()
for i in chess:
x.append(i[0])
y.append(i[1])
c,first,last=0,0,0
for i in range(len(x)-1):
if x[i+1]!=x[i]:
if x[i]+1==x[i+1]:
c+=1
last=i+1
else:
if c<4:
first=i+1
c=0
else:
last=i
print(last)
break
else:
last=i+1
if c>=4:
dis=[]
for i in range(first,last+1):
dis.append(x[i]-y[i])
count=Counter(dis)
for i in count:
if count[i]>=5:
return 1
dis=[]
x2=[i*(-1) for i in x]
for i in range(first,last+1):
dis.append(x2[i]-y[i])
count=Counter(dis)
for i in count:
if count[i]>=5:
return 1
def gameover():
wcx_count,wcy_count,bcx_count,bcy_count=Counter(wcx),Counter(wcy),Counter(bcx),Counter(bcy)
if row_column_win(wcx_count,0,1,white_chess)==1:
return 0
elif row_column_win(bcx_count,0,1,black_chess)==1:
return 1
elif row_column_win(wcy_count,1,0,white_chess)==1:
return 0
elif row_column_win(bcy_count,1,0,black_chess)==1:
return 1
elif xiejiao_win(white_chess)==1:
return 0
elif xiejiao_win(black_chess)==1:
return 1
def draw_text(text,x,y,size):
pygame.font.init()
fontObj=pygame.font.SysFont('SimHei',size )
textSurfaceObj=fontObj.render(text, True, white,black)
textRectObj=textSurfaceObj.get_rect()
textRectObj.center=(x,y)
screen.blit(textSurfaceObj, textRectObj)
pygame.display.update()
#定义服务器名称
HOST = '0.0.0.0'
PORT = 400
BUFSIZE = 1024
ADDR = (HOST,PORT)
#定义服务器属性
tcpsersock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcpsersock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) # 对socket的配置重用ip和端口号
tcpsersock.bind(ADDR)
tcpsersock.listen(1)
inputs=[tcpsersock]
print(inputs)
draw_board()
settable=1
link=False
while True:
rs,ws,es=select.select(inputs, [], [],0)
for r in rs:
if r is tcpsersock:
link=True
print('new ser')
tcpcliscock, addr = tcpsersock.accept()
inputs.append(tcpcliscock)
else:
data,addr=r.recvfrom(BUFSIZE)
disconnected=not data
draw_text('你的回合',200,420,15)
if disconnected:
inputs.remove(r)
draw_text('对手掉线',200,420,15)
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
else:
data=json.loads(data)
settable=1
white_chess.append(data)
wcx.append(data[0])
wcy.append(data[1])
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
tcpsersock.close()
if link==True:
if settable==1:
if set_chess()==1:
draw_text('对手回合',200,420,15)
settable=0
msg1=json.dumps(msg)
tcpcliscock.sendto(msg1.encode(),ADDR)
msg=[]
draw_chess()
if gameover()==1:
draw_text('你赢了!',200,420,15)
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
elif gameover()==0:
draw_text('你输了!',200,420,15)
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
tcpcliscock.close()
tcpsersock.close()
客户端:
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 8 14:03:09 2021
@author: Administrator
"""
import pygame
import sys
from pygame.locals import *
from collections import Counter
from socket import *
from time import ctime
import json
import select
import socket
import time
#界面初始化
screen=pygame.display.set_mode((400,450))
pygame.display.set_caption('五子棋')
pygame.init()
#图片导入
img_board=pygame.image.load('F:/images/五子棋/chess_board.png')
img_bchess=pygame.image.load('F:/images/五子棋/black_chess.jpg')
img_wchess=pygame.image.load('F:/images/五子棋/white_chess.jpg')
#颜色
white=(255,255,255)
black=(0,0,0)
#用于传送的数据
msg=[]
#棋盘定义
chess_board=[[]]
def set_chess_board():
x,y=0,0
while True:
if x==400:
x=0
y+=40
if y<400:
chess_board.append([])
if y==400:
break
chess_board[-1].append([x,y])
x+=40
set_chess_board()
#棋盘格子是否落子
chess_exist=[[0 for i in range(10)]for j in range(10)]
#黑白棋子初始化
black_chess,white_chess=[],[]
#棋子类型
chess_kind=1 #1为黑棋,0为白棋
wcx,wcy,bcx,bcy=[],[],[],[] #white_chess_x
def draw_board():
for i in chess_board:
for j in i:
screen.blit(img_board,(j[0],j[1]))
pygame.display.update()
#默认棋子类型为0
def set_chess():
if event.type==MOUSEBUTTONDOWN:
pos=pygame.mouse.get_pos()
for i in range(len(chess_board)):
for j in range(len(chess_board[i])):
if chess_board[i][j][0]<pos[0]<chess_board[i][j][0]+40 and chess_board[i][j][1]<pos[1]<chess_board[i][j][1]+40:
if chess_exist[i][j]==0:
white_chess.append([i,j])
wcx.append(white_chess[-1][0])
wcy.append(white_chess[-1][1])
msg.extend((i,j))
chess_exist[i][j]=1
pygame.display.update()
return 1
def draw_chess():
for i in white_chess:
screen.blit(img_wchess,(i[1]*40,i[0]*40))
for i in black_chess:
screen.blit(img_bchess,(i[1]*40,i[0]*40))
pygame.display.update()
def row_column_win(x,m,n,chess):
for i in x:
if x[i]>=5:
xy=[]
for j in chess:
if j[m]==i:
xy.append(j[n])
xy.sort()
count=0
for j in range(len(xy)-1):
if xy[j]+1==xy[j+1]:
count+=1
else:
count=0
if count>=4:
return 1
def xiejiao_win(chess):
x,y=[],[]
chess.sort()
for i in chess:
x.append(i[0])
y.append(i[1])
c,first,last=0,0,0
for i in range(len(x)-1):
if x[i+1]!=x[i]:
if x[i]+1==x[i+1]:
c+=1
last=i+1
else:
if c<4:
first=i+1
c=0
else:
last=i
print(last)
break
else:
last=i+1
if c>=4:
dis=[]
for i in range(first,last+1):
dis.append(x[i]-y[i])
count=Counter(dis)
for i in count:
if count[i]>=5:
return 1
dis=[]
x2=[i*(-1) for i in x]
for i in range(first,last+1):
dis.append(x2[i]-y[i])
count=Counter(dis)
for i in count:
if count[i]>=5:
return 1
def gameover():
wcx_count,wcy_count,bcx_count,bcy_count=Counter(wcx),Counter(wcy),Counter(bcx),Counter(bcy)
if row_column_win(wcx_count,0,1,white_chess)==1:
return 1
elif row_column_win(bcx_count,0,1,black_chess)==1:
return 0
elif row_column_win(wcy_count,1,0,white_chess)==1:
return 1
elif row_column_win(bcy_count,1,0,black_chess)==1:
return 0
elif xiejiao_win(white_chess)==1:
return 1
elif xiejiao_win(black_chess)==1:
return 0
def draw_text(text,x,y,size):
pygame.font.init()
fontObj=pygame.font.SysFont('SimHei',size )
textSurfaceObj=fontObj.render(text, True, white,black)
textRectObj=textSurfaceObj.get_rect()
textRectObj.center=(x,y)
screen.blit(textSurfaceObj, textRectObj)
pygame.display.update()
#定义客户端名称
HOST = '10.203.111.180'
PORT = 400
BUFSIZE = 1024
ADDR = (HOST,PORT)
#连接服务器
tcpCliSock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcpCliSock.connect(ADDR)
inputs=[tcpCliSock]
draw_board()
settable=0
while True:
rs,ws,es=select.select(inputs,[],[],0)
for r in rs:
if r is tcpCliSock:
data,addr = r.recvfrom(BUFSIZE)
draw_text('你的回合',200,420,15)
data=json.loads(data)
settable=1
black_chess.append(data)
bcx.append(data[0])
bcy.append(data[1])
for event in pygame.event.get():
if event.type==QUIT:
tcpCliSock.close()
pygame.quit()
sys.exit()
if settable==1:
if set_chess()==1:
draw_text('对手回合',200,420,15)
settable=0
msg1=json.dumps(msg)
tcpCliSock.sendto(msg1.encode(),ADDR)
msg=[]
draw_chess()
if gameover()==1:
draw_text('你赢了!',200,420,15)
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
elif gameover()==0:
draw_text('你输了!',200,420,15)
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
背景:
黑棋:
白棋:
效果演示:
来源:https://blog.csdn.net/qq_41890466/article/details/117792912
0
投稿
猜你喜欢
- 本文分析了python3新特性函数注释Function Annotations用法。分享给大家供大家参考,具体如下:Python 3.X新增
- 如果您目前拥有一个冷备份,但是缺少了其中的一个数据文件,但你目前存在所有的归档,如果您要恢复数据文件,可以参考以下的示例:[oracle@j
- 注:答案一般在网上都能够找到。1.对if __name__ == 'main'的理解陈述2.python是如何进行内存管理的
- 题目描述将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。LeetCode原题地址:https:/
- 1.Pool资源池的概念Pool资源池的官方文档:https://docs.ceph.com/en/pacific/rados/operat
- 一、asp.net中导出Execl的方法:在asp.net中导出Execl有两种方法,一种是将导出的文件存放在服务器某个文件夹下面,然后将文
- 在处理pandas的DataFrame中,如果想像excel那样筛选,只要其中的某一行或者几行,可以使用isin()方法来实现,只需要将需要
- 第二次修改models.py以后再次python manage.py makemigrations提示如下You are trying to
- 项目简介之前学python的时候 写了个游戏来练手 用的是 pygame 没有别的依赖只用了一两百行的代码就实现了 整体来说功能并不算完整项
- 在Linux、Windows、Mac OS的命令行窗口或Shell窗口,执行python命令,启动Python交互式解释器。交互式解释器会等
- 拉勾网面试题1. 你首先说出三个不同的特殊数,要求必须是个位数,比如3、5、7。2. 让所有学生拍成一队,然后按顺序报数。3. 学生报数时,
- 如下所示:# coding = utf-8import ospath = "D:\\chunyu"#想要重命名所有文件存
- ConfigParser模块在Python3修改为configparser,这个模块定义了一个ConfigeParser类,该类的作用是让配
- 本文实例为大家分享了python模拟事件触发机制的具体代码,供大家参考,具体内容如下EventManager.py# -*- encodin
- 前言MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,属于 Oracle 旗下产品。MySQL 是最流行的关系型数据库
- JSON Schema是一个用于验证JSON数据结构的强大工具, 我查看并学习了JSON Schema的官方文档, 做了详细的记录, 分享一
- I. 前言在前面的一篇文章PyTorch搭建LSTM实现时间序列预测(负荷预测)中,我们利用LSTM实现了负荷预测,但我们只是简单利用负荷预
- 网关是什么简单来说,网关就是暴露给外部的请求入口。就和门卫一样,外面的人想要进来,必须要经过门卫。当然,网关并不一定是必须的,后端服务通过h
- 什么是1433端口 1433端口,是SQL Server默认的端口,SQL Server服务使用两个端口:TCP-1433、UDP-1434
- Mysql安装、配置、优化,供大家参考,具体内容如下Mysql下载首先登入官网下载mysql的安装包,官网地址https://dev.mys