pygame手搓五子棋

代码:

#coding=utf-8

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

pygame.init()
pygame.display.set_caption("五子棋")

percent = 0.8
screen_width = GetSystemMetrics(0)
screen_height = GetSystemMetrics(1)
window_width = screen_width*percent
window_height = screen_height*percent

maxLine = 25
maxField = 25
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')
numFont = pygame.font.Font(font_path, int(15*percent))
fontMsg = pygame.font.Font(font_path, int(19*percent))

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)
        myfont = pygame.font.Font(font_path, int(19*percent))
        text = myfont.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 = ["黑子开始执棋..."]
buttonwidth = 80*percent
restartBt = Button(window_width-right_width+2, 1, buttonwidth, 25, 'Gold3', '重新开始')
numBt = Button(window_width-right_width+buttonwidth+4, 1, buttonwidth, 25, 'Gold3', '显示编号')
panBg = Button(window_width-right_width+buttonwidth*2+6, 1, buttonwidth, 25, 'Gold3', '切换背景')
bgNum = 1
bg_img_path = os.path.join(os.path.dirname(sys.argv[0]), 'bg00'+str(bgNum)+'.jpeg')
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:
                    numIsON = False
                else:
                    numIsON = True
                    
            if panBg.x + panBg.width > event.pos[0] > panBg.x and panBg.y + panBg.height > event.pos[1] > panBg.y:
                bgNum += 1
                bgNum = bgNum % 3 + 1
                bg_img_path = os.path.join(os.path.dirname(sys.argv[0]), 'bg00'+str(bgNum)+'.jpeg')
                
            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')
    
    if numIsON == True:
        numBt.changeText('隐藏编号')
    else:
        numBt.changeText('显示编号')
    numBt.draw(screen, 'blue')
    
    panBg.draw(screen, 'black')
    
    #消息
    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 = numFont.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()

 

截图:

 

 

 

 

posted @ 2024-08-26 14:00  河北大学-徐小波  阅读(9)  评论(0编辑  收藏  举报