【发布时间】:2020-08-27 06:56:13
【问题描述】:
我现在学习 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 很陌生,所以我不知道该怎么做。任何人都可以帮忙吗?
提前致谢!
(我不喜欢使用 Class,因为我还没有学习 :)
【问题讨论】:
-
好吧,逻辑思考一下:如果你有 N 个人,你需要多少步数?你能想出一种优雅的方式来存储它吗? (提示:你是如何将 N 个人存储在一个变量中的?)那么,你能想出一种方法将给定的步数与正确的人相关联吗?
标签: python list for-loop count turtle-graphics