无人变形金刚

下面是一个基本的无人变形金刚代码示例:

class Transformer:
    def __init__(self, name, vehicle_mode, robot_mode):
        self.name = name
        self.vehicle_mode = vehicle_mode
        self.robot_mode = robot_mode
        self.mode = vehicle_mode

    def transform(self):
        if self.mode == self.vehicle_mode:
            self.mode = self.robot_mode
            print(f"{self.name} transformed into robot mode.")
        elif self.mode == self.robot_mode:
            self.mode = self.vehicle_mode
            print(f"{self.name} transformed into vehicle mode.")

    def attack(self):
        if self.mode == self.vehicle_mode:
            print(f"{self.name} is in vehicle mode and cannot attack.")
        elif self.mode == self.robot_mode:
            print(f"{self.name} is attacking in robot mode.")


# 创建两个无人变形金刚对象
optimus_prime = Transformer("Optimus Prime", "Truck", "Robot")
bumblebee = Transformer("Bumblebee", "Car", "Robot")

# 测试代码
optimus_prime.transform()  # 输出:Optimus Prime transformed into robot mode.
optimus_prime.attack()     # 输出:Optimus Prime is attacking in robot mode.
optimus_prime.transform()  # 输出:Optimus Prime transformed into vehicle mode.
optimus_prime.attack()     # 输出:Optimus Prime is in vehicle mode and cannot attack.

bumblebee.transform()      # 输出:Bumblebee transformed into robot mode.
bumblebee.attack()         # 输出:Bumblebee is attacking in robot mode.
bumblebee.transform()      # 输出:Bumblebee transformed into vehicle mode.
bumblebee.attack()         # 输出:Bumblebee is in vehicle mode and cannot attack.

这段代码创建了一个Transformer类,该类具有名称、两种模式(车辆模式和机器人模式)以及当前模式的属性。类定义了transform方法用于切换模式,并且根据当前模式输出相应的消息。类还定义了attack方法,根据当前模式输出相应的攻击消息。

在测试代码中,我们创建了两个无人变形金刚对象optimus_primebumblebee。通过调用对象的方法,我们可以看到它们在不同模式下的转换和攻击行为。

你可能感兴趣的:(android)