当前位置: 首页 > article >正文

Pygame实现记忆拼图游戏7

2.5 绘制线条

如果图案的形状是线条,则使用图10所示的代码进行绘制。

图10 绘制线条的代码

线条的图案如图11所示。

图11 线条图案

其中,图10中第93行代码判断形状是否是线条,如果是,则第94行代码通过for循环绘制图11所示的线条;第95-96行代码用于绘制线条图案的左上部分;第97-99行代码用户绘制线条图案的右下部分。

2.6 绘制椭圆

如果图案的形状是椭圆,则使用图12所示的代码进行绘制。

图12 绘制椭圆的代码

椭圆的图案如图13所示。

图13 椭圆图案

图12的第100行代码判断形状是否是椭圆,如果是,第101行代码调用pygame.draw.ellipse()函数绘制椭圆,第102行代码表示包含这个椭圆的长方形左上角横纵坐标left、top+quarter以及该长方形的宽度BOXSIZE和高度half。

3 绘制游戏的所有图案

在《Pygame实现记忆拼图游戏5》中提到,通过自定义函数drawBoard()绘制游戏的所有图案,该函数在main()中调用。在drawBoard()函数中,会通过图案状态数据revealed绘制游戏图案,当图案状态数据是False时,则在该位置处绘制图案的背面。接下来继续编写drawBoard()函数代码,当图案状态数据revealed是True时,则在该位置调用drawIcon()绘制相应的图案,代码如图14所示。

图14 drawBoard()函数的代码

其中,59-61行代码为已经实现的绘制图案背面的代码;第62-64行为新添加代码,第62行判断revealed[boxx][boxy]是否是True,如果是,则第63行代码获取该图案的形状shape和颜色color;第64行代码根据图案的形状、颜色以及位置绘制该图案。

通过调试代码,将revealedBoxes的第二个元素全部设置为True,即显示游戏图案的第二列,代码如图15所示。

图15 调试效果

4 完整代码

以上提到的完整代码如下所示。

import pygame
import os
from pygame.locals import *
import random

def main():
    global DISPLAYSURF
    DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH,WINDOWHEIGHT))
    pygame.display.set_caption('Memory Puzzle')
    
    mainBoard = getRandomizedBoard()
    revealedBoxes = generateRevealedBoxesData(False)
    for i in range(BOARDHEIGHT):#显示图案中的第二列
        revealedBoxes[1][i] = True#13-14行为调试代码,需删除
    startGameAnimation(mainBoard)
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                os.sys.exit()

        DISPLAYSURF.fill(BGCOLOR)
        drawBoard(mainBoard, revealedBoxes)
        pygame.display.update()

def getRandomizedBoard():
    icons = []
    for color in ALLCOLORS:
        for shape in ALLSHAPES:
            icons.append( (shape, color) )
            
    random.shuffle(icons) 
    numIconsUsed = int(BOARDWIDTH * BOARDHEIGHT / 2) 
    icons = icons[:numIconsUsed] * 2 
    random.shuffle(icons)

    board = []
    for x in range(BOARDWIDTH):
        column = []
        for y in range(BOARDHEIGHT):
            column.append(icons[0])
            del icons[0] 
        board.append(column)
    return board

def startGameAnimation(board):
    coveredBoxes = generateRevealedBoxesData(False)
    drawBoard(board, coveredBoxes)

def leftTopCoordsOfBox(boxx, boxy):
    left = boxx * (BOXSIZE + GAPSIZE) + XMARGIN
    top = boxy * (BOXSIZE + GAPSIZE) + YMARGIN
    return (left, top)

def drawBoard(board, revealed):
    for boxx in range(BOARDWIDTH):
        for boxy in range(BOARDHEIGHT):
            left, top = leftTopCoordsOfBox(boxx, boxy)
            if not revealed[boxx][boxy]:
                pygame.draw.rect(DISPLAYSURF, BOXCOLOR, \
                                 (left, top, BOXSIZE, BOXSIZE))
            else:
                shape, color = getShapeAndColor(board, boxx, boxy)
                drawIcon(shape, color, boxx, boxy)
                
def generateRevealedBoxesData(val):
    revealedBoxes = []
    for i in range(BOARDWIDTH):
        revealedBoxes.append([val] * BOARDHEIGHT)
    return revealedBoxes

def getShapeAndColor(board, boxx, boxy):
    return board[boxx][boxy][0], board[boxx][boxy][1]
