import random标签:box,python,迷宫,window,pygame,ay,ax,line From: https://www.cnblogs.com/lld76/p/16750385.html
import sys
import pygame
# 使用pygame之前必须初始化
pygame.init()
# 参数设置
box_w, box_h = 5, 5 # 盒子宽高
window_w, window_h = 400, 400
x, y = 0, 0 #盒子起始点
# 设置主屏窗口
screen = pygame.display.set_mode((window_w, window_h))
# 设置窗口标题
pygame.display.set_caption('迷宫生成')
def line_left(ax, ay):
left1 = ax + box_w, ay
left2 = ax + box_w, ay - box_h
return left1, left2
def line_right(ax, ay):
right1 = ax, ay
right2 = ax, ay - box_h
return right1, right2
def line_up(ax, ay):
up1 = ax, ay - box_h
up2 = ax + box_w, ay - box_h
return up1, up2
def line_down(ax, ay):
down1 = ax, ay
down2 = ax + box_w, ay
return down1, down2
line_list = []
for i in range(1, int(window_w/box_h)):
for j in range(1, int(window_w/box_h)):
ax, ay = (j - 1) * box_w, i * box_h
l1, l2 = random.choice([line_down(ax, ay),line_left(ax, ay)])
line_list.append([l1, l2])
# 如果没有下列主循环代码,运行结果会一闪而过
while True:
# 更新屏幕内容
pygame.display.flip()
# #填充主窗口的背景颜色,参数值RGB(颜色元组)
screen.fill((255, 255, 255))
# 循环获取事件,监听事件
for event in pygame.event.get():
# 判断用户是否点了关闭按钮
if event.type == pygame.QUIT:
#卸载所有模块
pygame.quit()
#终止程序
sys.exit()
if event.type == pygame.KEYDOWN:
# 右移
if event.key == pygame.K_RIGHT:
t = True
if [(x + box_w, y + box_h), (x + box_w, y)] in line_list:
t = False
if (0 <= (x + box_w) < window_w) and t:
x += box_w
# 左移
elif event.key == pygame.K_LEFT:
t = True
if [(x, y + box_h), (x, y)] in line_list:
t = False
if 0 < x < window_w and t:
x -= box_w
# 上移
elif event.key == pygame.K_UP:
t = True
if [(x, y), (x + box_w, y)] in line_list:
t = False
if 0 < y < window_h and t:
y -= box_h
# 下移
elif event.key == pygame.K_DOWN:
t = True
if [(x, y + box_h), (x + box_w, y + box_h)] in line_list:
if 0 < (y + box_h) < window_h and t:
y += box_h
pygame.draw.rect(screen, (255, 0, 255), (x, y, box_w, box_h),width=0)
for l1,l2 in line_list:
pygame.draw.line(screen, (255, 0, 255), l1, l2, 2)
screen.blit(screen, (0, 0))
# 定义频率
clock = pygame.time.Clock()
# 设定刷新帧率
clock.tick(60) # 越大刷新的越快
pygame.display.update()