使用Python创建20个Bot()
import random
import string
class Bot:
def __init__(self, name):
self.name = name
def generate_random_string(self, length):
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))
def greet(self):
print(f"Hello, my name is {self.name}!")
def generate_password(self):
password = self.generate_random_string(8)
print(f"My name is {self.name} and my password is {password}.")
def solve_math_problem(self):
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
operation = random.choice(['+', '-', '*', '/'])
answer = None
if operation == '+':
answer = num1 + num2
elif operation == '-':
answer = num1 - num2
elif operation == '*':
answer = num1 * num2
elif operation == '/':
answer = num1 / num2
print(f"I am {self.name} and I can solve math problems! What is {num1} {operation} {num2}?")
user_answer = float(input("Enter your answer: "))
if user_answer == answer:
print("Correct answer!")
else:
print(f"Wrong answer. The correct answer is {answer}.")
def guess_number(self):
secret_number = random.randint(1, 100)
print(f"I am {self.name} and I can guess a number! Try to guess a number between 1 and 100.")
while True:
user_guess = int(input("Enter your guess: "))
if user_guess == secret_number:
print("Congratulations! You guessed the correct number.")
break
elif user_guess < secret_number:
print("Too low. Try again!")
else:
print("Too high. Try again!")
# Creating 20 Bot objects and interacting with them
bots = []
bot_names = ['Bot1', 'Bot2', 'Bot3', 'Bot4', 'Bot5', 'Bot6', 'Bot7', 'Bot8', 'Bot9', 'Bot10', 'Bot11', 'Bot12', 'Bot13', 'Bot14', 'Bot15', 'Bot16', 'Bot17', 'Bot18', 'Bot19', 'Bot20']
for name in bot_names:
bot = Bot(name)
bots.append(bot)
for bot in bots:
bot.greet()
for bot in bots:
bot.generate_password()
for bot in bots:
bot.solve_math_problem()
for bot in bots:
bot.guess_number()
# The above code creates 20 Bot objects with names 'Bot1' to 'Bot20'. It then calls the greet() method for each bot to print a greeting message. Then, it calls the generate_password() method for each bot to generate a random password. After that, it calls the solve_math_problem() method for each bot to generate and solve a math problem. Finally, it calls the guess_number() method for each bot to play a number guessing game.
