你好!现在我们正尝试使用面向对象的编程来制作和野兔的比赛。我们使用python3在jupyter notebook中编码。这就是我们目前所拥有的。
这是代码的第一部分,似乎我们让动物移动的方式是使用提前位置方法,但我们不知道放什么来让它们移动。这将根据动物对速度和午睡时间的定义,将动物的位置提前一秒钟。
class animal:
time = 0
def __init__(self, name, species, speed, napStart, napDuration, currentPosition):
self.name = str(name)
self.species = str(species)
self.speed = int(speed)
self.napStart = int(napStart)
self.napDuration = int(napDuration)
self.currentPosition = int(currentPosition)
def __str__(self):
return str(self.name) + " " + str(self.species) + " " + str(self.speed) + " " + str(self.napStart) + " " + str(self.napDuration) + " " + str(self.currentPosition)
def getName(self):
return self.name
def getSpeed(self):
return self.speed
def getNapStart(self):
return self.napStart
def getNapDuration(self):
return self.napDuration
def getCurrentPosition(self):
return self.currentPosition
def getSpecies(self):
return self.species
def advancePosition():
pass
def setSpeed(self, newSpeed):
self.speed = newSpeed
def setNapStart(self, newNapStart):
self.napStart = newNapStart
def setNapDuration(self, newNapDuration):
self.napDuration = newNapDuration
def setCurrentPosition(self, newCurrentPosition):
self.currentPosition = newCurrentPosition
然后我们有比赛代码,它还没有工作,因为我不知道如何让他们首先移动
class Race:
def __init__(self, eventName, distance, contestant1, contestant2):
self.eventName = eventName
self.distance = distance
self.contestant1 = contestant1
self.contestant2 = contestant2
def __str__(self):
return str(self.eventName) + " " + str(self.distance) + " " + str(self.contestant1) + " " + str(self.contestant2)
def getEventName(self):
return self.eventName
def getDistance(self):
return self.distance
def runRace(self):
pass
我最后拥有的只是测试动物,所以你知道它们是做什么的?
tortoise = animal("tort", "tortoise", 2, 0, 0, 0)
hare = animal("harry", "hare", 10, 5, 20, 0)
这是针对比赛代码的
race1 = Race("the race", 30, tortoise, hare)
非常感谢您的帮助,如果您需要更多信息,我完全可以为您提供:)
def runRace(self):
time = 0
while self.contestant1.getCurrentPosition() < self.getDistance() and self.contestant2.getCurrentPosition() < self.getDistance():
time += 1
if self.contestant2.getNapStart() > time or self.contestant2.getNapStart() + self.contestant2.getNapDuration < time:
self.contestant1.advancePosition()
self.contestant1.advancePosition()
if self.contestant1.getCurrentPosition > self.contestant2.getCurrentPosition:
return self.contestant1
else:
return self.contestant2
def advancePosition():
self.currentPosition += self.getSpeed()
winner = race1.runRace()
print(winner.getName())
小心,在此示例代码中只有参赛者 2 可以打盹(应该始终是野兔(
该方法可能只是将动物的速度advancePosition(self)
添加到位置上(即每秒行进 3 个单位,因此在 1 秒内他的位置现在将是 3(。只需每次更新都调用此值。
我不确定"小睡"是为了什么,或者这场比赛的逻辑是什么,但这应该是一个开始。