如何使用类在Python中初始化多只乌龟 [英] How to initialize multiple turtles in Python with classes

查看:54
本文介绍了如何使用类在Python中初始化多只乌龟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的初学者,而且是Stack Exchange的新手.我正在尝试编写一个程序,该程序在一个正方形内移动5只海龟.我有满足我需求的代码,但是这很繁琐,我想使用类来初始化我所有的海龟,而不是一个一个地完成.我只希望它们以随机坐标和随机标题开始.

I am a beginner at Python and I'm new to Stack Exchange. I'm trying to write a program that has 5 turtles moving within a square. I've got code that does what I want, but it's tedious and I'd like to initialize all my turtles using classes instead of doing it one by one. I just want them to start out at random coordinates and with a random heading.

我的代码存在问题

  • 屏幕上仅显示一只乌龟.在下面的代码中定义了两个.

  • Only one turtle is shown on screen. Two are defined in the code below.

未初始化乌龟的航向和坐标.

The turtle's heading and coordinates aren't being initialized.

这是我尝试过的代码:

import numpy as np
from turtle import *

# setting up screen
reset()
screensize(550)
Screen().bgcolor('black')
tracer(0)

# drawing box
t0 = Turtle()
t0.penup()
t0.goto(-256,-256)
t0.color('cyan')
t0.pendown()
for i in range(4):
    t0.forward(512)
    t0.left(90)
t0.ht()

# parameters
velocity = 5
iterations = 200
boxsize = 512
ranheader = np.random.random()*360
ranx = np.random.random()*boxsize
rany = np.random.random()*boxsize

class turtle_agents(Turtle):
    def _init_(self):
        self.up()
        self.seth(ranheader)
        self.setpos(ranx,rany)
        self.velocity = velocity
        self.down()

# turtle
t1 = turtle_agents()
t1.color('green')
t2 = turtle_agents()
t2.color('blue')

# turtle movement
for turtle in turtles():
    for i in range(iterations):
        turtle.forward(velocity)
        if turtle.xcor() >= 256:
            turtle.goto(-256,t0.ycor())
        elif turtle.xcor() <= -256:
            turtle.goto(256,t0.ycor())
        elif turtle.ycor() >= 256:
            turtle.goto(t0.xcor(),-256)
        elif turtle.ycor() <= -256:
            turtle.goto(t0.xcor(),256)

update()    
exitonclick()

推荐答案

屏幕上只显示一只乌龟.在下面的代码中定义了两个.乌龟的航向和坐标尚未初始化.

only one turtle shown on screen. Two are defined in the code below. the turtle's heading and coordinates aren't being initialized.

我相信问题是,您在海龟创建循环之外定义了一次随机位置和航向,因此它们都从同一位置开始,以相同的方向以相同的方向移动.IE.他们是彼此对立的.

I believe the problem is that you defined the random position and heading once, outside the turtle creation loop so they all start in the same place, move in the same direction at the same speed. I.e. they're right on top of each other.

我们不需要@BlivetWidget的显式 List 来解决此问题,因为正如您所发现的,乌龟已经保存在一个列表中,可以通过屏幕的 turtles()方法.以下是我对您的代码的修正,以解决各种问题:

We don't need @BlivetWidget's explicit List to fix the problem since, as you discovered, turtles are already maintained in a list which we can get via the screen's turtles() method. Below is my rework of your code to fix various issues:

from turtle import Screen, Turtle
from random import randrange, randint

# parameters
COLORS = ['green', 'blue', 'red', 'orange', 'white']
ITERATIONS = 500
VELOCITY = 5
BOX_SIZE = 512

# setting up screen
screen = Screen()
screen.setup(BOX_SIZE + 50, BOX_SIZE + 50)
screen.bgcolor('black')
screen.tracer(False)

# drawing box
turtle = Turtle()
turtle.hideturtle()
turtle.color('cyan')

turtle.penup()
turtle.goto(-BOX_SIZE/2, -BOX_SIZE/2)
turtle.pendown()

for _ in range(4):
    turtle.forward(BOX_SIZE)
    turtle.left(90)

# turtle
for color in COLORS:
    angle = randrange(360)
    x = randint(-BOX_SIZE/2, BOX_SIZE/2)
    y = randint(-BOX_SIZE/2, BOX_SIZE/2)

    turtle = Turtle()
    turtle.color(color)
    turtle.setheading(angle)
    turtle.penup()
    turtle.setposition(x, y)
    turtle.pendown()

# turtle movement
for _ in range(ITERATIONS):
    for turtle in screen.turtles():
        turtle.forward(VELOCITY)

        x, y = turtle.position()

        if x >= BOX_SIZE/2:
            turtle.penup()
            turtle.setx(-BOX_SIZE/2)
            turtle.pendown()
        elif x <= -BOX_SIZE/2:
            turtle.penup()
            turtle.setx(BOX_SIZE/2)
            turtle.pendown()
        elif y >= BOX_SIZE/2:
            turtle.penup()
            turtle.sety(-BOX_SIZE/2)
            turtle.pendown()
        elif y <= -BOX_SIZE/2:
            turtle.penup()
            turtle.sety(BOX_SIZE/2)
            turtle.pendown()

    screen.update()

screen.exitonclick()

我同意@BlivetWidget的观点,您无需创建类就可以将它们移至起始位置".我在上面使用了一个简单的循环.

I agree with @BlivetWidget that "you don't need to create a class just to move them to your starting positions". I use a simple loop above.

这篇关于如何使用类在Python中初始化多只乌龟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