给Python乌龟一个用于乒乓球比赛的矩形

问题描述 投票:0回答:5

我试图在Python中为海龟提供一个矩形形状,但是海龟外观方法没有任何作用。 据说乌龟没有这个属性。 我能做什么?

paddle = turtle.Turtle()
paddle.shape("rectangle")

output:
turtle.TurtleGraphicsError: There is no shape named rectangle
python turtle-graphics
5个回答
2
投票

在 Python 附带的海龟模块中,您可以使用

shapesize()
来调整任何现有海龟形状选项的大小,在本例中为
'square'
。您可以在两个维度上以不同的方式拉伸或收缩它。这是一个位于屏幕中间的桨示例,其高度大于宽度,并且只能在屏幕上上下移动:

from turtle import Screen, Turtle

def drag(_, y):
    paddle.ondrag(None)
    paddle.sety(y)
    paddle.ondrag(drag)

screen = Screen()

paddle = Turtle('square')
paddle.speed('fastest')
paddle.shapesize(1, 4)
paddle.setheading(90)
paddle.penup()

paddle.ondrag(drag)

screen.mainloop()

您可以使用两只乌龟在屏幕的左侧和右侧创建这些乌龟,以进行乒乓球游戏。


1
投票

使用

shapesize
方法。它接受 2 个参数。第一个值是图形的高度将扩大多少倍,第二个值是其宽度将扩大多少倍。

海龟的默认大小是

(20, 20)
。 例如,如果您想创建一个高度为 100 像素、宽度为 20 像素的桨,则应使用以下代码。

paddle = Turtle("square")
paddle.shapesize(5, 1)

5 * 20 = 100px(高度)
1 * 20 = 20px(宽度)


0
投票

turtle.addshape(名称,形状=无) 可以通过三种不同的方式调用该函数: name 是 gif 文件的名称,shape 是 None:安装相应的图像形状。

screen.register_shape("turtle.gif")

注意 转动乌龟时图像形状不会旋转,因此它们不会显示乌龟的方向! name 是任意字符串,shape 是坐标对的元组:安装相应的多边形形状。

screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3))

你应该改变大小以获得矩形形状的乌龟! :)


0
投票

您可能应该尝试使用:

turtle.shape()

在函数中只需输入“square”。

有任何问题欢迎提问!


0
投票

我也有同样的疑问,我最终做了什么:

  1. 我让我的乌龟对象变成了“正方形”,

turtle.shape("正方形")

在我打印出它的形状作为坐标之后:

打印(turtle.get_shapepoly())

2.之后,我不断地调整坐标,直到得到想要的效果。本质上,最终结果是:

from turtle import Turtle, Screen, Shape

形状 = ((10, -40), (10, 40), (-10, 40), (-10, -40))

桨类(海龟):

def __init__(self, contour_color):
    super().__init__()
    self.new_shape(contour_color)
    self.setheading(90)

def new_shape(self, contour_color):
    screen = Screen()
    s = Shape("compound")
    poly1 = SHAPE
    s.addcomponent(poly1, "grey", outline=contour_color)
    screen.register_shape("paddle", s)
    self.shape("paddle")

我在这里留下了所使用文档的链接。希望对您有帮助!

https://docs.python.org/3/library/turtle.html#turtle.get_shapepoly 海龟图形库。描述和相关部分的链接

© www.soinside.com 2019 - 2024. All rights reserved.