代码解释:
-
SandbagGame
类:num_sandbags
: 桌上的沙包数量。sandbags_in_hand
: 当前手中抓到的沙包数量。
-
throw_sandbag
方法:- 模拟将沙包抛起并落下的过程。
-
try_to_grab
方法:- 随机生成抓到的沙包数量,并更新手中沙包的数量。
-
catch_sandbag
方法:- 检查是否成功抓住落下的沙包。
-
main
函数:- 初始化游戏,处理用户输入,模拟游戏的每一轮。
运行说明:
- 输入沙包的数量后,按下回车键进行游戏。程序会模拟抛起沙包、尝试抓取桌上的沙包,并检查是否成功抓住落下的沙包。游戏结束后,你可以选择是否重新开始游戏。
import random
import time
class SandbagGame:
def __init__(self, num_sandbags):
self.num_sandbags = num_sandbags
self.sandbags_in_hand = 0
def throw_sandbag(self):
print("Throwing the sandbag into the air...")
time.sleep(1) # 模拟抛起沙包的过程
print("The sandbag is falling back down!")
def try_to_grab(self):
# 随机生成抓到的沙包数目
grabbed = random.randint(0, self.num_sandbags)
self.num_sandbags -= grabbed
self.sandbags_in_hand += grabbed
print(f"You grabbed {grabbed} sandbags. You now have {self.sandbags_in_hand} sandbags in hand.")
def catch_sandbag(self):
# 模拟抓住落下的沙包
if self.sandbags_in_hand > 0:
print("You caught the falling sandbag successfully!")
else:
print("You missed catching the falling sandbag.")
def main():
print("Welcome to the Sandbag Game!")
num_sandbags = int(input("Enter the number of sandbags on the table: "))
game = SandbagGame(num_sandbags)
while True:
input("Press Enter to throw the sandbag...")
game.throw_sandbag()
game.try_to_grab()
game.catch_sandbag()
play_again = input("Play again? (y/n): ")
if play_again.lower() != 'y':
break
if __name__ == "__main__":
main()