用Python带你制作小时候玩的“大富翁”(文末赠书)

news2024/10/6 18:24:00

名字:阿玥的小东东

学习:Python、C/C++

主页链接:阿玥的小东东的博客_CSDN博客-python&&c++高级知识,过年必备,C/C++知识讲解领域博主

 

目录

首先

接下来需要定义各种类型的物业,包括普通物业、铁路、公用事业等等。

接下来需要定义一些特殊的位置,比如Jail、Free Parking、Go To Jail等等。

然后需要定义一些Chance和Community Chest卡片

最后,需要定义一个Game类

完整代码

本期推荐


首先

需要定义一个Player类来跟踪每个玩家的状态,包括姓名、当前拥有的资金、当前所处的位置以及已经购买的物业信息。此外还需要一些方法,比如移动、支付、收取资金、破产等等。

class Player:
    def __init__(self, name, money):
        self.name = name
        self.money = money
        self.position = 0
        self.properties = []
        
    def move(self, steps):
        self.position = (self.position + steps) % 40  # 地图总共40个位置
        print(self.name, 'moved to position', self.position)
        
    def pay(self, amount):
        self.money -= amount
        print(self.name, 'paid', amount, 'and now has', self.money)
        
    def receive(self, amount):
        self.money += amount
        print(self.name, 'received', amount, 'and now has', self.money)
        
    def bankrupt(self):
        print(self.name, 'is bankrupt!')

接下来需要定义各种类型的物业,包括普通物业、铁路、公用事业等等。

每种物业都有自己的名字、价格、租金等属性,同时还有一些特殊的方法,比如购买、支付租金、升级等等。

class Property:
    def __init__(self, name, cost, rent):
        self.name = name
        self.cost = cost
        self.rent = rent
        self.owner = None
    
    def pay_rent(self, player):
        player.pay(self.rent)
        
    def buy(self, player):
        player.pay(self.cost)
        player.properties.append(self)
        self.owner = player
        
    def land_on(self, player):
        if self.owner is None:
            action = input('Do you want to buy ' + self.name + ' for ' + str(self.cost) + '? (y/n) ')
            if action.lower() == 'y':
                self.buy(player)
                
        elif self.owner == player:
            print('You already own', self.name)
            
        else:
            self.pay_rent(player)
            
    def __str__(self):
        return self.name

class Street(Property):
    def __init__(self, name, cost, rent, color):
        super().__init__(name, cost, rent)
        self.color = color
        self.houses = 0
    
    def pay_rent(self, player):
        amount = self.rent[self.houses]
        player.pay(amount)
        
    def build_house(self):
        self.houses += 1
        print('Built a house on', self.name)
        self.rent = self.rent[:self.houses] + [self.rent[self.houses] * 2] + self.rent[self.houses+1:]
        
    def __str__(self):
        return super().__str__() + ' (' + self.color + ')'

class Utility(Property):
    def __init__(self, name, cost):
        super().__init__(name, cost, None)
        
    def pay_rent(self, player, steps):
        amount = steps * 10 if self.owner.utilities_owned == 1 else steps * 20
        player.pay(amount)
        
class Railroad(Property):
    def __init__(self, name, cost):
        super().__init__(name, cost, [25, 50, 100, 200])
        
    def pay_rent(self, player):
        amount = self.rent[self.owner.railroads_owned-1]
        player.pay(amount)

接下来需要定义一些特殊的位置,比如Jail、Free Parking、Go To Jail等等。

class Jail(Property):
    def __init__(self):
        super().__init__('Jail', None, None)

class FreeParking(Property):
    def __init__(self):
        super().__init__('Free Parking', None, None)

class GoToJail(Property):
    def __init__(self):
        super().__init__('Go To Jail', None, None)

然后需要定义一些Chance和Community Chest卡片

,包括描述、执行的操作以及可能涉及到的金额等等。当玩家经过Chance或Community Chest位置时,需要随机抽取一张卡片并执行对应的操作。

