首页 > 解决方案 > 使用 Python 乌龟图形创建砖墙

问题描述

我对如何制作墙有一个想法,但我必须在砖块之间实现空间,并且它必须填满窗户。有人对如何最好地实施这一点有任何建议吗?我的代码是这样的:

import turtle
x1= -300
y1= 270

turtle.setup(600, 600)
turtle.speed(0)
turtle.bgcolor('black')
for y in range (1, 16):

    for x in range(10):
        turtle.penup()
        turtle.goto(x1, y1)
        turtle.pencolor('red')
        turtle.pendown()
        turtle.fillcolor('red')
        turtle.begin_fill()
        turtle.forward(50)
        turtle.left(90)
        turtle.forward(25)
        turtle.left(90)
        turtle.forward(50)
        turtle.left(90)
        turtle.forward(25)
        turtle.left(90)
        turtle.end_fill()
        x1 += 60
    if y % 2 == 0:
        x1 -= -200

    else:
        x1 = -300
        y1 -= 270

在第一行之后,y 应该自增并在第一行下方再增加一行,直到填满屏幕。

标签: pythonturtle-graphics

解决方案


即使这不是您的想法,它也应该给您一些关于如何进行的想法。它基于冲压而不是绘图,并将坐标系设置为以砖为中心:

from turtle import Screen, Turtle

CURSOR_SIZE = 20

screen = Screen()
screen.setup(600, 600)  # 12 x 24 bricks
screen.setworldcoordinates(0, 0, 12, 24)  # coordinates based on bricks
screen.bgcolor('black')

turtle = Turtle('square', visible=False)
turtle.penup()
turtle.speed('fastest')
turtle.color('black', 'red')
turtle.shapesize(25 / CURSOR_SIZE, 50 / CURSOR_SIZE, 5)  # turn cursor into brick

for y in range(24):
    turtle.setposition(-0.5 * (y % 2), y + 0.3)

    for x in range(13):  # baker's dozen due to brick skew
        turtle.stamp()
        turtle.forward(1)

screen.mainloop()

在此处输入图像描述


推荐阅读