下午好,
我正在使用海龟模拟病毒爆发。我想出了以下代码,我的问题将在代码之后:
import turtle
import random
import time
def make_population(amount):
"""
Creates a list representing a population with a certain amount of people.
"""
population = []
for person in range(amount):
population.append(turtle.Turtle())
for person in population:
person.shape("circle")
person.shapesize(0.2)
return population
def random_move(person):
"""
Makes a turtle move forward a random amount and then turn a random amount.
"""
person.forward(random.randint(0,20))
person.right(random.randint(-180,180))
def check_boundary(person):
"""
Checks if a turtle is still within the given boundaries.
"""
if -250 <= person.xcor() <= 250 and -250 <= person.ycor() <= 250:
return
person.setpos(random.randint(-200,200),random.randint(-200,200))
def infect_random(population):
"""
Gets a random item from the population list and turns one red
"""
infected = random.choice(population)
infected.color("red")
return infected
def infect_person(person):
"""
Makes the turtle infected
"""
infected_person = person.color("red")
return infected_person
def simulation(amount, moves = 0):
"""
Simulates a virus outbreak
"""
border = 500
window = turtle.Screen()
turtle.setup(500,500)
turtle.tracer(0)
population = make_population(amount)
for person in population:
person.penup()
person.setpos(random.randint(-250,250),random.randint(-250,250))
turtle.update()
infected = infect_random(population)
for move in range(moves):
turtle.tracer(0)
for person in population:
random_move(person)
if person.distance(infected) < 50:
infect_person(person)
check_boundary(person)
turtle.update()
time.sleep(0.5)
window.exitonclick()
因此,当模拟开始时,我会感染 1 个随机人,如果其他海龟靠近,例如在 50 像素内,它们也会被感染并变成红色。然而,这些新“感染”的乌龟不会感染其他乌龟,因为与最初的乌龟相比,它们没有“感染”。我曾尝试将其更改为受感染的 = infect_person(person) 但这只会给我一个错误。我现在被困了一段时间,想知道是否有人可以提供帮助。我还考虑过制作两个列表:人口和感染人口也许可以解决我的问题,但我无法弄清楚如何在我的其余代码中实现它。
提前致谢