在Python中使用Turtle绘制棋盘
Turtle是Python中的一个内建模块。它提供了使用屏幕(纸板)和Turtle(笔)的绘画。为了在屏幕上画东西,我们需要移动Turtle(笔)。为了移动Turtle,有一些函数,如forward()、backward()等。
绘制棋盘的步骤如下:
- 导入Turtle并制作一个物体。
- 设置屏幕尺寸和Turtle位置。
- 定义一个方法来画一个正方形
- 在另一个循环下调用该方法8次,以替代颜色进行8次。
- 隐藏Turtle对象。
以下是实现。
# import turtle package
import turtle
# create screen object
sc = turtle.Screen()
# create turtle object
pen = turtle.Turtle()
# method to draw square
def draw():
for i in range(4):
pen.forward(30)
pen.left(90)
pen.forward(30)
# Driver Code
if __name__ == "__main__" :
# set screen
sc.setup(600, 600)
# set turtle object speed
pen.speed(100)
# loops for board
for i in range(8):
# not ready to draw
pen.up()
# set position for every row
pen.setpos(0, 30 * i)
# ready to draw
pen.down()
# row
for j in range(8):
# conditions for alternative color
if (i + j)% 2 == 0:
col ='black'
else:
col ='white'
# fill with given color
pen.fillcolor(col)
# start filling with colour
pen.begin_fill()
# call method
draw()
# stop filling
pen.end_fill()
# hide the turtle
pen.hideturtle()
# This code is contributed by Deepanshu Rustagi.