pygame手搓五子棋

news/2024/11/14 13:06:07/文章来源:https://www.cnblogs.com/xuxiaobo/p/18380881

代码:

#coding=utf-8import os,sys,re,time
import pygame
import random
from win32api import GetSystemMetricspygame.init()
pygame.display.set_caption("五子棋")percent = 0.6
screen_width = GetSystemMetrics(0)
screen_height = GetSystemMetrics(1)
window_width = screen_width*percent
window_height = screen_height*percentmaxLine = 15
maxField = 15
empty_width = window_height / (maxLine + 2) / 1.6left_width = window_height
left_height = window_height
left_width_nei = left_width - 2 * empty_width
left_height_nei = left_height - 2 * empty_width
right_width = window_width - left_width
right_height = window_height
line_border_width = 1perWidth = left_width_nei / maxField
perHeight = left_height_nei / maxLinecircle_width = perWidth / 2.5font_path = os.path.join(os.path.dirname(sys.argv[0]), 'simsun.ttc')
bg_img_path = os.path.join(os.path.dirname(sys.argv[0]), 'bg003.jpeg')
font = pygame.font.Font(font_path, 15)
fontMsg = pygame.font.Font(font_path, 12)dt = 0
clock = pygame.time.Clock()screen = pygame.display.set_mode((window_width-right_width/1.5, window_height))#停止处理输入法事件
pygame.key.stop_text_input()def placePiece(hindex = 0, windex = 0, type = 0, number = 1):if hindex > maxLine:return Falseif windex > maxField:return Falseif type == 0:circle_color = 'white'else:circle_color = 'black'pygame.draw.circle(screen, circle_color, (empty_width+windex*perWidth, empty_width+hindex*perHeight), circle_width)def checkWhoWin():#白子pieceList0 = []#黑子pieceList1 = []for p in pieceList:if p['type'] == 0:pieceList0.append(p)else:pieceList1.append(p)sorted_pieceList0 = sorted(pieceList0, key=lambda piece: '%s_%s' % (piece['hindex'], piece['windex']))sorted_pieceList1 = sorted(pieceList1, key=lambda piece: '%s_%s' % (piece['hindex'], piece['windex']))for piece in sorted_pieceList0:poslist = []for plus in range(0, 5):poslist.append({'hindex':piece['hindex']+plus, 'windex':piece['windex']})if checkWinPositionList(sorted_pieceList0, poslist):return [0, poslist]poslist = []for plus in range(0, 5):poslist.append({'hindex':piece['hindex']-plus, 'windex':piece['windex']})if checkWinPositionList(sorted_pieceList0, poslist):return [0, poslist]poslist = []for plus in range(0, 5):poslist.append({'hindex':piece['hindex'], 'windex':piece['windex']+plus})if checkWinPositionList(sorted_pieceList0, poslist):return [0, poslist]poslist = []for plus in range(0, 5):poslist.append({'hindex':piece['hindex'], 'windex':piece['windex']-plus})if checkWinPositionList(sorted_pieceList0, poslist):return [0, poslist]poslist = []for plus in range(0, 5):poslist.append({'hindex':piece['hindex']+plus, 'windex':piece['windex']+plus})if checkWinPositionList(sorted_pieceList0, poslist):return [0, poslist]poslist = []for plus in range(0, 5):poslist.append({'hindex':piece['hindex']-plus, 'windex':piece['windex']-plus})if checkWinPositionList(sorted_pieceList0, poslist):return [0, poslist]poslist = []for plus in range(0, 5):poslist.append({'hindex':piece['hindex']+plus, 'windex':piece['windex']-plus})if checkWinPositionList(sorted_pieceList0, poslist):return [0, poslist]poslist = []for plus in range(0, 5):poslist.append({'hindex':piece['hindex']-plus, 'windex':piece['windex']+plus})if checkWinPositionList(sorted_pieceList0, poslist):return [0, poslist]for piece in sorted_pieceList1:poslist = []for plus in range(0, 5):poslist.append({'hindex':piece['hindex']+plus, 'windex':piece['windex']})if checkWinPositionList(sorted_pieceList1, poslist):return [1, poslist]poslist = []for plus in range(0, 5):poslist.append({'hindex':piece['hindex']-plus, 'windex':piece['windex']})if checkWinPositionList(sorted_pieceList1, poslist):return [1, poslist]poslist = []for plus in range(0, 5):poslist.append({'hindex':piece['hindex'], 'windex':piece['windex']+plus})if checkWinPositionList(sorted_pieceList1, poslist):return [1, poslist]poslist = []for plus in range(0, 5):poslist.append({'hindex':piece['hindex'], 'windex':piece['windex']-plus})if checkWinPositionList(sorted_pieceList1, poslist):return [1, poslist]poslist = []for plus in range(0, 5):poslist.append({'hindex':piece['hindex']+plus, 'windex':piece['windex']+plus})if checkWinPositionList(sorted_pieceList1, poslist):return [1, poslist]poslist = []for plus in range(0, 5):poslist.append({'hindex':piece['hindex']-plus, 'windex':piece['windex']-plus})if checkWinPositionList(sorted_pieceList1, poslist):return [1, poslist]poslist = []for plus in range(0, 5):poslist.append({'hindex':piece['hindex']+plus, 'windex':piece['windex']-plus})if checkWinPositionList(sorted_pieceList1, poslist):return [1, poslist]poslist = []for plus in range(0, 5):poslist.append({'hindex':piece['hindex']-plus, 'windex':piece['windex']+plus})if checkWinPositionList(sorted_pieceList1, poslist):return [1, poslist]def checkWinPositionList(pieceList, poslist):for posinfo in poslist:if checkWinPositioninfo(pieceList, posinfo) == False:return Falsereturn Truedef checkWinPositioninfo(pieceList, posinfo):for piece in pieceList:if piece['hindex'] == posinfo['hindex'] and piece['windex'] == posinfo['windex']:return Truereturn Falseclass Button:def __init__(self, x, y, width, height, color, text):self.x = xself.y = yself.width = widthself.height = heightself.color = colorself.text = textdef draw(self, win, outline=None, line_width = 1):pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height))if outline:pygame.draw.rect(win, outline, (self.x, self.y, self.width, self.height), 1)font = pygame.font.Font(font_path, 12)text = font.render(self.text, 1, (0, 0, 0))win.blit(text, (self.x + (self.width / 2 - text.get_width() / 2), self.y + (self.height / 2 - text.get_height() / 2)))def changeText(self, text):self.text = textmouse_pos = (-1, -1)
pieceList = [] #棋子列表
poslist = [] #连子列表
posResult = None
numIsON = False
msglist = ["黑子开始执棋..."]
restartBt = Button(window_width-right_width+2, 5, 80, 25, 'Gold3', '重新开始')
numBt = Button(window_width-right_width+84, 5, 80, 25, 'Gold3', '显示编号')
running = True
while running:for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseif event.type == pygame.MOUSEBUTTONDOWN:mouse_pos = pygame.mouse.get_pos()if restartBt.x + restartBt.width > event.pos[0] > restartBt.x and restartBt.y + restartBt.height > event.pos[1] > restartBt.y:pieceList = [] #棋子列表poslist = [] #连子列表posResult = NonenumIsON = Falsemsglist = ["黑子开始执棋..."]if numBt.x + numBt.width > event.pos[0] > numBt.x and numBt.y + numBt.height > event.pos[1] > numBt.y:if numIsON == True:numBt.changeText('显示编号')numIsON = Falseelse:numBt.changeText('隐藏编号')numIsON = Trueif mouse_pos[0] <= left_width and mouse_pos[1] <= left_height and posResult == None:cy = Nonefor i in range(0, maxLine):line1 = empty_width + perHeight * iline2 = line1 + perHeightif mouse_pos[0] >= line1 and mouse_pos[0] <= line2:if mouse_pos[0]-line1 < line2 - mouse_pos[0]:cy = ielse:cy = i+1cx = Nonefor i in range(0, maxField):field1 = empty_width + perWidth * ifield2 = field1 + perWidthif mouse_pos[1] >= field1 and mouse_pos[1] <= field2:if mouse_pos[1]-field1 < field2 - mouse_pos[1]:cx = ielse:cx = i+1if cy != None and cx != None:placeFlag = Truefor p in pieceList:if p['hindex'] == cx and p['windex'] == cy:placeFlag = Falseif placeFlag:if len(pieceList) > 0:if pieceList[-1]['type'] == 0:type = 1typecn = '黑子'else:type = 0typecn = '白子'else:type = 1typecn = '黑子'number = len(pieceList) + 1pieceList.append({'hindex':cx, 'windex':cy, 'type':type, 'number':number})print('%s 落在%s行%s列' % (typecn, cx+1, cy+1))msglist.append('%s 落在%s行%s列' % (typecn, cx+1, cy+1))posResult = checkWhoWin()if not posResult == None:winner = posResult[0]poslist = posResult[1]numIsON = Trueif winner == 0:print('白子胜')msglist.append('白子胜')else:print('黑子胜')msglist.append('黑子胜')keys_pressed = pygame.key.get_pressed()#ESC键if keys_pressed[pygame.K_ESCAPE]:running = Falsescreen.fill("purple")#左侧块rect1 = pygame.Rect(empty_width, empty_width, perWidth*maxField, perHeight*maxLine)pygame.draw.rect(screen, 'LightYellow1', rect1)imgbg = pygame.image.load(bg_img_path).convert_alpha()timgbg = pygame.transform.scale(imgbg, (left_width, left_height))screen.blit(timgbg, (0, 0))#右侧块rect2 = pygame.Rect(left_width, 0, right_width, right_height)pygame.draw.rect(screen, 'Honeydew', rect2)restartBt.draw(screen, 'black')numBt.draw(screen, 'blue')#消息for i,msg in enumerate(msglist[-30:]):msg = "[%s]%s" % (i+1, msg)rect_text = fontMsg.render(msg, 1, 'black')screen.blit(rect_text, (left_width+5, 33+i*18+5))#横线for i in range(0, maxLine+1):start = (empty_width, empty_width+i*perHeight)end = (empty_width+left_width_nei, empty_width+i*perHeight)pygame.draw.aaline(screen, 'black', start, end, line_border_width)#竖线for i in range(0, maxField+1):start = (empty_width+i*perWidth, empty_width)end = (empty_width+i*perWidth, empty_width+left_height_nei)pygame.draw.aaline(screen, 'black', start, end, line_border_width)#画棋子for p in pieceList:placePiece(p['hindex'], p['windex'], p['type'], p['number'])#画编号if numIsON:for p in pieceList:if p['type'] == 0:font_color = 'black'else:font_color = 'white'rect_text = font.render(str(p['number']), 1, font_color)screen.blit(rect_text, (empty_width+p['windex']*perWidth-perHeight/13, empty_width+p['hindex']*perHeight-perHeight/13))#将获胜棋子画上黄边if poslist:for posinfo in poslist:pygame.draw.circle(screen, 'yellow', (empty_width+posinfo['windex']*perWidth, empty_width+posinfo['hindex']*perHeight), circle_width, 2)#更新显示
    pygame.display.flip()#pygame.display.update()
    dt = clock.tick(60) / 600pygame.quit()

 

