首页 > 其他分享 >pygame手搓五子棋

pygame手搓五子棋

时间:2024-08-26 14:04:17浏览次数:5  
标签:poslist hindex 五子棋 width plus pygame piece windex

代码:

#coding=utf-8

import os,sys,re,time
import pygame
import random
from win32api import GetSystemMetrics

pygame.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*percent

maxLine = 15
maxField = 15
empty_width = window_height / (maxLine + 2) / 1.6

left_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 = 1

perWidth = left_width_nei / maxField
perHeight = left_height_nei / maxLine

circle_width = perWidth / 2.5

font_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 False
    
    if windex > maxField:
        return False
    
    if 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 False
        
    return True
        
def checkWinPositioninfo(pieceList, posinfo):
    for piece in pieceList:
        if piece['hindex'] == posinfo['hindex'] and piece['windex'] == posinfo['windex']:
            return True
    return False

class Button:
    def __init__(self, x, y, width, height, color, text):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.text = text
 
    def 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 = text
        
    
mouse_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 = False
        if 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 = None
                numIsON = False
                msglist = ["黑子开始执棋..."]
                
            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 = False
                else:
                    numBt.changeText('隐藏编号')
                    numIsON = True
                
            if mouse_pos[0] <= left_width and mouse_pos[1] <= left_height and posResult == None:
                cy = None
                for i in range(0, maxLine):
                    line1 = empty_width + perHeight * i
                    line2 = line1 + perHeight
                    if mouse_pos[0] >= line1 and mouse_pos[0] <= line2:
                        if mouse_pos[0]-line1 < line2 - mouse_pos[0]:
                            cy = i
                        else:
                            cy = i+1
                            
                cx = None
                for i in range(0, maxField):
                    field1 = empty_width + perWidth * i
                    field2 = field1 + perWidth
                    if mouse_pos[1] >= field1 and mouse_pos[1] <= field2:
                        if mouse_pos[1]-field1 < field2 - mouse_pos[1]:
                            cx = i
                        else:
                            cx = i+1
                            
                if cy != None and cx != None:
                    placeFlag = True
                    for p in pieceList:
                        if p['hindex'] == cx and p['windex'] == cy:
                            placeFlag = False
                
                    if placeFlag:
                        if len(pieceList) > 0:
                            if pieceList[-1]['type'] == 0:
                                type = 1
                                typecn = '黑子'
                            else:
                                type = 0
                                typecn = '白子'
                        else:
                            type = 1
                            typecn = '黑子'
                        number = len(pieceList) + 1
                        pieceList.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 = True
                            if winner == 0:
                                print('白子胜')
                                msglist.append('白子胜')
                            else:
                                print('黑子胜')
                                msglist.append('黑子胜')
            
    keys_pressed = pygame.key.get_pressed()
    
    #ESC键
    if keys_pressed[pygame.K_ESCAPE]:
        running = False
        
    screen.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) / 600
    
pygame.quit()

 

截图:

 

 

 

标签:poslist,hindex,五子棋,width,plus,pygame,piece,windex
From: https://www.cnblogs.com/xuxiaobo/p/18380881

相关文章

  • Go实现一个五子棋功能
    参考https://juejin.cn/post/6847902215575699464packagemainimport( "fmt" "math/rand" "strconv" "strings" "time")typehanduintconst( NilHandhand=iota//空白 BlackHand//黑手 Wh......
  • pygame各类形状
    代码:#coding=utf-8importos,sys,re,time,mathimportpygameimportrandomfromwin32apiimportGetSystemMetricsfrommathimportpipygame.init()pygame.display.set_caption("各种形状测试")percent=0.6screen_width=GetSystemMetrics(0)screen_hei......
  • pygame物体碰撞
    代码:#coding=utf-8importos,sys,re,timeimportpygameimportrandomimportmathfromwin32apiimportGetSystemMetricsfromtkinterimportmessageboxpygame.init()pygame.display.set_caption("我的游戏")percent=0.6screen_width=GetSystemMetri......
  • 使用 Pygame 创建简单的移动方块游戏
    Pygame是一个用于开发图形和多媒体应用的优秀Python库。下面,我们将逐步解释如何创建一个简单的游戏,其中一个蓝色方块可以在屏幕上移动。 安装Pygame首先,确保你已经安装了Pygame。可以通过以下命令安装:pipinstallpygame 游戏结构1.初始化Pygame开始时,需......
  • C语言工程实践实现完整的五子棋项目一
    五子棋第一章玩家信息部分五子棋五子棋第一章前言一、所需技术二、玩家信息部分实现1.头文件部分2.菜单部分3.玩家信息部分总结每文推荐前言接下来的几篇文章我将带领大家实现一个工程实践的项目–五子棋。它是一个比较完整的项目,主要包括了三个部分:1.玩家信......
  • pygame开发小游戏
    代码:#coding=utf-8importos,sys,re,timeimportpygameimportrandomfromwin32apiimportGetSystemMetricsfromtkinterimportmessageboxfromsqlparse.filtersimportright_margin#pyinstaller-F-wdaziyan.pypygame.init()pygame.display.set_caption(&......
  • 【python】pygame开发小游戏原来如此简单,掌握这几步就可以快速上手
    ✨✨欢迎大家来到景天科技苑✨✨......
  • 无法写入使用 pygbag 编译的 python/pygame 程序中的文本文件
    我有一个python/pygame程序,它从与该程序位于同一目录中的测试文件中读取数据。在程序结束时,应该将文本写回测试文件。这在Python环境中运行程序时有效,但在使用Pygbag编译并在浏览器中运行时无效。程序(称为main,py)是:importasyncioimportosimportpygamepyg......
  • pygame.init() 到底做了什么?
    我读过/看过的每个pygame教程都说,在考虑做其他事情之前,请将“pygame.init()”压缩到代码中。显然,它初始化了pygame模块或其他东西,这似乎非常重要。直到我想到从代码中删除“pygame.init()”行,只是为了看看会发生什么。你瞧,我的游戏工作原理完全一样。我上网,再一次,无......
  • (一)pygame保证玩家移动速度与电脑性能无关,pygame中的增量时间(dt)的利用
    前言在pygame中一般刚入门书籍上的游戏项目玩家移动逻辑如下:玩家坐标.x+=移动方向*速度玩家坐标.y+=移动方向*速度使用这种移动逻辑的缺点十分明显,就是玩家的移动速度会受到电脑性能的影响。主要体现在游戏运行时候帧率不一样,高性能的电脑帧率比较高,代码调用频率高......