我正在尝试使用嵌套循环和Python创建棋盘。我很难弄清楚如何用黑色填充特定的盒子以及如何创建64个盒子。到目前为止,我的编码是:
import turtle
t = turtle.Turtle()
t.speed(0)
t.penup()
t.goto(0, 0)
t.pendown()
for j in range(-150, 100, 50):
for i in range(-150, 150, 50):
t.penup()
t.goto(i, j)
t.pendown()
t.begin_fill()
for k in range(4):
t.forward(50)
t.left(90)
t.color("black")
t.end_fill()
for j in range(-100, 150, 50):
for i in range(-100, 150, 50):
t.penup()
t.goto(i, j)
t.pendown()
t.begin_fill()
for k in range(4):
t.forward(50)
t.left(90)
t.end_fill()
t.hideturtle()
turtle.done()
这将达到目的:
import turtle
def drawSquare(turtule, isBlack = False):
if isBlack:
t.begin_fill()
for k in range(4):
t.forward(50)
t.left(90)
t.color("black")
t.end_fill()
t = turtle.Turtle()
t.speed(0)
t.penup()
t.goto(0, 0)
t.pendown()
lastWhite = False
for j in range(-150, 250, 50):
lastWhite = not lastWhite
for i in range(-150, 250, 50):
t.penup()
t.goto(i, j)
t.pendown()
if lastWhite:
drawSquare(t, True)
lastWhite = False
else:
drawSquare(t)
lastWhite = True
t.hideturtle()
turtle.done()
编辑:此代码不使用该drawSquare
方法
import turtle
t = turtle.Turtle()
t.speed(0)
t.penup()
t.goto(0, 0)
t.pendown()
lastWhite = False
for j in range(-150, 250, 50):
lastWhite = not lastWhite
for i in range(-150, 250, 50):
t.penup()
t.goto(i, j)
t.pendown()
if lastWhite:
t.begin_fill()
for k in range(4):
t.forward(50)
t.left(90)
t.color("black")
t.end_fill()
lastWhite = False
else:
for k in range(4):
t.forward(50)
t.left(90)
t.color("black")
lastWhite = True
t.hideturtle()
turtle.done()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句