我现在学习python已经三个星期了,我被卡住了。 这是我的代码:(之后是我的问题)
from turtle import Screen, Turtle
from random import randint, choice
def person_characteristics(people):
"""
Gives the turtle 'person' all it's characteristics / values.
"""
for person in people:
person.shape('circle')
person.shapesize(0.2)
person.speed('fastest')
person.penup()
x = randint(-200, 200) #turtle gets a random position
y = randint(-200, 200)
person.setpos(x, y)
person.showturtle()
def population(population_size):
"""
Makes a population, by making a list of turtles (persons).
population_size = type(int)
"""
people = []
for _ in range(population_size):
people.append(Turtle(visible=False))
return people
def random_walk(person, step_size, area_size):
"""
Makes the person walk around randomly within the borders.
step_size = type(int) -> determines how big of a step each person takes.
area_size = type(int) -> determines how big the area is where the persons are in.
"""
if -area_size < person.xcor() < area_size and -area_size < person.ycor() < area_size: #if person is within the borders then it moves randomly
person.right(randint(0, 360))
person.forward(step_size)
else:
person.right(180) #if person is outside the borders it turns around
person.forward(step_size)
def infect_random(people):
"""
Random person gets infected (a red color)
people = a list of persons achieved from de function population()
"""
infected = choice(people)
infected.color('red')
return infected
screen = Screen()
people = population(100)
person_characteristics(people)
infected_people = []
initial_infected = infect_random(people)
infected_people.append(initial_infected)
counted_infections = 1
#count_steps = 0
#healed_people = []
for _ in range(10): # determines the number of steps = time
for person in people:
random_walk(person, 30, 400)
for infected_person in infected_people:
if person.pencolor() != 'red' and person.distance(infected_person) < 30: #if a person gets close to the initial infected person it also
person.color('red') #gets infected & added to the list of infected persons
infected_people.append(person)
#count_steps +=1
#if count_steps = 5:
#infected_person.color('green')
#healed_people.append(infected_person)
#infected_people.remove(infected_person)
break
count_susceptible = len(people) - len(infected_people) #counts number of susceptible people
count_infected = len(infected_people) #counts number of infected people
print(count_susceptible)
print(count_infected)
screen.exitonclick()
我想把受感染的人变成绿色(=治愈),在海龟完成5个步骤后,把它变成治愈的人(从受感染的人列表中删除)。我的想法是使用if语句来实现这一点,但是这不起作用。我的想法在上面的代码中。我知道为什么它不起作用:现在它计算每个感染者的总步数,而不是单独计算。 我认为可能有一个非常简单的解决方案,但我对python非常陌生,所以我不知道如何做到这一点。有人能帮忙吗
提前谢谢
(我不喜欢使用类,因为我还没有学会:)
您可以使用辅助数组来保存人的步数。如果使用相同的大小创建它,则可以使用索引。例如:
people=[person1,person2,person3]
人员步骤=[步骤1的步骤数,步骤2的步骤数,步骤3的步骤数]
这只是一个图形表示
但是最好使用类来完成,这样步骤的数量就作为属性包含在其中
我希望这有帮助。如果您有任何建议或问题,请告诉我
相关问题 更多 >
编程相关推荐