截图:

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/787504.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

网站提示404错误:页面未找到怎么办

当网站提示 404 Error 或 “页面未找到” 时,这意味着客户端尝试访问的资源在服务器上不存在或无法找到。这种情况很常见,可以通过以下几个步骤来诊断和解决问题: 常见原因URL 输入错误:这是最常见的原因之一。由于人为疏忽或输入错误,导致请求的 URL 与服务器上实际存在的…

OpenCV开发笔记(七十九):基于Stitcher类实现全景图片拼接

前言一个摄像头视野不大的时候,我们希望进行两个视野合并,这样让正视的视野增大,从而可以看到更广阔的标准视野。拼接的方法分为两条路,第一条路是stitcher类,第二条思路是特征点匹配。  本篇使用stitcher匹配,进行两张图来视野合并拼接。 Demo 两张图拼接过程步骤一:…

WPF 路由事件

一、什么是路由事件? 根据MSDN定义:功能定义:路由事件是一种可以针对元素树中的多个侦听器(而不是仅针对引发该事件的对象)调用处理程序的事件。 实现定义:路由事件是由 类的实例支持的 CLR 事件, RoutedEvent 由事件 Windows Presentation Foundation (WPF) 系统处理。…

【转载】Win11优化大小核调度(无需重启)

出处:https://bbs.saraba1st.com/2b/thread-2140520-1-1.html 打开隐藏电源管理选项: 管理员模式运行cmd,分别输入: powercfg -attributes SUB_PROCESSOR 7f2f5cfa-f10c-4823-b5e1-e93ae85f46b5 -ATTRIB_HIDE powercfg -attributes SUB_PROCESSOR 93b8b6dc-0698-4d1c-9ee4-…

