python代码实现抓沙包游戏

代码解释:

  1. SandbagGame

    • num_sandbags: 桌上的沙包数量。
    • sandbags_in_hand: 当前手中抓到的沙包数量。
  2. throw_sandbag 方法

    • 模拟将沙包抛起并落下的过程。
  3. try_to_grab 方法

    • 随机生成抓到的沙包数量,并更新手中沙包的数量。
  4. catch_sandbag 方法

    • 检查是否成功抓住落下的沙包。
  5. 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()
 

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值