class Chance:
    def __init__(self, description, action, amount=0):
        self.description = description
        self.action = action
        self.amount = amount
        
    def execute(self, player, game):
        if self.action == 'move':
            player.move(self.amount)
            game.land_on(player)
        elif self.action == 'pay':
            player.pay(self.amount)
        elif self.action == 'receive':
            player.receive(self.amount)

class CommunityChest:
    def __init__(self, description, action, amount=0):
        self.description = description
        self.action = action
        self.amount = amount
        
    def execute(self, player):
        if self.action == 'move':
            player.move(self.amount)
        elif self.action == 'pay':
            player.pay(self.amount)
        elif self.action == 'receive':
            player.receive(self.amount)

最后,需要定义一个Game类

用于管理整个游戏的进程。在游戏开始时,需要随机分配玩家的位置和顺序。每一轮玩家依次行动,根据投掷的骰子数目移动到新的位置,然后执行该位置对应的操作,包括支付租金、购买物业、抽取Chance和Community Chest卡片等等。如果一个玩家资金不够支付租金或遇到其他困难而破产,则该玩家退出游戏。当只剩下一个玩家时,游戏结束,该玩家获胜。

class Game:
    def __init__(self, players, properties, chances, community_chests):
        self.players = players
        self.properties = properties
        self.chances = chances
        self.community_chests = community_chests
        
    def land_on(self, player):
        property = self.properties[player.position]
        print(player.name, 'landed on', property)
        if isinstance(property, Property):
            property.land_on(player)
        elif isinstance(property, Chance):
            card = self.chances.pop(0)
            self.chances.append(card)
            print(player.name, 'picked a chance card:', card.description)
            card.execute(player, self)
        elif isinstance(property, CommunityChest):
            card = self.community_chests.pop(0)
            self.community_chests.append(card)
            print(player.name, 'picked a community chest card:', card.description)
            card.execute(player)
        
    def play(self):
        round_num = 1
        
        while True:
            print('\n----- Round', round_num, '-----\n')
            random.shuffle(self.players)
            for player in self.players:
                print('\n---', player.name, '---\n')
                dice_roll = random.randint(2, 12)
                print(player.name, 'rolled a', dice_roll)
                player.move(dice_roll)
                self.land_on(player)
                if player.money <= 0:
                    player.bankrupt()
                    self.players.remove(player)
                
                if len(self.players) == 1:
                    self.players[0].win()
                    return
                    
            round_num += 1

完整代码

因为不可能给大家把完整代码放这里,所以剩下的大家可以自行完善

import random

class Player:
    def __init__(self, name, money):
        self.name = name
        self.money = money
        self.position = 0
        self.properties = []
        self.railroads_owned = 0
        self.utilities_owned = 0
        
    def move(self, steps):
        self.position = (self.position + steps) % 21  # 地图总共21个位置
        print(self.name, 'moved to position', self.position)
        
    def pay(self, amount):
        self.money -= amount
        print(self.name, 'paid', amount, 'and now has', self.money)
        
    def receive(self, amount):
        self.money += amount
        print(self.name, 'received', amount, 'and now has', self.money)
        
    def bankrupt(self):
        print(self.name, 'is bankrupt!')
        
    def win(self):
        print(self.name, 'wins!')

class Property:
    def __init__(self, name, cost, rent):
        self.name = name
        self.cost = cost
        self.rent = rent
        self.owner = None
    
    def pay_rent(self, player):
        player.pay(self.rent)
        
    def buy(self, player):
        player.pay(self.cost)
        player.properties.append(self)
        self.owner = player
        
    def land_on(self, player):
        if self.owner is None:
            action = input('Do you want to buy ' + self.name + ' for ' + str(self.cost) + '? (y/n) ')
            if action.lower() == 'y':
                self.buy(player)
                
        elif self.owner == player:
            print('You already own', self.name)
            
        else:
            self.pay_rent(player)
            
    def __str__(self):
        return self.name

