代码:
#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()
截图: