我们现在可以在任意位置绘制任意颜色的图形了, 那么如何绘制成组的图形呢?
首选, 我们从绘制一个3列2行的组开始
(1) 定义2个变量, 用来定义组的大小(宽3行, 高2行)
BOARD_WIDTH = 3
BOARD_HEIGHT = 2
(2) 确定图形的空间位置
BOXSIZE = 40 # 每个图形框大小
GAPSIZE = 10 # 图形之间的间隙大小
(3) 定义图形组绘制的边界位置(图形组的左上角起始位置), 这样不管设置了多大的图形组, 都可以自动调整到画面中央位置
XMARGIN = int((WINDOW_WIDTH - BOARD_WIDTH * (BOXSIZE + GAPSIZE)) / 2)
YMARGIN = int((WINDOW_HEIGHT - BOARD_HEIGHT * (BOXSIZE + GAPSIZE)) /2)
(4) 创建一个函数,能够根据图形的行列位置转换为它在屏幕中的坐标(注意行列位置从0,0开始)
def left_top_coords_of_box(boxx, boxy):
# Convert board coordinates to pixel coordinates
left = boxx * (BOXSIZE + GAPSIZE) + XMARGIN
top = boxy * (BOXSIZE + GAPSIZE) + YMARGIN
return left, top
(5) 结合上面的内容, 就可以在画面中央画出图形组, 让我们试着画一组红色的甜甜圈.
完整代码(main.py)
# Memory Puzzle
import random, pygame, sys
from pygame.locals import *
# 配置基础 ------------------------------------------------------------
FPS = 30 # 设置帧数为30
WINDOW_WIDTH = 640 # 窗口宽度640像素
WINDOW_HEIGHT = 480 # 窗口告诉480像素
BOARD_WIDTH = 3 # 每行有3个图形
BOARD_HEIGHT = 2 # 每行有2个图形
BOXSIZE = 40 # 图形范围
GAPSIZE = 10 # 每个图形之间的间隔
# 左边边缘位置
XMARGIN = int((WINDOW_WIDTH - BOARD_WIDTH*(BOXSIZE+GAPSIZE)) / 2)
# 顶部边缘位置
YMARGIN = int((WINDOW_HEIGHT - BOARD_HEIGHT*(BOXSIZE+GAPSIZE)) /2 )
# 游戏中需要用到的颜色设置 -----------------------------------------------
# R G B 颜色
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)
PUPPLE = (255,0,255)
CYAN = (0,255,255)
BGCOLOR = NAVYBLUE # 背景色设置为navyblue
# 工具函数 -------------------------------------------------------------
def left_top_coords_of_box(boxx, boxy):
# 将图形行列位置转换为屏幕上的像素坐标
left = boxx * (BOXSIZE + GAPSIZE) + XMARGIN
top = boxy * (BOXSIZE + GAPSIZE) + YMARGIN
return left, top
# 定义main函数 ---------------------------------------------------------
def main():
pygame.init() # pygame初始化
fpsclock = pygame.time.Clock()
displaysurf = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("Memory Game") # 设置窗口标题
displaysurf.fill(BGCOLOR)
while True: # 游戏主题循环
displaysurf.fill(BGCOLOR) # 用背景色填充窗口
for event in pygame.event.get(): # 获取游戏事件
if event.type == QUIT:
pygame.quit()
sys.exit()
# 下面的代码用来展示如何绘制一组图形 ------------------------------------------
quarter = int(BOXSIZE * 0.25) # syntax suger
half = int(BOXSIZE * 0.5)
for left, top in ((0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)):
left, top = left_top_coords_of_box(left, top)
pygame.draw.circle(displaysurf, RED, (left + half, top + half),
half - 5)
pygame.draw.circle(displaysurf, BGCOLOR, (left + half, top + half),
quarter - 5)
# ---------------------------------------------------------------
pygame.display.update()
fpsclock.tick(FPS)
if __name__ == '__main__':
main()
网友评论