我想在Python中加入海龟图形的功能。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我想在Python中加入海龟图形的功能。相关的知识,希望对你有一定的参考价值。
我的代码让用户输入乌龟的数量,然后,它会用随机的乌龟形状和颜色来显示输入的数量。然后,它会用随机的乌龟形状和颜色来显示输入的数量。我想在我的乌龟图形代码中添加3个函数。
- "请输入乌龟的数量。"
- 通过接收龟的数量作为参数来初始化龟阵的函数。
- 最后,函数绘制乌龟
请帮帮我,这是我的代码。
import turtle
import random
myturtle,tx,ty,tcolor,tsize,tshape=[None]*6
shapelist=[]
playerturtles=[]
swidth,sheight=500,500
if __name__=='__main__':
turtle.title('Turtle list utilization')
turtle.setup(width=swidth+50,height=sheight+50)
turtle.screensize(swidth,sheight)
shapelist=turtle.getshapes()
a=int(input('Turtle Count:'))
for i in range(0,a):
random.shuffle(shapelist)
myturtle=turtle.Turtle(shapelist[0])
tx=random.randrange(-swidth/2,swidth/2)
ty=random.randrange(-sheight/2,sheight/2)
r=random.random();g=random.random();b=random.random()
tsize=random.randrange(1,3)
playerturtles.append([myturtle,tx,ty,tsize,r,g,b])
for i in range(0,a):
myturtle=playerturtles[i][0]
myturtle.color((playerturtles[i][4],playerturtles[i][5],playerturtles[i][6]))
myturtle.pencolor((playerturtles[i][4],playerturtles[i][5],playerturtles[i][6]))
myturtle.turtlesize(playerturtles[i][3])
myturtle.goto(playerturtles[i][1],playerturtles[i][2])
turtle.done()
答案
下面是使用的代码 global
变量。你应该考虑在这个函数中从全局变量中切换,阅读关于 全球性 变量。
import turtle
import random
myturtle, tx, ty, tcolor, tsize, tshape = [None] * 6
shapelist = []
playerturtles = []
swidth, sheight = 500, 500
def start_turtles():
global shapelist
turtle.title('Turtle list utilization')
turtle.setup(width=swidth + 50, height=sheight + 50)
turtle.screensize(swidth, sheight)
shapelist = turtle.getshapes()
a = int(input('Turtle Count:'))
return a
def turtle_start(a):
global myturtle
global tsize
global tx
global ty
for i in range(0, a):
random.shuffle(shapelist)
myturtle = turtle.Turtle(shapelist[0])
tx = random.randrange(-swidth / 2, swidth / 2)
ty = random.randrange(-sheight / 2, sheight / 2)
r = random.random()
g = random.random()
b = random.random()
tsize = random.randrange(1, 3)
playerturtles.append([myturtle, tx, ty, tsize, r, g, b])
def turtle_draw(a):
global myturtle
for i in range(0, a):
myturtle = playerturtles[i][0]
myturtle.color((playerturtles[i][4], playerturtles[i][5], playerturtles[i][6]))
myturtle.pencolor((playerturtles[i][4], playerturtles[i][5], playerturtles[i][6]))
myturtle.turtlesize(playerturtles[i][3])
myturtle.goto(playerturtles[i][1], playerturtles[i][2])
turtle.done()
if __name__ == '__main__':
a = start_turtles()
turtle_start(a)
turtle_draw(a)
以上是关于我想在Python中加入海龟图形的功能。的主要内容,如果未能解决你的问题,请参考以下文章