python人类与宠物模拟世界代码
时间: 2023-11-04 17:11:23 浏览: 108
Python我的世界小游戏源代码
5星 · 资源好评率100%
以下是一个基于 Python 的简单的人类与宠物模拟世界代码示例:
```python
import random
class Person:
def __init__(self, name, age, gender, pet=None):
self.name = name
self.age = age
self.gender = gender
self.pet = pet
def has_pet(self):
return self.pet is not None
def adopt_pet(self, pet):
self.pet = pet
def play_with_pet(self):
if self.has_pet():
print(f"{self.name} plays with {self.pet.name}.")
self.pet.play()
else:
print(f"{self.name} doesn't have a pet to play with.")
class Pet:
def __init__(self, name, species, mood=50):
self.name = name
self.species = species
self.mood = mood
def play(self):
self.mood += random.randint(10, 20)
print(f"{self.name} is happy!")
def get_mood(self):
return self.mood
def __str__(self):
return f"{self.name} ({self.species})"
# 创建人类和宠物对象
person1 = Person("Alice", 25, "Female")
person2 = Person("Bob", 30, "Male")
pet1 = Pet("Charlie", "Dog")
pet2 = Pet("Fluffy", "Cat")
# Alice和Bob分别领养一只宠物
person1.adopt_pet(pet1)
person2.adopt_pet(pet2)
# Alice玩宠物
person1.play_with_pet()
# Fluffy的心情
print(f"{pet2.name}'s mood is {pet2.get_mood()}.")
```
这个简单的代码示例创建了两个类:`Person`和`Pet`。一个`Person`对象可以拥有一个`Pet`对象,可以通过`adopt_pet()`方法领养一只宠物,通过`play_with_pet()`方法和宠物玩耍。`Pet`对象有一个`play()`方法,可以增加心情值,另外还有一个`get_mood()`方法,用于获取当前心情值。
你可以根据自己的需求对代码进行修改和扩展。
阅读全文