绘制棋盘式iPython?

时间:2016-01-11 05:41:28

标签: python-3.x turtle-graphics

我正在尝试绘制一个检查板。以下失败。我错在哪里?

import turtle

side = 40

for i in range(8):
    turtle.backward(side)
    turtle.right(90)
    turtle.forward(side)
    turtle.left(90)
for i in range(8):
    if (i % 2 == 0 and  i % 2 == 0) or (i % 2 != 0 and i % 2 != 0):
        turtle.begin_fill()
for i in range(4):
    turtle.forward(side)
    turtle.left(90)
    turtle.end_fill()
    turtle.forward(side)

PS:阅读有类似问题,但代码不同。

1 个答案:

答案 0 :(得分:0)

绘制棋盘的最简单方法是绘制9条平行的水平和垂直线,然后填充其他每个小方块。但是tk和tkinter和龟没有像某些绘图程序那样的泛滥功能。

我决定我需要更多的乌龟练习,并使用不同的计划写下以下工作:绘制棋盘的轮廓,然后添加32个实心方块。

import turtle as t

def moveto(x, y):
    "Move turtle with pen up."
    t.penup()
    t.goto(x, y)
    t.pendown()

def square(size):
    "Draw square of size, ending as started."
    for i in range(4):
        t.forward(size)
        t.left(90)

def check(x, y, size):
    "Draw filled check at x, y of sides size."
    moveto(x, y)
    t.begin_fill()
    square(size)
    t.end_fill()


side = 40  # pixel size of squares
ll = -(4 * side)  # lower left of board

# turtle starts at 0,0 (center of screen) facing right)
# move to lower left corner of checkerboard
moveto(ll, ll)
# draw outline of board
square(8 * side)

# draw 32 filled squares
t.fillcolor('red')
for row in range(8):
    y = ll + row * side
    offset = row % 2
    for col in range(0 + offset, 8+offset, 2):
        x = ll + col * side
        check(x, y, side)

我逐渐开发了这个,从外部广场开始。我接下来添加了一个填充的方块,然后是其余的。我按照我的方式开发了小实用功能,因为我注意到重复代码。

您仍然应该根据自己的计划编写自己的代码。