class Street(Property):
    def __init__(self, name, cost, rent, color):
        super().__init__(name, cost, rent)
        self.color = color
        self.houses = 0
    
    def pay_rent(self, player):
        amount = self.rent[self.houses]
        player.pay(amount)
        
    def build_house(self):
        self.houses += 1
        print('Built a house on', self.name)
        self.rent = self.rent[:self.houses] + [self.rent[self.houses] * 2] + self.rent[self.houses+1:]
        
    def __str__(self):
        return super().__str__() + ' (' + self.color + ')'

class Utility(Property):
    def __init__(self, name, cost):
        super().__init__(name, cost, None)
        
    def pay_rent(self, player, steps):
        amount = steps * 10 if self.owner.utilities_owned == 1 else steps * 20
        player.pay(amount)
        
class Railroad(Property):
    def __init__(self, name, cost):
        super().__init__(name, cost, [25, 50, 100, 200])
        
    def pay_rent(self, player):
        amount = self.rent[self.owner.railroads_owned-1]
        player.pay(amount)

class Chance:
    def __init__(self, description, action, amount=0):
        self.description = description
        self.action = action
        self.amount = amount
        
    def execute(self, player, game):
        if self.action == 'move':
            player.move(self.amount)
            game.land_on(player)
        elif self.action == 'pay':
            player.pay(self.amount)
        elif self.action == 'receive':
            player.receive(self.amount)

class Tax:
    def __init__(self, description, amount):
        self.description = description
        self.amount = amount
        
    def pay(self, player):
        player.pay(self.amount)
        
    def __str__(self):
        return self.description + ' (' + str(self.amount) + ')'

class CommunityChest:
    def __init__(self, description, action, amount=0):
        self.description = description
        self.action = action
        self.amount = amount
        
    def execute(self, player):
        if self.action == 'move':
            player.move(self.amount)
        elif self.action == 'pay':
            player.pay(self.amount)
        elif self.action == 'receive':
            player.receive(self.amount)

class Game:
    def __init__(self, players, properties, chances, taxes, community_chests):
        self.players = players
        self.properties = properties
        self.chances = chances
        self.taxes = taxes
        self.community_chests = community_chests
        
    def land_on(self, player):
        property = self.properties[player.position]
        print(player.name, 'landed on', property)
        if isinstance(property, Property):
            property.land_on(player)
        elif isinstance(property, Tax):
            property.pay(player)
        elif isinstance(property, Chance):
            card = self.chances.pop(0)
            self.chances.append(card)
            print(player.name, 'picked a chance card:', card.description)
            card.execute(player, self)
        elif isinstance(property, CommunityChest):
            card = self.community_chests.pop(0)
            self.community_chests.append(card)
            print(player.name, 'picked a community chest card:', card.description)
            card.execute(player)
        
    def play(self):
        round_num = 1
        
        while True:
            print('\n----- Round', round_num, '-----\n')
            for player in self.players:
                print('\n---', player.name, '---\n')
                dice_roll = random.randint(2, 12)
                print(player.name, 'rolled a', dice_roll)
                player.move(dice_roll)
                self.land_on(player)
                if player.money <= 0:
                    player.bankrupt()
                    self.players.remove(player)
                
                if len(self.players) == 1:
                    self.players[0].win()
                    return
                    
            round_num += 1

