我在用python 3.2.2turtle编程。我可以让乌龟跟着我的光标当我咔哒声,但现在我有困难改变乌龟的外观。在我的代码中,你会看到一个坦克,我希望坦克的图像是我的乌龟。
这是我的代码:
#importing modules
from turtle import Turtle
from turtle import *
#Setting up variables
unVar1 = 25
unVar2 = 100
unVar3 = 90
unVar4 = 150
unVar5 = -30
unVar6 = 75
unVar7 = 50
screen = Screen() # create the screen
#first part in making the turtle move
turtle = Turtle()
t = Turtle() # create the first turtle
t2 = Turtle() # create the second turtle
screen.onscreenclick(turtle.goto) # set up the callback for moving the first turtle
#defining shapes and objects
def drawSquare(t , xPrime, yPrime, sideLength):
t.up()
t.hideturtle()
t.goto(xPrime, yPrime)
t.setheading(270)
t.down()
for count in range(4):
t.forward(sideLength)
t.left(90)
t.end_fill()
def drawRectangle(t, x2, y2, sideLength1, sideLength2):
t.up()
t.hideturtle()
t.goto(x2, y2)
t.setheading(270)
t.down()
for count in range(2):
t.forward(sideLength1)
t.left(90)
t.forward(sideLength2)
t.left(90)
t.end_fill()
def drawTank():
t.pencolor("black")
t.fillcolor("gray")
t.begin_fill()
tire1 = drawRectangle(t, int("10"), unVar1, unVar6, int("30")) #Tire
t.begin_fill()
tire2 = drawRectangle(t, int("110"), unVar1, unVar6, int("30")) #Tire
t.begin_fill()
tire3 = drawRectangle(t, int("110"), unVar2, unVar6, int("30")) #Tire
t.begin_fill()
tire4 = drawRectangle(t, int("10"), unVar2, unVar6, int("30")) #Tire
t.pencolor("gray")
t.fillcolor("black")
t.begin_fill()
bodyTank = drawRectangle(t, int("20"), unVar3, int("130"), int("110"))
t.begin_fill()
gunTank = drawRectangle(t, int("65"), unVar4, int("100"), int("20")) #Gun
t.begin_fill()
exhaustTank = drawRectangle(t, int("50"), unVar5, int("20"), int("10"))
t.fillcolor("red")
t.begin_fill()
turretTank = drawSquare(t, int("50"), unVar7, int("50")) #Turret
t.end_fill()
drawTank()
screen.mainloop() # start everything running
你可以用你的代码创建一个坦克光标,你只需要重新排列它。绘图功能需要创建多边形,而不是直接绘制到屏幕上。下面将创建您的坦克光标,并驱动它围绕屏幕一点。请参阅
tankCursor()
上关于如何也可以使用固定多边形的注释--您不必制作位图图像来执行此操作:由于坦克是您使用turtle创建的一个形状,您只需拍摄坦克的屏幕快照,然后使用turtle模块的
register_shape
和shape
函数将该屏幕快照设置为乌龟的形状,如下所示:但是,如果您想做一些更难的事情,可以使用上面所示的
turtle.register_shape()
方法,但是不提供某些图像的路径,而是必须提供名称,然后提供一些坐标来创建形状。简而言之,其语法为:不过,鉴于你的坦克已经有多复杂,这将是非常乏味的,所以我建议继续采用上述方法,你只需拍摄坦克的截图,并将截图用作海龟的形状。
另外,我发现你的代码有一些问题:
以下内容:
您正在导入turtle模块两次。没必要这样!
from turtle import *
已经导入Turtle()
函数,因此不需要第一个导入命令。因此,将import命令更改为仅:当用户点击屏幕上的某个地方时,你的乌龟会在任何地方创建一条线。有办法避免这种情况。然而,我不知道你是否想要这个,但是如果你想要并且决定保留它,它确实会导致很多行去他们不应该去的地方,并且最终可能开始占用大量内存,直到你的程序崩溃。所以我确实建议你采取这一步,但你是否采取这一步取决于你自己。但是,如果决定执行此步骤,则要开始,请在
t2 = Turtle()
之后定义以下函数:然后改变:
致:
就这样!我希望这有帮助!:)
相关问题 更多 >
编程相关推荐