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

yipeiwu_com6年前Python基础

本文实例为大家分享了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设计】。

相关文章

python中@property和property函数常见使用方法示例

本文实例讲述了python中@property和property函数常见使用方法。分享给大家供大家参考,具体如下: 1、基本的@property使用,可以把函数当做属性用 class...

python使用matplotlib绘制柱状图教程

python使用matplotlib绘制柱状图教程

Matplotlib的概念这里就不多介绍了,关于绘图库Matplotlib的安装方法:点击这里 小编之前也和大家分享过python使用matplotlib实现的折线图和制饼图效果,感兴趣...

python3 读写文件换行符的方法

最近在处理文本文件时,遇到编码格式和换行符的问题。 基本上都是GBK 和 UTF-8 编码的文本文件,但是python3 中默认的都是按照 utf-8 来打开。用不正确的编码参数打开,在...

python画双y轴图像的示例代码

很多时候可能需要在一个图中画出多条函数图像,但是可能y轴的物理含义不一样,或是数值范围相差较大,此时就需要双y轴。 matplotlib和seaborn都可以画双y轴图像。 一个例子:...

Python设计模式之模板方法模式实例详解

Python设计模式之模板方法模式实例详解

本文实例讲述了Python设计模式之模板方法模式。分享给大家供大家参考,具体如下: 模板方法模式(Template Method Pattern):定义一个操作中的算法骨架,将一些步骤延...