gpt4 book ai didi

python - 想改进简单的python代码

转载 作者:太空宇宙 更新时间:2023-11-04 05:40:49 24 4
gpt4 key购买 nike

我是 python 编程的新手。这是我要改进的代码

# Critter Caretaker
# A virtual pet to care for

class Critter(object):
"""A virtual pet"""
def __init__(self, name, hunger = 0, boredom = 0):
self.name = name
self.hunger = hunger
self.boredom = boredom

def __pass_time(self):
self.hunger += 1
self.boredom += 1

@property
def mood(self):
unhappiness = self.hunger + self.boredom
if unhappiness < 5:
m = "happy"
elif 5 <= unhappiness <= 10:
m = "okay"
elif 11 <= unhappiness <= 15:
m = "frustrated"
else:
m = "mad"
return m

def talk(self):
print("I'm", self.name, "and I feel", self.mood, "now.\n")
self.__pass_time()

def eat(self, food = 4):
print("Brruppp. Thank you.")
self.hunger -= food
if self.hunger < 0:
self.hunger = 0
self.__pass_time()

def play(self, fun = 4):
print("Wheee!")
self.boredom -= fun
if self.boredom < 0:
self.boredom = 0
self.__pass_time()

def __str__(self):
rep = "Attribut value is\n"
rep += str(self.hunger) + "\n" + str(self.boredom) + "\n"
return rep


def main():
crit_name = input("What do you want to name your critter?: ")
crit = Critter(crit_name)

choice = None
while choice != "0":
print \
("""
Critter Caretaker

0 - Quit
1 - Listen to your critter
2 - Feed your critter
3 - Play with your critter
""")

choice = input("Choice: ")
print()

# exit
if choice == "0":
print("Good-bye.")

# listen to your critter
elif choice == "1":
crit.talk()

# feed your critter
elif choice == "2":
crit.eat()

# play with your critter
elif choice == "3":
crit.play()

# secret option
elif choice == "!":
print(crit)

# some unknown choice
else:
print("\nSorry, but", choice, "isn't a valid choice.")

main()
("\n\nPress the enter key to exit.")

你看这是一个木偶,它表现出他的心情和寻找你来喂他和他一起玩。每次木偶说话、吃饭或玩耍时,counter pass_time 都会提升 2 级。属性食物乐趣总是有相同的数字直接影响心情。我想让用户可以输入可以影响木偶情绪的食物量和时间。为什么我不能这样做

    def eat(self, food):
print("Brruppp. Thank you.")
self.hunger -= food
if self.hunger < 0:
self.hunger = 0
self.__pass_time()

def play(self, fun):
print("Wheee!")
self.boredom -= fun
if self.boredom < 0:
self.boredom = 0
self.__pass_time()

还有这个

        choice = input("Choice: ")
print()

# exit
if choice == "0":
print("Good-bye.")

# listen to your critter
elif choice == "1":
crit.talk()

# feed your critter
elif choice == "2":
food = int(input("How much food?: "))

crit.eat()

# play with your critter
elif choice == "3":
fun = int(input("How much time?: "))

crit.play()

# secret option
elif choice == "!":
print(crit)

# some unknown choice
else:
print("\nSorry, but", choice, "isn't a valid choice.")

最佳答案

如果我理解你的问题,你似乎就快到了。让我们以 eat 函数为例。您想将 food 变量传递给要使用的类函数。如果需要,您还可以添加验证以检查输入的值是否为数字。

elif choice == "2":
food = int(input("How much food?: "))
crit.eat(food) # pass food in as a parameter

关于python - 想改进简单的python代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33984611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com