# 创建游戏地图和物业
properties = [Property('GO', 0, None),
              Street('Mediterranean Avenue', 60, [2, 10, 30, 90, 160, 250], 'brown'),
              Chance('Advance to St. Charles Place', 'move', 11),
              Street('Baltic Avenue', 60, [4, 20, 60, 180, 320, 450], 'brown'),
              Tax('Income Tax', 200),
              Railroad('Reading Railroad', 200),
              Street('Oriental Avenue', 100, [6, 30, 90, 270, 400, 550], 'light blue'),
              Chance('Advance to Boardwalk', 'move', 39),
              Street('Vermont Avenue', 100, [6, 30, 90, 270, 400, 550], 'light blue'),
              Street('Connecticut Avenue', 120, [8, 40, 100, 300, 450, 600], 'light blue'),
              Property('Jail', None, None),
              Street('St. Charles Place', 140, [10, 50, 150, 450, 625, 750], 'pink'),
              Utility('Electric Company', 150),
              Street('States Avenue', 140, [10, 50, 150, 450, 625, 750], 'pink'),
              Street('Virginia Avenue', 160, [12, 60, 180, 500, 700, 900], 'pink'),
              Railroad('Pennsylvania Railroad', 200),
              Street('St. James Place', 180, [14, 70, 200, 550, 750, 950], 'orange'),
              Chance('Advance to Illinois Avenue', 'move', 24),
              Street('Tennessee Avenue', 180, [14, 70, 200, 550, 750, 950], 'orange'),
              Street('New York Avenue', 200, [16, 80, 220, 600, 800, 1000], 'orange'),
              Property('Free Parking', None, None),
              Street('Kentucky Avenue', 220, [18, 90, 250, 700, 875, 1050], 'red'),
              Chance('Advance to Boardwalk', 'move', 39),
              Street('Indiana Avenue', 220, [18, 90, 250, 700, 875, 1050], 'red'),
              Street('Illinois Avenue', 240, [20, 100, 300, 750, 925, 1100], 'red'),
              Railroad('B.&O. Railroad', 200),
              Street('Atlantic Avenue', 260, [22, 110, 330, 800, 975, 1150], 'yellow'),
              Street('Ventnor Avenue', 260, [22, 110, 330, 800, 975, 1150], 'yellow'),
              Utility('Water Works', 150),
              Street('Marvin Gardens', 280, [24, 120, 360, 850, 1025, 1200], 'yellow'),
              Property('Go To Jail', None, None),
              Street('Pacific Avenue', 300, [26, 130, 390, 900, 1100, 1275], 'green'),
              Street('North Carolina Avenue', 300, [26, 130, 390, 900, 1100, 1275]

以上是一个简单的大富翁游戏的代码框架和一些示例代码,希望能对您有帮助。这只是一个初步的代码,还需要根据需求进行优化和完善。

本期推荐

截止日期:6月29日20:00

参与方式:点赞+收藏+评论:人生苦短,我用Python!!!(否则无效)

 

 

本真正从漏洞靶场、项目案例来指导读者提高Web安全、漏洞利用技术与渗透测试技巧的图书。本书以新手实操为出发点,搭建漏洞靶场:解析攻防原理+详解攻防手法+构建完整攻防体系。

本书从一开始便对Web开发基础和靶场搭建做了详细介绍,结合红日安全团队的漏洞挖掘和评估项目实战经验对各种实战技术进行分析,便于读者理解书中讲到的项目评估攻防案例的底层逻辑

内容简介

我们都生活在移动互联网时代,个人信息、企业信息等都暴露在互联网之下。一旦有居心叵测的人攻破网络,会造成无法估量的损失。本书结合红日安全团队的多年经验,深入讲解Web安全的相关知识。

全书共21章,第1章到第6章讲解入门知识,包括HTTP基本概念、工具实战、信息收集、靶场搭建等内容;第7章到第20章讲解Web渗透测试的14个典型漏洞案例,包括SQL注入、XSS漏洞、CSRF漏洞、SSRF漏洞、任意文件上传、业务逻辑漏洞等内容;第21章是项目实战,主要模拟真实Web安全评估项目。

当当销售链接:《Web安全攻防从入门到精通 红日安全出品》(红日安全)【简介_书评_在线阅读】 - 当当图书

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/683696.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Spring 】项目创建和使用

哈喽&#xff0c;哈喽&#xff0c;大家好~ 我是你们的老朋友&#xff1a;保护小周ღ 谈起Java 圈子里的框架&#xff0c;最年长最耀眼的莫过于 Spring 框架啦&#xff0c;如今已成为最流行、最广泛使用的Java开发框架之一。不知道大家有没有在使用 Spring 框架的时候思考过这…

强化学习从基础到进阶-常见问题和面试必知必答[5]::梯度策略、添加基线(baseline)、优势函数、动作分配合适的分数(credit)

【强化学习原理项目专栏】必看系列&#xff1a;单智能体、多智能体算法原理项目实战、相关技巧&#xff08;调参、画图等、趣味项目实现、学术应用项目实现 专栏详细介绍&#xff1a;【强化学习原理项目专栏】必看系列&#xff1a;单智能体、多智能体算法原理项目实战、相关技巧…

Spring Cloud - Nacos 注册发现、分级模型、配置集群、环境隔离、原理

目录 一、Nacos 安装和配置 二、Nacos 服务注册发现 2.1、将服务注册到 nacos 中 2.2、执行效果 三、Nacos 的服务分级模型及配置 3.1、分级模型 3.2、配置集群 3.3、配置 Nacos 负载均衡策略 3.4、Nacos 服务实例的权重设置 3.5、环境隔离——namespace 四、Nacos注…

真实企业做自动化测试做法,从测试用例到测试报告...

目录&#xff1a;导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09; 前言 首先&#xff0c;…

SAP MM 组织结构配置

1.定义公司代码 创建公司代码一般来说是财务去配置&#xff0c;但是我们需要去有一个基本的了解&#xff0c;这样&#xff0c;你才能理清公司代码和MM 组织的关系 配置&#xff1a;SAP IMG Enterprise Structure -》Definition -> Financial Accounting -> Edit, Copy, …

深度学习(26)——YOLO系列(5)

深度学习&#xff08;26&#xff09;——YOLO-v7&#xff08;5&#xff09; 文章目录 深度学习&#xff08;26&#xff09;——YOLO-v7&#xff08;5&#xff09;絮絮叨叨1. conv和BN的融合2. 3*3卷积的替换&#xff08;1&#xff09;1*1卷积有什么作用&#xff1f;&#xff08…

解决方案 | 照明行业数字化营销CRM平台

“数字中国”作为二十大报告的“关键词”&#xff0c;也成为各行各业的高质量发展的主旋律&#xff0c;历史悠久的中国照明产业也积极拥抱“数字化”&#xff0c;以驱动高质量发展 。作为照明行业的领军企业&#xff0c;某照明行业客户很早就意识到企业数字化转型的重要性&…

Spring事务源码详解-spring原码(二)

上篇文章介绍了事务开启&#xff0c;前面介绍了解析adviors。 spring事务源码详解-spring原码&#xff08;一&#xff09;https://blog.csdn.net/ke1ying/article/details/131360060 事务源码 先从缓存里获取&#xff0c;主要是判断循环依赖是否创建动态代理 进去wrapIfNeces…

【MOOC 作业】第3章 传输层

不是标答也不是参考答案 仅从个人理解出发去做题 1、(20分) ‍主机甲和主机乙之间已建立一个 TCP 连接&#xff0c;TCP 最大段长度为 1000 字节&#xff0c;若主机甲的当前拥塞窗口为 5000 字节&#xff0c;在主机甲向主机乙连接发送 2 个最大段后&#xff0c;成功收到主机乙发…

Java微服务金融项目智牛股 项目简介与金融知识介绍及技术特点

项目简介 金融交易平台服务于金融衍生产品&#xff0c; 包含外汇、贵金属、期货、股票。 各产品具有不同属性与交易规则&#xff0c; 本项目对标MT4等大型交易平台&#xff0c; 遵循FIX全球最广泛的金融市场通用协议。 实现从证券注册开户、行情订阅与呈现&#xff0c; 股票撮合…

JAVA 日期类Date SimpleDateFormat Calendar

1、Date日期类 类 Date 表示一个特定的瞬间&#xff0c;精确到毫秒 1.1 Date的构造函数 Date() 分配一个 Date 对象&#xff0c;以表示分配它的时间&#xff08;精确到毫秒&#xff09; Date(long date) 分配一个 Date 对象&#xff0c;表示自从标准基准时间起指定时间的毫秒数…

2023最新AI创作系统/ChatGPT商业运营版网站程序源码+支持GPT4+支持ai绘画(MJ)+实时语音识别输入+免费更新版本

2023最新AI创作系统/ChatGPT商业运营版网站程序源码支持ai绘画支持GPT4.0实时语音识别输入文章资讯发布功能用户会员套餐免费更新版本 一、AI创作系统二、系统介绍三、系统程序下载四、安装教程五、主要功能展示六、更新日志 一、AI创作系统 1、提问&#xff1a;程序已经支持G…

论洗碗哥在CSDN摸滚打爬的256个日夜

目录 机缘 收获 成就 憧憬 机缘 创作初心了为了记录一下自己的日常学习过程&#xff0c;方便自己日后去总结&#xff0c;或者遇到类似的问题的时候就可以翻阅自己的文章了。也可以加深自己的印象。其实一开始我是一个不太善于总结的人&#xff0c;机缘之下&#xff0c;听到…

机器学习之PCA算法

目录 PCA算法 PCA目标 PCA原理推导 基于最大可分性推导 基于最近重构误差推导 PCA算法流程 PCA优点 PCA缺点 基于PCA的人脸识别 PCA算法 PCA&#xff0c;即主成分分析&#xff08;Principal Component Analysis&#xff09;&#xff0c;是一种常用的降维技术&#x…

【博客674】警惕Prometheus 中的重复样本和无序时间戳错误

警惕Prometheus 中的重复样本和无序时间戳错误 1、场景 您的 Prometheus 服务器日志中是否遇到过以下错误&#xff1f; "Error on ingesting out-of-order samples" "Error on ingesting samples with different value but same timestamp" "dupli…

2023最全 Java 高频面试合集,掌握这些你也能进大厂

进大厂是大部分程序员的梦想&#xff0c;而进大厂的门槛也是比较高的&#xff0c;所以这里整理了一份阿里、美团、滴滴、头条等大厂面试大全&#xff0c;对于 Java 后端的朋友来说应该是最全面最完整的面试备战仓库&#xff0c;为了更好地整理每个模块&#xff0c;我也参考了很…

内网隧道代理技术(六)之 PowerCat反弹Shell

PowerCat反弹Shell PowerCat介绍 PowerCat是一个powershell写的tcp/ip瑞士军刀&#xff0c;看一看成ncat的powershell的实现&#xff0c;然后里面也加入了众多好用的功能&#xff0c;如文件上传&#xff0c;smb协议支持&#xff0c;中继模式&#xff0c;生成payload&#xff…

几分钟带你快速了解SpringBoot框架理论知识!

1.什么是SpringBoot SpringBoot其实就是Spring的子项目。它简化了Spring的开发难度&#xff0c;舍弃了一切可以舍弃的xml配置文件&#xff0c;提供了各种启动器&#xff0c;让程序员上手更快&#xff0c;节省了开发时间。 2.SpringBoot的优点 SpringBoot其实就是对Spring的缺…

抖音林客系统定制开发

抖音林客是一款提供旅游攻略和景点推荐的短视频社交平台&#xff0c;主要用户群体为喜欢旅游和分享生活的年轻人。从需求分析角度来看&#xff0c;可以从以下几个方面进行分析&#xff1a; 信息获取需求&#xff1a;抖音林客用户需求获取有关旅游的详细和实用的信息&#x…

Idea快捷键设置(Idea快捷键大全)

目录 友情提醒第一章、IDEA常用快捷键1.1&#xff09;快捷键&#xff1a;查找/提示类1.2&#xff09;快捷键&#xff1a;修改代码类1.3&#xff09;快捷键&#xff1a;光标移动类 第二章、如何修改快捷键2.1&#xff09;修改快捷键的方法2.2&#xff09;我修改的快捷键&#xf…