欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python图形工具turtle绘制国际象棋棋盘

程序员文章站 2023-11-12 08:42:16
本文实例为大家分享了python图形工具turtle绘制国际象棋棋盘的具体代码,供大家参考,具体内容如下 #编写程序绘制一个国际象棋的棋盘 import t...

本文实例为大家分享了python图形工具turtle绘制国际象棋棋盘的具体代码,供大家参考,具体内容如下

#编写程序绘制一个国际象棋的棋盘
import turtle
turtle.speed(30)
turtle.penup()
off = true
for y in range(-40, 30 + 1, 10):
 for x in range(-40, 30 + 1, 10):
 if off:
 turtle.goto(x, y)
 turtle.pendown()
 turtle.begin_fill()
 turtle.color("black")
 turtle.forward(10)
 turtle.left(90)
 turtle.forward(10)
 turtle.left(90)
 turtle.forward(10)
 turtle.left(90)
 turtle.forward(10)
 turtle.left(90)
 turtle.end_fill()
 turtle.penup()
 else:
 turtle.goto(x, y)
 turtle.pendown()
 turtle.forward(10)
 turtle.left(90)
 turtle.forward(10)
 turtle.left(90)
 turtle.forward(10)
 turtle.left(90)
 turtle.forward(10)
 turtle.left(90)
 turtle.penup()
 off = bool(int(off) - 1)
 off = bool(int(off) - 1)
turtle.hideturtle()
turtle.done()

通过函数的重用优化代码:

先建立一个usefulturtlefunctions.py 的文件夹

import turtle
#draw a square
def drawsquare():
 turtle.pendown()
 turtle.forward(10)
 turtle.left(90)
 turtle.forward(10)
 turtle.left(90)
 turtle.forward(10)
 turtle.left(90)
 turtle.forward(10)
 turtle.left(90)
 turtle.penup()

再在test中调用它

#编写程序绘制一个国际象棋的棋盘
 
import turtle
from usefulturtlefunctions import *
turtle.speed(30)
turtle.penup()
off = true
for y in range(-40, 30 + 1, 10):
 for x in range(-40, 30 + 1, 10):
 if off:
 turtle.goto(x, y)
 turtle.begin_fill()
 turtle.color("black")
 drawsquare()
 turtle.end_fill()
 turtle.penup()
 else:
 turtle.goto(x, y)
 drawsquare()
 off = bool(int(off) - 1)
 off = bool(int(off) - 1)
turtle.hideturtle()
turtle.done()

最后结果:

python图形工具turtle绘制国际象棋棋盘

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。