【Pytorch教程】迅速入门Pytorch深度学习框架

@目录前言1.tensor基础操作1.1 tensor的dtype类型1.2 创建tensor(建议写出参数名字)1.2.1 空tensor(无用数据填充)API示例1.2.2 全一tensor1.2.3 全零tensor1.2.4 随机值[0,1)的tensor1.2.5 随机值为整数且规定上下限的tensorAPI示例1.2.6 随机值均值0方差1的tensor1.2.7 从…

AMD显卡VGA转HDMI花屏或者雪花屏解决办法

本以为是显卡或者显示屏或者转接线有问题,查阅资料后得出VGA转HDMI花屏或者雪花屏解决办法: 进入AMD控制面板。点击设置 - > 显示器 - > 覆盖 - > 禁用HDCP 即可完美解决问题。

AIGC时代,如何为“数据飞轮”提速

本文从技术角度,具体拆解DataLeap-找数助手、开发助手的实现方式,详AIGC如何为企业数智化转型赋能。更多技术交流、求职机会,欢迎关注字节跳动数据平台微信公众号,回复【1】进入官方交流群 企业通过数智化转型实现降本增效,已经成为行业共识。而随着AIGC时代到来,企业的…

windows 安装nginx

1.进入下载页面下载window版本 安装 2.解压, 直接运行 exe就行 3.使用nssm 将exe文件 作为服务运行 4.配置conf/nginx.conf 的配置文件

