迷宫生成器by李兴球@2020/3/9

如本文章标有价格,需议价或其它事情商议请加微信pythonxia

"""
   迷宫生成器by李兴球@2020/3/9
"""
from turtle import *
from PIL import Image

def make_image(width,height,color=(255,0,0,255),border=2,bordercolor=(0,0,0,255)):
    """本函数用Image生成一个RGBA格式的图像,然后如果border不是0,则加边框。
       width:图像宽度,height:图像高度,color:填充颜色
       border:边框像素量,bordercolor:边框像素的颜色,返回图形对象。
    """
    pic = Image.new('RGBA',(width,height),color=color)
    if border > 0 :
        for x in range(width):
            for h in range(border):
                pic.putpixel((x,h),bordercolor)
                pic.putpixel((x,height-h-1),bordercolor)
        for y in range(height):
            for h in range(border):
                pic.putpixel((h,y),bordercolor) 
                pic.putpixel((width-h-1,y),bordercolor)
    return pic

def make_maze(mazefile,brickfilename):
    """根据mazefile描述的信息用brickfilename图形铺设迷宫"""
    im = Image.open(brickfilename)
    imgwidth,imgheight = im.size
                    
    f = open(mazefile)
    c = f.read()
    f.close()

    lines = c.split('\n')
    rows = len(lines)
    cols = len(lines[0])
    width = imgwidth * cols
    height = imgheight * rows

    screen = Screen()
    screen.delay(0)
    screen.setup(width,height)
    screen.addshape(brickfilename,Shape("image", screen._image(brickfilename)))

    square = Turtle(brickfilename,visible=False)
    square.penup()
    square.speed(0)
    square.goto(-width/2+imgwidth/2,height/2 - imgheight/2)
    nullcors = []
    for r in range(rows):
        for c in range(cols):
           if lines[r][c] == '+':
               square.stamp()
           else:
               nullcors.append(square.pos())
           square.fd(imgwidth)
        square.bk(width)
        square.sety(square.ycor()-imgheight)
    return screen,square,nullcors

if __name__ == "__main__":

    pic = make_image(50,50)
    pic.save('c:/a.png')
    screen,square,nullcors = make_maze('maze.txt','c:/a.png')
    for x,y in nullcors:
        square.goto(x,y)
        square.dot(5,'blue')

本站所有作品,教程等皆为原创,版权所有。只供个人及单位内部研究使用,对外展示或传播必需经本站同意,且注明来自本站。培训机构等用本站资源培训学生,需经本站授权。一旦付款,表示同意本站知识付费原则:数字商品,不支持退款。亦可直接向微信号scratch8付款购买。入住QQ群:225792826 和爱好者共同交流,并且能下载免费提供的Python资源(需提供真实姓名才可入群)
李兴球的博客_Python创意编程技术前沿_pygame » 迷宫生成器by李兴球@2020/3/9
scratch

学本领,探索更大的世界!

李兴球博客 风火轮编程主页