def drawIcon(shape, color, boxx, boxy):
    quarter = int(BOXSIZE * 0.25) 
    half =    int(BOXSIZE * 0.5)  

    left, top = leftTopCoordsOfBox(boxx, boxy) 
    if shape == DONUT:
        pygame.draw.circle(DISPLAYSURF, color, \
                           (left + half, top + half), half - 5)
        pygame.draw.circle(DISPLAYSURF, BGCOLOR, \
                           (left + half, top + half), quarter - 5)
    elif shape == SQUARE:
        pygame.draw.rect(DISPLAYSURF, color, \
            (left + quarter, top + quarter, BOXSIZE - half, BOXSIZE - half))
    elif shape == DIAMOND:
        pygame.draw.polygon(DISPLAYSURF, color, \
                            ((left + half, top), \
                             (left + BOXSIZE - 1, top + half), \
                             (left + half, top + BOXSIZE - 1), \
                             (left, top + half)))
    elif shape == LINES:
        for i in range(0, BOXSIZE, 4):
            pygame.draw.line(DISPLAYSURF, color,\
                             (left, top + i), (left + i, top))
            pygame.draw.line(DISPLAYSURF, color, \
                             (left + i, top + BOXSIZE - 1), \
                             (left + BOXSIZE - 1, top + i))
    elif shape == OVAL:
        pygame.draw.ellipse(DISPLAYSURF, color, \
                            (left, top + quarter, BOXSIZE, half))
pygame.init()
WINDOWWIDTH = 640 
WINDOWHEIGHT = 480

BOARDWIDTH = 10 
BOARDHEIGHT = 7
assert (BOARDWIDTH * BOARDHEIGHT) % 2 == 0, \
           'Board needs to have an even number of boxes for pairs of matches.'

BOXSIZE = 40
GAPSIZE = 10
XMARGIN = int((WINDOWWIDTH - (BOARDWIDTH * (BOXSIZE + GAPSIZE))) / 2)
YMARGIN = int((WINDOWHEIGHT - (BOARDHEIGHT * (BOXSIZE + GAPSIZE))) / 2)

GRAY     = (100, 100, 100)
NAVYBLUE = ( 60,  60, 100)
WHITE    = (255, 255, 255)
RED      = (255,   0,   0)
GREEN    = (  0, 255,   0)
BLUE     = (  0,   0, 255)
YELLOW   = (255, 255,   0)
ORANGE   = (255, 128,   0)
PURPLE   = (255,   0, 255)
CYAN     = (  0, 255, 255)

DONUT = 'donut'
SQUARE = 'square'
DIAMOND = 'diamond'
LINES = 'lines'
OVAL = 'oval'

BGCOLOR = NAVYBLUE
BOXCOLOR = WHITE

ALLCOLORS = (RED, GREEN, BLUE, YELLOW, ORANGE, PURPLE, CYAN)
ALLSHAPES = (DONUT, SQUARE, DIAMOND, LINES, OVAL)
assert len(ALLCOLORS) * len(ALLSHAPES) * 2 >= BOARDWIDTH * BOARDHEIGHT, \
                "Board is too big for the number of shapes/colors defined."

if __name__ == '__main__':
    main()


http://www.kler.cn/a/589679.html

相关文章:

  • 接口请求限制自定义注解
  • 机器学习核心概念解读
  • Webpack构建流程详解优化前端性能\Dev-Server与Proxy\网络攻击\HMR
  • 深入解析 Spring Boot 中的 FailureAnalyzer
  • C++菱形继承内存模型
  • ONENET数据可视化命令框下发命令使用
  • 内网环境安装dlv,本地远程调试go
  • 自动化实施的常用元件有哪几种?
  • hadoop-配置安装jdk
  • Linux目录结构以及文件操作
  • IDEA的相关配置
  • 孤儿进程与僵尸进程:Linux进程管理中的“隐形杀手”与“无主孤儿”
  • 蓝桥杯 之 数学规律求解
  • React:React主流组件库对比
  • 【数据库】Data Model(数据模型)数据模型分析
  • AGI大模型(8):提示词的安全与防护
  • Redis 持久化机制:AOF 与 RDB 详解
  • 使用Ollama本地部署DeepSeek
  • (hash表+vector 数位和相等数对的最大和)leetcode 2342
  • CUDA多线程