使用yum命令报错

报错如下Could not retrieve mirrorlist http://mirrorlist.centos.org/?release=7&arch=x86_64&repo=os&infra=stock error was 14: curl#6 - "Could not resolve host: mirrorlist.centos.org; Unknown error"One of the configured repositories fai…

EXITS:基于极值点低标注成本弱监督实例分割 | CVPR 2024

EXITS将极值点视为真实实例掩模的一部分并将它们传播以识别潜在前景和背景点,所有这些都用于训练伪标签生成器,然后由生成器给出的伪标签反过来用于最终模型的监督学习。 来源:晓飞的算法工程笔记 公众号论文: Extreme Point Supervised Instance Segmentation论文地址:htt…

Swahili-text:华中大推出非洲语言场景文本检测和识别数据集 | ICDAR 2024

论文提出了一个专门针对斯瓦希里语自然场景文本检测和识别的数据集,这在当前研究中是一个未充分开发的语言领域。数据集包括976张带标注的场景图像,可用于文本检测,以及8284张裁剪后的图像用于识别。 来源:晓飞的算法工程笔记 公众号论文: The First Swahili Language Scen…

Codeforces Round 968 (Div. 2)

良心出题人给了中文题解!!! A. Turtle and Good Strings 长度为 \(n\) 的字符串至少分成两段,使 \(\forall i < j\) ,第 \(i\) 段的首字符不等于第 \(j\) 段的尾字符 第一个字符一定作为首字符,最后一个字符一定作为尾字符,只要判断这两个字符是否相等即可 相等的话一…