14.3.1 绘制场景
设计样式如图14-5所示。

图14-5 画格子
设计的宽度是800、高度是600,假如有Row = 30,Col= 40,那么每行有20,每列也有20,把格子用pygame.draw.line()函数画出来。
使用方法:line(Surface, color, start_pos, end_pos, width=1) -> Rect(https://www.daowen.com)
说明:在Surface对象上绘制一条线段,两端以方形结束。
import pygame
pygame.init()
# 窗口的宽和高
# 宽
W = 800
# 高
H = 600
size = (W, H)
# 和显示相关的使用display 创建Windows 对象
windows = pygame.display.set_mode(size)
# 设置 标题
pygame.display.set_caption('简单贪吃蛇')
# 定义是否退出
quit = True
# 游戏时间钟
clock = pygame.time.Clock()
# 1.解决:一闪而过:Pygame自上而下执行
# 使用while 解决问题
while quit:
# 2.解决卡死问题
# 游戏退出事件
events = pygame.event.get() # 获取事件
for event in events: # 遍历所有的事件
print(event) # 当退出时,显示QUIT
if event.type == pygame.QUIT: # 如果点了退出
quit = False
# 渲染:画出来
# 渲染:画出来
# (向哪里画,画什么颜色,(位置:你们那开始,w,h))
#颜色——RGB
#red=(255,0,0)
#white=(255,255,255)
#black=(0,0,0)
#pygame.draw.rect(windows,(255,255,255),(0,0,W,H))
windows.fill((255,255,255)) # 将界面设置为蓝色
for x in range(0, W, 20):
pygame.draw.line(windows,(0,0,255),(x,0),(x,600),1)
for y in range(0, H, 20):
pygame.draw.line(windows,(0,0,255),(0,y),(800,y),1)
pygame.display.update() # 必须调用update才能看到绘图显示
pygame.display.flip()
# 设置帧数
clock.tick(20)
# 退出
pygame.quit()