Exemple #1
0
 def __init__(self, id, logPath):
     self.id = id
     self.asset_list = []
     self.accounts = [Account(0, "Bank")]
     self.logPath = logPath
     self.logObj = Printer(self.logPath)
     self.PlayerBuyMenu = MenuBox("Buy Menu", self.logPath)
     self.PlayerBuyMenu.addOption("Want to buy")
     self.PlayerMortMenu = MenuBox('Cash Raise Menu', self.logPath)
    def __init__(self, player_count, log_path, user=None, password=None):
        self.logPath = log_path
        self.dbuser = user
        self.dbpassword = password
        self.PlayerMenu = MenuBox("Game Menu", self.logPath, 0)
        self.PlayerMenu.addOptions([
            "Continue", "Redeem", "Build Property", "Sell Property",
            "Show Asset Info", "Quit Game"
        ])
        if self.dbuser is not None:
            self.PlayerMenu.addOption('Save Game')
        self.PlayerBuyMenu = MenuBox("Buy Menu", self.logPath)
        self.PlayerBuyMenu.addOption("Want to buy")

        self.logObj = Printer(self.logPath)
        self.player_count = player_count
        self.players = []
        self.dice = Dice()
        self.available_players_id = []
        self.turnHolderPlayerID = 0
        self.BoardData = {}
        self.state = True
        for i in range(36):
            self.BoardData[i + 1] = []
        self.country_name_list = [
            "England", "Iraq", "France", "Iran", "Egypt", "Canada", "Germany",
            "Swiss", "Brazil", "Italy", "Japan", "USA", "Mexico", "Hongkong",
            "Australia", "India", "SaudiArab", "China", "Malaysia", "Singapore"
        ]
        # key value array of Utility [boardPosition, buyValue, mortgageValue]
        self.utility_name_list = [
            "Waterways", "Satellite", "Airways", "Roadways", "Petroleum",
            "Railways"
        ]
        self.Banker = Banksmart(0, self.logPath)
        self.Banker.asset_list = [Country(country_list[i][0], i, country_list[i][1], country_list[i][2], country_list[i][4],
                                          country_list[i][5], country_list[i][6], country_list[i][3]) for i in country_list] + \
                                 [Utility(utility_list[i][0], i, utility_list[i][1], utility_list[i][2],  utility_list[i][3],
                                             utility_list[i][4], utility_list[i][5]) for i in utility_list]
Exemple #3
0
class Account(object):
    def __init__(self, id, name, balance=0):
        self.id = id
        self.name = name
        self.balance = balance
        self.transaction_statement = Printer()
        self.state = True

    def deposit(self, amount, msg=""):
        self.balance += amount
        self.statement_populate(msg, amount, 1)

    def withdraw(self, amount, msg=""):
        self.balance -= amount
        self.statement_populate(msg, amount, 0)
        if self.balance < 0: raise ValueError

    def isenoughbalance(self, amount):
        if self.balance >= amount:
            return True
        return False

    def set_statement_filename(self, fname, mode):
        self.transaction_statement.set_log_file_name(fname, mode)
        self.transaction_statement.file_only_printer(
            "{: >60} {: >8} {: >8} {: >8}".format("Transaction Details",
                                                  "Debit", "Credit",
                                                  "Balance"))

    def statement_populate(self, msg, amount, type):
        if type == 0:
            statement = "{: >60} {: >8} {: >8} {: >8}".format(
                msg, amount, "", self.balance)
        else:
            statement = "{: >60} {: >8} {: >8} {: >8}".format(
                msg, "", amount, self.balance)
        self.transaction_statement.file_only_printer(statement)

    def acc_state(self):
        return (self.id, self.balance, self.state)

    def change_state(self, new_state):
        (self.balance, self.state) = new_state
class Smartcontroller(object):

    crossover_amount = 100

    def __init__(self, player_count, log_path, user=None, password=None):
        self.logPath = log_path
        self.dbuser = user
        self.dbpassword = password
        self.PlayerMenu = MenuBox("Game Menu", self.logPath, 0)
        self.PlayerMenu.addOptions([
            "Continue", "Redeem", "Build Property", "Sell Property",
            "Show Asset Info", "Quit Game"
        ])
        if self.dbuser is not None:
            self.PlayerMenu.addOption('Save Game')
        self.PlayerBuyMenu = MenuBox("Buy Menu", self.logPath)
        self.PlayerBuyMenu.addOption("Want to buy")

        self.logObj = Printer(self.logPath)
        self.player_count = player_count
        self.players = []
        self.dice = Dice()
        self.available_players_id = []
        self.turnHolderPlayerID = 0
        self.BoardData = {}
        self.state = True
        for i in range(36):
            self.BoardData[i + 1] = []
        self.country_name_list = [
            "England", "Iraq", "France", "Iran", "Egypt", "Canada", "Germany",
            "Swiss", "Brazil", "Italy", "Japan", "USA", "Mexico", "Hongkong",
            "Australia", "India", "SaudiArab", "China", "Malaysia", "Singapore"
        ]
        # key value array of Utility [boardPosition, buyValue, mortgageValue]
        self.utility_name_list = [
            "Waterways", "Satellite", "Airways", "Roadways", "Petroleum",
            "Railways"
        ]
        self.Banker = Banksmart(0, self.logPath)
        self.Banker.asset_list = [Country(country_list[i][0], i, country_list[i][1], country_list[i][2], country_list[i][4],
                                          country_list[i][5], country_list[i][6], country_list[i][3]) for i in country_list] + \
                                 [Utility(utility_list[i][0], i, utility_list[i][1], utility_list[i][2],  utility_list[i][3],
                                             utility_list[i][4], utility_list[i][5]) for i in utility_list]

    def set_turn(self, value):
        if self.turnHolderPlayerID == 0:
            self.turnHolderPlayerID += 1
        else:
            next_players_index = (
                self.available_players_id.index(self.turnHolderPlayerID) +
                value) % len(self.available_players_id)
            self.turnHolderPlayerID = self.available_players_id[
                next_players_index]

    def print_winner(self, name):
        self.logObj.printer(color_coded[11] + ("*" * 30 + "\n") * 2 +
                            "The winner is %s\n" % name +
                            ("*" * 30 + "\n") * 2 + color_coded[8])

    def remove_player_from_game(self, player_id):
        if player_id == 0:
            self.logObj.printer(color_coded[10] + "Bank is out of cash." +
                                color_coded[8])
            self.state = False
            self.print_winner(self.get_winner())
        else:
            res = self.Banker.bankrupt_a_player(player_id)
            for i in res:
                assets_board_locations[i] = "    "
            self.players[player_id - 1].active = False
            self.players[player_id - 1].board_pos = 0
            if len(self.available_players_id) >= 2:
                if self.turnHolderPlayerID == player_id:
                    self.set_turn(-1)
                self.available_players_id.remove(player_id)
            if len(self.available_players_id) == 1:
                self.state = False
                self.print_winner(self.players[self.available_players_id[0] -
                                               1].name)

    def next_move(self, chance):
        self.logObj.printer(color_coded[11] + "Chance #%d" % chance +
                            color_coded[8])
        if self.state:
            self.set_turn(1)
        turnplayer = self.players[self.turnHolderPlayerID - 1]
        self.logObj.printer(color_coded[11] +
                            "Player %s, your chance" % turnplayer.name +
                            color_coded[8])
        optionGameRecv = 1
        if optionGameRecv == 1:
            dice_out = self.dice.throw_dice()
            self.logObj.printer("Dice outcome = %d" % dice_out)
            iscrossover = turnplayer.move(dice_out)
            self.show_board(
                color_coded[11] +
                "Chance #%d\nPlayer %s, your chance\nDice outcome = %d\n" %
                (chance, turnplayer.name, dice_out) + color_coded[8])
            if iscrossover:
                self.logObj.printer(color_coded[11] +
                                    "You received crossover payment of $%d" %
                                    Smartcontroller.crossover_amount +
                                    color_coded[8])
                res = self.Banker.payreward(
                    turnplayer.id, Smartcontroller.crossover_amount,
                    'Crossover payment to Player-%d' % turnplayer.id)
                self.bank_response_action(res)
            ownerID = self.get_property_owner_where_player_standing(turnplayer)
            if ownerID == -1:
                if turnplayer.board_pos == 5 or turnplayer.board_pos == 26:  # UNO
                    self.apply_uno_to_player(turnplayer.id, dice_out)
                elif turnplayer.board_pos == 17 or turnplayer.board_pos == 30:  # CHANCE
                    self.apply_chance_to_player(turnplayer.id, dice_out)
                elif turnplayer.board_pos == 14:  # custom duty
                    self.logObj.printer(color_coded[10] +
                                        'You reached on Custom Duty' +
                                        color_coded[8])
                    res = self.Banker.p2ptransaction(
                        turnplayer.id, 0, -1,
                        "Custom Duty - Player-%d" % turnplayer.id)
                    self.bank_response_action(res)
                elif turnplayer.board_pos == 22:  # travelling duty
                    self.logObj.printer(color_coded[10] +
                                        'You reached on Travelling Duty' +
                                        color_coded[8])
                    res = self.Banker.p2ptransaction(
                        turnplayer.id, 0, -1,
                        "Travelling Duty - Player-%d" % turnplayer.id)
                    self.bank_response_action(res)
                elif turnplayer.board_pos == 28:  # JAIL
                    self.gotojail(turnplayer.id)
                elif turnplayer.board_pos == 10:  # Resort
                    self.enjoyment_in_resort(turnplayer.id)
                elif turnplayer.board_pos == 19:  # Party House
                    self.get_party_from_others(turnplayer.id)
                else:
                    pass
            else:
                result = self.Banker.sell_asset_to_player(
                    turnplayer.id, turnplayer.board_pos)
                if result == 0:
                    assets_board_locations[turnplayer.board_pos] = color_coded[
                        turnplayer.id +
                        9] + "|P%d|" % turnplayer.id + color_coded[8]
                elif result == -1:
                    self.remove_player_from_game(turnplayer.id)
                elif result == 2:
                    auc_res = self.Banker.auction_of_asset(
                        turnplayer.board_pos)
                    if auc_res > 0:
                        assets_board_locations[
                            turnplayer.board_pos] = color_coded[
                                auc_res +
                                9] + "|P%d|" % auc_res + color_coded[8]
                else:
                    pass
            if self.state:
                optionPlayerRecv = 0
                while optionPlayerRecv not in (1, 6, 7):
                    self.logObj.printer(
                        color_coded[9 + self.turnHolderPlayerID] +
                        "Player-%d (%s)...\n" %
                        (self.turnHolderPlayerID, turnplayer.name) +
                        color_coded[8])
                    optionPlayerRecv = self.PlayerMenu.runMenu()
                    if optionPlayerRecv == 1:
                        self.logObj.printer("Continuing the game...\n")
                        self.show_board()
                    elif optionPlayerRecv == 2:
                        self.logObj.printer(
                            "Player %d wants to redeem his mortgaged assets" %
                            self.turnHolderPlayerID)
                        self.redeem_mortgaged_property_of_player(
                            self.turnHolderPlayerID)
                    elif optionPlayerRecv == 3:
                        self.logObj.printer(
                            "Player %d wants to build property on his site" %
                            self.turnHolderPlayerID)
                        self.build_property_on_player_site(
                            self.turnHolderPlayerID)
                    elif optionPlayerRecv == 4:
                        self.logObj.printer(
                            "Player %d wants to sell property of his site" %
                            self.turnHolderPlayerID)
                        self.sell_property_of_player_site(
                            self.turnHolderPlayerID)
                    elif optionPlayerRecv == 5:
                        select = 0
                        while select == False:
                            inp = raw_input("Enter the asset code: ")
                            self.logObj.printer("")
                            matchObj = re.match(r'^(\d+)$', inp, re.M)
                            if matchObj:
                                if 1 <= int(matchObj.group(1)) <= 36:
                                    select = int(inp)
                                else:
                                    self.logObj.printer(
                                        color_coded[10] +
                                        "Please enter valid asset code between 2 and 36."
                                        + color_coded[8])
                            else:
                                self.logObj.printer(
                                    color_coded[10] +
                                    "Please enter valid asset code between 2 and 36."
                                    + color_coded[8])
                        asset = self.Banker.get_asset_by_assetid(select)
                        if asset is not None:
                            self.logObj.printer(asset.info())
                        else:
                            self.logObj.printer(
                                color_coded[10] +
                                'Input asset code is not valid. Please check the board.'
                                + color_coded[8])
                    elif optionPlayerRecv == 6:
                        self.logObj.printer(
                            color_coded[10] +
                            'Player-%d (%s) is leaving the game.' %
                            (self.turnHolderPlayerID, turnplayer.name) +
                            color_coded[8])
                        self.logObj.printer(
                            color_coded[11] +
                            'Only %d players left in the game' %
                            (len(self.available_players_id) - 1) +
                            color_coded[8])
                        self.remove_player_from_game(self.turnHolderPlayerID)
                    elif optionPlayerRecv == 7:
                        if len(self.available_players_id) > 1:
                            self.save_game(chance)
                        else:
                            self.logObj.printer(
                                "Game already finished. It can not be saved.")
                        self.state = False
                    else:
                        pass

    def print_all_player_assets_table(self, term_only):
        output = ""
        total_cash_reserver = self.Banker.get_players_balance(0) + reduce(
            lambda x, y: x + y, [
                self.Banker.get_players_balance(i.id)
                for i in self.players if i.active
            ])
        total_asset_reserver = self.Banker.get_players_asset_value(0) + reduce(
            lambda x, y: x + y, [
                self.Banker.get_players_asset_value(i.id)
                for i in self.players if i.active
            ])
        output += '-' * 118 + '\n'
        output += "|PID   |Name      |    Cash| NetWorth |    Assets Counters    |Asset Names                                                \n"
        output += '-' * 118 + '\n'
        for i in self.players:
            if i.active:
                output += "|{: <5} |{: <10}|{: >8}|{: >10}|{: <10}\n".format(
                    i.id, i.name, self.Banker.get_players_balance(i.id),
                    self.Banker.get_players_asset_value(i.id),
                    self.Banker.group_wise_asset_list(i.id))
                output += '-' * 118 + '\n'
        output += "|{: <5} |{: <10}|{: >8}|{: >10}|{: <10}\n".format(
            0, 'Bank', self.Banker.get_players_balance(0),
            self.Banker.get_players_asset_value(0),
            self.Banker.group_wise_asset_list(0))
        output += '-' * 118 + '\n'
        if total_cash_reserver != 1000000:
            output += "Cash-Balance issue occurred.\n"
            raise ValueError
        if total_asset_reserver != 118000:
            output += "Asset-Balance issue occurred.\n"
            raise ValueError
        if term_only is False: self.logObj.printer(output)
        else: print output

    def display_board(self, term_only):
        output = ' ' * 71 + '-' * 24 + '\n' + ' ' * 71 + color_coded[
            1] + color_coded[9] + '|INTERNATIONAL BUSINESS|' + color_coded[
                8] + color_coded[7] + '\n' + ' ' * 71 + '-' * 24 + '\n'
        i = 0
        while i < len(board_display_data):
            pp = self.check_all_player_presence_on_a_position(i + 1)
            if (i + 1) in assets_board_locations:
                owner_tag = assets_board_locations[i + 1]
            else:
                owner_tag = "    "
            loc = ""
            for j in range(len(pp)):
                if pp[j]:
                    loc = loc + color_coded[pp[j].id + 9] + "<P" + str(
                        pp[j].id) + ">" + color_coded[8]
            loc = loc + "    " * (self.player_count - len(pp))
            self.BoardData[i + 1] = [board_display_data[i], owner_tag, loc]
            i += 1
        pl_col_len = 133 + 16 * (self.player_count - 2)
        output += '-' * pl_col_len + '\n'
        output += "|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|\n" % (
            'Location          ', 'Own ', 'Player  ' + ' ' * 4 *
            (self.player_count - 2), 'Location          ', 'Own ',
            'Player  ' + ' ' * 4 * (self.player_count - 2),
            'Location          ', 'Own ', 'Player  ' + ' ' * 4 *
            (self.player_count - 2), 'Location          ', 'Own ',
            'Player  ' + ' ' * 4 * (self.player_count - 2))
        output += '-' * pl_col_len + '\n'
        for i in range(9):
            output += "|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|\n" % (
                self.BoardData[i + 1][0], self.BoardData[i + 1][1],
                self.BoardData[i + 1][2], self.BoardData[i + 10][0],
                self.BoardData[i + 10][1], self.BoardData[i + 10][2],
                self.BoardData[i + 19][0], self.BoardData[i + 19][1],
                self.BoardData[i + 19][2], self.BoardData[i + 28][0],
                self.BoardData[i + 28][1], self.BoardData[i + 28][2])
        output += '-' * pl_col_len + '\n'
        if term_only is False:
            self.logObj.printer(output)
        else:
            print output

    def get_property_owner_where_player_standing(self, playerobj):
        return self.Banker.get_owner_by_assetid(playerobj.board_pos)

    def show_board(self, msg="", term_only=False):
        if platform.system() == 'Linux':
            _ = os.system('clear')
        else:
            _ = os.system('cls')
        self.display_board(term_only)
        self.print_all_player_assets_table(term_only)
        self.logObj.printer(msg)

    def transmit_from_one_to_rest(self, sender, amount, reason_text):
        for i in self.available_players_id:
            if i != sender:
                res = self.Banker.p2ptransaction(sender, i, amount,
                                                 reason_text)
                self.bank_response_action(res)
                if sender in res:
                    break

    def receive_from_all_to_one(self, receiver, amount, reason_text):
        for i in self.available_players_id:
            if i != receiver:
                res = self.Banker.p2ptransaction(i, receiver, amount,
                                                 reason_text)
                self.bank_response_action(res)

    def enjoyment_in_resort(self, player_id):
        self.logObj.printer(color_coded[10] +
                            'You reached on Resort. Paid $200 to all.' +
                            color_coded[8])
        self.transmit_from_one_to_rest(player_id, 200,
                                       "Resort money - Player-%d" % player_id)

    def get_party_from_others(self, player_id):
        self.logObj.printer(
            color_coded[11] +
            'You reached on Party House. Eligible to receive $200 from all.' +
            color_coded[8])
        self.receive_from_all_to_one(player_id, 200,
                                     "Party House - Player-%d" % player_id)

    def gotojail(self, player_id):
        self.logObj.printer(color_coded[10] +
                            'You reached on Jail. Paid $ 100 to come out.' +
                            color_coded[8])
        res = self.Banker.p2ptransaction(
            player_id, 0, 100, "Reached to Jail - Player-%d" % player_id)
        self.bank_response_action(res)

    def check_all_player_presence_on_a_position(self, board_pos):
        return [
            i for i in self.players if i.active and i.board_pos == board_pos
        ]

    def apply_uno_to_player(self, recipient, rule_num):
        if rule_num == 2:
            self.logObj.printer(
                color_coded[11] +
                "UNO-2: It is your anniversary, collect $500 from each player."
                + color_coded[8])
            self.receive_from_all_to_one(
                recipient, 500,
                "UNO-2: Anniversary gift - Player-%d" % recipient)
        elif rule_num == 4:
            self.logObj.printer(
                color_coded[11] +
                "UNO-4: 1st prize in Beauty Contest of $2500." +
                color_coded[8])
            res = self.Banker.payreward(
                recipient, 2500,
                "UNO-4, Won Beauty Contest - Player-%d" % recipient)
            self.bank_response_action(res)
        elif rule_num == 6:
            self.logObj.printer(color_coded[11] +
                                "UNO-6: Income tax refund of $2000." +
                                color_coded[8])
            res = self.Banker.payreward(
                recipient, 2000, "UNO-6, IT refund - Player-%d" % recipient)
            self.bank_response_action(res)
        elif rule_num == 8:
            self.logObj.printer(
                color_coded[11] +
                "UNO-8: Go to party house and collect $200 from each player." +
                color_coded[8])
            self.receive_from_all_to_one(
                recipient, 200, "UNO-8: Party house - Player-%d" % recipient)
            for i in self.players:
                if i.id == recipient:
                    i.board_pos = 19
        elif rule_num == 10:
            self.logObj.printer(
                color_coded[11] +
                "UNO-10: Receive interest on shares of $1500." +
                color_coded[8])
            res = self.Banker.payreward(
                recipient, 1500,
                "UNO-10: shares interest - Player-%d" % recipient)
            self.bank_response_action(res)
        elif rule_num == 12:
            self.logObj.printer(
                color_coded[11] +
                "UNO-12: Receive amount of $3000 after sale of stocks." +
                color_coded[8])
            res = self.Banker.payreward(
                recipient, 3000,
                "UNO-12: sale of stocks - Player-%d" % recipient)
            self.bank_response_action(res)
        elif rule_num == 3:
            self.logObj.printer(color_coded[10] +
                                "UNO-3: Go to jail with $500 fine" +
                                color_coded[8])
            res = self.Banker.p2ptransaction(
                recipient, 0, 500,
                "UNO-3: Sent to Jail - Player-%d" % recipient)
            self.bank_response_action(res)
            for i in self.players:
                if i.id == recipient:
                    i.board_pos = 28
        elif rule_num == 5:
            self.logObj.printer(
                color_coded[10] +
                "UNO-5: School and medical fees expenses of $2500." +
                color_coded[8])
            res = self.Banker.p2ptransaction(
                recipient, 0, 2500,
                "UNO-5: School Fees - Player-%d" % recipient)
            self.bank_response_action(res)
        elif rule_num == 7:
            self.logObj.printer(
                color_coded[10] +
                "UNO-7: Submit your passport and pay $5000 fine." +
                color_coded[8])
            res = self.Banker.p2ptransaction(
                recipient, 0, 5000,
                "UNO-7: Passport Deposit - Player-%d" % recipient)
            self.bank_response_action(res)
        elif rule_num == 9:
            self.logObj.printer(
                color_coded[10] +
                "UNO-9: Make general repair on your properties of $100" +
                color_coded[8])
            res = self.Banker.p2ptransaction(
                recipient, 0, 100, "UNO-9: Repair - Player-%d" % recipient)
            self.bank_response_action(res)
        elif rule_num == 11:
            self.logObj.printer(color_coded[10] +
                                "UNO-11: Pay insurance premium of $1500." +
                                color_coded[8])
            res = self.Banker.p2ptransaction(
                recipient, 0, 1500,
                "UNO-11, Insurance Premium - Player-%d" % recipient)
            self.bank_response_action(res)
        else:
            pass

    def apply_chance_to_player(self, recipient, rule_num):
        if rule_num == 2:
            self.logObj.printer(color_coded[10] +
                                "Chance-2: Loss in share market of $2000." +
                                color_coded[8])
            res = self.Banker.p2ptransaction(
                recipient, 0, 2000,
                "Chance-2: Loss in share - Player-%d" % recipient)
            self.bank_response_action(res)
        elif rule_num == 4:
            self.logObj.printer(
                color_coded[10] +
                "Chance-4: Fine for accident due to wrong driving of $1000" +
                color_coded[8])
            res = self.Banker.p2ptransaction(
                recipient, 0, 1000,
                "Chance-4: Driving fine - Player-%d" % recipient)
            self.bank_response_action(res)
        elif rule_num == 6:
            self.logObj.printer(color_coded[10] +
                                "Chance-6: House repair of $1500." +
                                color_coded[8])
            res = self.Banker.p2ptransaction(
                recipient, 0, 1500,
                "Chance-6: House repair - Player-%d" % recipient)
            self.bank_response_action(res)
        elif rule_num == 8:
            self.logObj.printer(
                color_coded[10] +
                "Chance-8: Loss of $3000 due to fire in Go-down." +
                color_coded[8])
            res = self.Banker.p2ptransaction(
                recipient, 0, 3000,
                "Chance-8: Loss due to fire - Player-%d" % recipient)
            self.bank_response_action(res)
        elif rule_num == 10:
            self.logObj.printer(color_coded[10] + "Chance-10: Go to jail." +
                                color_coded[8])
            res = self.Banker.p2ptransaction(
                recipient, 0, 500,
                "Chance-10: Sent to jail - Player-%d" % recipient)
            self.bank_response_action(res)
            for i in self.players:
                if i.id == recipient:
                    i.board_pos = 28
        elif rule_num == 12:
            self.logObj.printer(color_coded[10] +
                                "Chance-12: Repair of your car of $200." +
                                color_coded[8])
            res = self.Banker.p2ptransaction(
                recipient, 0, 200,
                "Chance-12: Car repair - Player-%d" % recipient)
            self.bank_response_action(res)
        elif rule_num == 3:
            self.logObj.printer(color_coded[11] +
                                "Chance-3: Won lottery prize of $2500." +
                                color_coded[8])
            res = self.Banker.payreward(
                recipient, 2500,
                "Chance-3: won lottery - Player-%d" % recipient)
            self.bank_response_action(res)
        elif rule_num == 5:
            self.logObj.printer(
                color_coded[11] +
                "Chance-5: You have won cross-word prize of $1000." +
                color_coded[8])
            res = self.Banker.payreward(
                recipient, 1000,
                "Chance-5: won cross-word - Player-%d" % recipient)
            self.bank_response_action(res)
        elif rule_num == 7:
            self.logObj.printer(
                color_coded[11] +
                "Chance-7: Collect $100 rent from each player for all of your site."
                + color_coded[8])
            amount = self.Banker.get_players_countries(recipient) * 100
            self.receive_from_all_to_one(
                recipient, amount,
                "Chance-7: Rent collection - Player-%d" % recipient)
        elif rule_num == 9:
            self.logObj.printer(
                color_coded[11] +
                "Chance-9: You have won the jackpot of $2000." +
                color_coded[8])
            res = self.Banker.payreward(
                recipient, 2000,
                "Chance-9: won jackpot - Player-%d" % recipient)
            self.bank_response_action(res)
        elif rule_num == 11:
            self.logObj.printer(
                color_coded[11] +
                "Chance-11: Prize for best performance in export of $1500." +
                color_coded[8])
            res = self.Banker.payreward(
                recipient, 1500,
                "Chance-11: Best exporter - Player-%d" % recipient)
            self.bank_response_action(res)
        else:
            pass

    def redeem_mortgaged_property_of_player(self, player_id):
        player_mort_props = [
            i for i in self.Banker.asset_list if i.owner == player_id + 10
        ]
        if len(player_mort_props) > 0:
            prop_redeem_menu = MenuBox('Asset Redemption Menu', self.logPath)
            prop_redeem_menu.addOptions([i.name for i in player_mort_props])
            optionGot = prop_redeem_menu.runMenu()
            if optionGot != prop_redeem_menu.getoptioncount():
                asset_id = player_mort_props[optionGot - 1].board_loc
                self.Banker.redeem_asset_of_player(player_id, asset_id)
            else:
                self.logObj.printer("Not interested in redemption.")
        else:
            self.logObj.printer(color_coded[11] +
                                "You do not have any mortgaged assets." +
                                color_coded[8])

    def build_property_on_player_site(self, player_id):
        player_props = [
            i for i in self.Banker.asset_list if i.issite()
            if i.owner == player_id and i.prop_vacancy
        ]
        if len(player_props) > 0:
            prop_buy_menu = MenuBox('Building Purchase Menu', self.logPath)
            prop_buy_menu.addOptions([i.name for i in player_props])
            optionGot = prop_buy_menu.runMenu()
            if optionGot != prop_buy_menu.getoptioncount():
                asset_id = player_props[optionGot - 1].board_loc
                self.Banker.sell_building_to_player(player_id, asset_id)
            else:
                self.logObj.printer("Not interested in buying")
        else:
            self.logObj.printer(
                "You do not have any eligible site to build property upon!")

    def sell_property_of_player_site(self, player_id):
        player_props = [
            i for i in self.Banker.asset_list if i.issite()
            if i.owner == player_id and i.prop_sell
        ]
        if len(player_props) > 0:
            prop_sell_menu = MenuBox('Building Sell Menu', self.logPath)
            prop_sell_menu.addOptions([i.name for i in player_props])
            optionGot = prop_sell_menu.runMenu()
            if optionGot != prop_sell_menu.getoptioncount():
                asset_id = player_props[optionGot - 1].board_loc
                self.Banker.get_building_from_player(player_id, asset_id)
            else:
                self.logObj.printer("Not interested in selling")
        else:
            self.logObj.printer(
                "You do not have any eligible site to sell property from!")

    def get_winner(self):
        winner = self.available_players_id[0]
        for i in self.available_players_id:
            if self.Banker.get_players_valuation(
                    i) > self.Banker.get_players_valuation(winner):
                winner = i
        return self.players[winner - 1].name

    def bank_response_action(self, player_list):
        for i in player_list:
            self.remove_player_from_game(i)

    def addplayersingame(self):
        for i in range(self.player_count):
            inp = raw_input(color_coded[11] + "Enter name for Player-%d : " %
                            (i + 1) + color_coded[8])
            self.players.append(
                Smartplayer(i + 1,
                            str(inp)[0:10], self.logPath))
            self.available_players_id.append(i + 1)
        # Initialize the bank cash reserve with $1000000
        self.Banker.add_players_accounts(self.player_count)
        self.Banker.accounts[0].deposit(1000000, "Cash reserved to bank")
        # Initial payment of $25000 to all the players for starting the game
        for i in range(self.player_count):
            res = self.Banker.payreward(
                i + 1, 25000, "Initial Payment - Player-%d" % (i + 1))

    def save_game(self, chance_count):
        self.logObj.printer(color_coded[11] +
                            "Saving game data into database..." +
                            color_coded[8])
        try:
            dx = DBhandler(self.dbuser, self.dbpassword)
            if dx.isDBexist('monopoly_game_db') == 1:
                dx.dropDB('monopoly_game_db')
            dx.createDB("monopoly_game_db")
            dx.createTable('monopoly_game_db', 'player', [
                'id', 'name', 'active', 'board_pos', 'isavailable',
                'isturnholder'
            ], [
                'tinyint primary key', 'varchar(30)', 'tinyint', 'tinyint',
                'tinyint', 'int'
            ])
            dx.createTable('monopoly_game_db', 'countries', [
                'board_loc', 'owner', 'current_rent', 'prop_count',
                'prop_vacancy', 'prop_sell'
            ], [
                'tinyint primary key', 'tinyint', 'int', 'tinyint', 'tinyint',
                'tinyint'
            ])
            dx.createTable('monopoly_game_db', 'utilities',
                           ['board_loc', 'owner', 'current_rent'],
                           ['tinyint primary key', 'tinyint', 'int'])
            dx.createTable('monopoly_game_db', 'accounts',
                           ['id', 'balance', 'state'],
                           ['tinyint primary key', 'int', 'tinyint'])
            for i in self.players:
                isavail, isturn = 0, 0
                if i.id in self.available_players_id: isavail = 1
                if i.id == self.turnHolderPlayerID: isturn = chance_count
                dx.insertintoDB(
                    'monopoly_game_db',
                    "INSERT INTO player values (%d, \'%s\', %d, %d, %d, %d)" %
                    (i.state() + (isavail, isturn)))

            for i in self.Banker.asset_list:
                if i.issite():
                    dx.insertintoDB(
                        'monopoly_game_db',
                        "INSERT INTO countries values (%d, %d, %d, %d, %d, %d)"
                        % i.state())
                else:
                    dx.insertintoDB(
                        'monopoly_game_db',
                        "INSERT INTO utilities values (%d, %d, %d)" %
                        i.state())

            for i in self.Banker.accounts:
                dx.insertintoDB(
                    'monopoly_game_db',
                    "INSERT INTO accounts values (%d, %d, %d)" % i.acc_state())
            self.logObj.printer("Current game saved into database.")
        except ValueError:
            self.logObj.printer("Unable to log into the database.")

    def set_owner_in_asset(self, board_pos, plid):
        if plid > 0:
            if plid > 10: plid -= 10
            assets_board_locations[board_pos] = color_coded[
                plid + 9] + "|P%d|" % plid + color_coded[8]

    def setprevgame(self):
        try:
            dx = DBhandler(self.dbuser, self.dbpassword)
            x = dx.queryDB('monopoly_game_db', 'SELECT * from countries')
            for i in x:
                self.Banker.get_asset_by_assetid(i[0]).change_state(
                    (i[1], i[2], i[3], bool(i[4]), bool(i[5])))
                self.set_owner_in_asset(i[0], i[1])

            x = dx.queryDB('monopoly_game_db', 'SELECT * from utilities')
            for i in x:
                self.Banker.get_asset_by_assetid(i[0]).change_state(
                    (i[1], i[2]))
                self.set_owner_in_asset(i[0], i[1])

            x = dx.queryDB('monopoly_game_db', 'SELECT * from player')
            for i in x:
                self.players.append(Smartplayer(i[0], i[1], self.logPath))
                if i[4] == 1:
                    self.available_players_id.append(i[0])
                if i[5] > 0:
                    self.turnHolderPlayerID = i[0]
                self.players[i[0] - 1].change_state((bool(i[2]), i[3]))
            self.Banker.add_players_accounts(self.player_count, 'a')
            x = dx.queryDB('monopoly_game_db', 'SELECT * from accounts')
            for i in x:
                self.Banker.accounts[i[0]].change_state((i[1], bool(i[2])))
            dx.dropDB('monopoly_game_db')
        except:
            self.logObj.printer(
                'Error while reading the previous game from DB.')
Exemple #5
0
class Banksmart(object):
    def __init__(self, id, logPath):
        self.id = id
        self.asset_list = []
        self.accounts = [Account(0, "Bank")]
        self.logPath = logPath
        self.logObj = Printer(self.logPath)
        self.PlayerBuyMenu = MenuBox("Buy Menu", self.logPath)
        self.PlayerBuyMenu.addOption("Want to buy")
        self.PlayerMortMenu = MenuBox('Cash Raise Menu', self.logPath)

    def add_players_accounts(self, player_count, mode='w'):
        self.accounts[0].set_statement_filename(
            "./business_game_logs/Bank_account_statement.txt", mode)
        for i in range(player_count):
            account_var = Account(i + 1, "PL-%d" % (i + 1))
            account_var.set_statement_filename(
                "./business_game_logs/Player-%d_account_statement.txt" %
                (i + 1), mode)
            self.accounts.append(account_var)

    def get_players_balance(self, player_id):
        return self.accounts[player_id].balance

    def bankrupt_a_player(self, player_id):
        self.accounts[0].deposit(
            self.accounts[player_id].balance,
            "Surrendered money from Player-%d" % player_id)
        self.accounts[player_id].withdraw(self.accounts[player_id].balance,
                                          "Bankrupt")
        self.accounts[player_id].transaction_statement.file_only_printer(
            "\nYour account has been deactivated.\n")
        prop_list = []
        for i in self.asset_list:
            if i.owner == player_id or i.owner == player_id + 10:
                prop_list.append(i.board_loc)
                i.owner = 0
                i.prop_count = 0
                i.current_rent = i.rent
                i.prop_vacancy = False
                i.prop_sell = False
        self.accounts[player_id].state = False
        return prop_list

    def raise_cash(self, player_id, min_amount):
        if self.get_players_credit_value(player_id) > min_amount:
            while self.accounts[player_id].balance < min_amount:
                player_props = [
                    i for i in self.asset_list if i.owner == player_id
                ]
                if len(player_props) == 0:
                    return False
                MortMenu = MenuBox('Player-%d Cash Raise Menu' % player_id,
                                   self.logPath)
                for i in player_props:
                    pname = ""
                    if i.issite():
                        if i.prop_count == 4:
                            pname = "(3 House, 1 Hotel)"
                        elif 1 <= i.prop_count < 4:
                            pname = "(%d House)" % i.prop_count
                        else:
                            pname = ""
                    MortMenu.addOption(i.name + " " + pname)
                opt = MortMenu.runMenu()
                print "you selected " + str(opt)
                if player_props[opt - 1].issite():
                    if player_props[opt - 1].prop_count > 0:
                        self.get_building_from_player(
                            player_id, player_props[opt - 1].board_loc)
                    else:
                        self.mortgage_asset_of_player(
                            player_id, player_props[opt - 1].board_loc)
                else:
                    self.mortgage_asset_of_player(
                        player_id, player_props[opt - 1].board_loc)
            return True
        else:
            return False

    def get_players_asset_value(self, player_id):
        return reduce(lambda x, y: x + y, [
            i.buy_price
            if i.owner == player_id or i.owner == player_id + 10 else 0
            for i in self.asset_list
        ])

    def get_players_valuation(self, player_id):
        val = 0
        for i in self.asset_list:
            if i.owner == player_id:
                val += i.buy_price
            elif i.owner == player_id + 10:
                val += i.buy_price - (i.mortgage_val * 1.1)
            else:
                pass
        return val + self.accounts[player_id].balance

    def get_players_credit_value(self, player_id):
        return reduce(
            lambda x, y: x + y, [self.accounts[player_id].balance] +
            [i.mortgage_val for i in self.asset_list if i.owner == player_id] +
            [(i.prop_price * i.prop_count) / 2
             for i in self.asset_list if i.owner == player_id if i.issite()])

    def get_owner_by_assetid(self, id):
        for i in self.asset_list:
            if i.board_loc == id:
                return i.owner
        return -1

    def get_asset_by_assetid(self, asset_id):
        return filter(lambda x: x.board_loc == asset_id, self.asset_list)[0]

    def get_players_countries(self, player_id):
        return len([
            i for i in self.asset_list if i.issite()
            if i.owner == player_id or i.owner == player_id + 10
        ])

    def get_players_mort_assets(self, player_id):
        return len([i for i in self.asset_list if i.owner == player_id + 10])

    def get_current_rent_by_assetid(self, id):
        asset = self.get_asset_by_assetid(id)
        if asset.issite():
            if asset.prop_count == 0:
                color_count = len([
                    1 for i in self.asset_list if i.issite() if
                    i.owner == asset.owner and i.color_grp == asset.color_grp
                ])
                if color_count >= 3:
                    return asset.current_rent * 2
            return asset.current_rent
        else:
            grp_count = len([
                1 for i in self.asset_list if i.issite() is False
                if i.owner == asset.owner and i.pair_grp == asset.pair_grp
            ])
            if grp_count == 2:
                return asset.pair_rent
            return asset.current_rent

    def group_wise_asset_list(self, player_id):
        color_code = ('R', 'G', 'B', 'Y', 'U')
        prop_name_list = [[], [], [], [], []]
        for i in self.asset_list:
            if i.owner == player_id:
                if i.issite():
                    prop_name_list[i.color_grp - 1].append(
                        i.get_name_with_prop_flag())
                else:
                    prop_name_list[4].append(i.name)
            elif i.owner == player_id + 10:
                if i.issite():
                    prop_name_list[i.color_grp -
                                   1].append(i.get_name_with_prop_flag() +
                                             '(m-%d)' % (i.mortgage_val * 1.1))
                else:
                    prop_name_list[4].append(i.name + '(m-%d)' %
                                             (i.mortgage_val * 1.1))
            else:
                pass
        return (", ".join([
            (color_coded[i + 10] + '%s:%d' %
             (color_code[i], len(prop_name_list[i])) + color_coded[8])
            for i in range(5)
        ]) + "|" + ('\n|      |          |        |          |' + ' ' * 23 +
                    '|').join([
                        color_coded[i + 10] + '%s' %
                        (",".join(prop_name_list[i])) + color_coded[8]
                        for i in range(5) if len(prop_name_list[i]) > 0
                    ]))

    def sell_asset_to_player(self, player_id, asset_id):
        asset = self.get_asset_by_assetid(asset_id)
        if asset.owner == 0:
            self.logObj.printer(color_coded[11] +
                                "You reached on %s\n" % asset.name +
                                color_coded[8])
            player_mort_assets = self.get_players_mort_assets(player_id)
            if player_mort_assets == 0:
                if self.accounts[player_id].isenoughbalance(asset.buy_price):
                    player_buyconsent = self.PlayerBuyMenu.runMenu()
                    if player_buyconsent == 1:
                        self.accounts[player_id].withdraw(
                            asset.buy_price,
                            "Asset %s purchase from Bank" % asset.name)
                        self.accounts[0].deposit(
                            asset.buy_price, "Asset %s sale to Player-%d" %
                            (asset.name, player_id))
                        asset.owner = player_id
                        self.prop_vacancy_set(player_id, asset)
                        self.logObj.printer(color_coded[11] + "Purchase done" +
                                            color_coded[8])
                        return 0
                    else:
                        self.logObj.printer(
                            color_coded[13] +
                            "Player-%d not interested in purchase." %
                            player_id + color_coded[8])
                else:
                    self.logObj.printer(
                        color_coded[10] +
                        "Player-%d has not sufficient balance to buy." %
                        player_id + color_coded[8])
            else:
                self.logObj.printer(
                    color_coded[10] +
                    'You have already mortgaged %d assets to bank.\nYou can not buy any property till you have any mortgaged one.\n'
                    % player_mort_assets + color_coded[8])
            return 2
        elif asset.owner == player_id:
            self.logObj.printer(color_coded[11] +
                                "You reached on your own property" +
                                color_coded[8])
        elif asset.owner < 10:
            rent = self.get_current_rent_by_assetid(asset_id)
            self.logObj.printer(
                color_coded[10] +
                "You reached on %s which attracts rent of $%d" %
                (asset.name, rent) + color_coded[8])
            if self.accounts[player_id].isenoughbalance(rent) is False:
                if self.raise_cash(player_id, rent):
                    pass
                else:
                    return -1  # return -1 for removing the player
            self.accounts[player_id].withdraw(
                rent, "Asset %s rent to Player-%d" % (asset.name, asset.owner))
            self.accounts[asset.owner].deposit(
                rent, "Asset %s rent from Player-%d" % (asset.name, player_id))
            return 1
        else:
            self.logObj.printer(
                color_coded[11] +
                "You reached on a mortgaged property. No need to pay any rent."
                + color_coded[8])
        return 1

    def auction_of_asset(self, asset_id):
        asset = self.get_asset_by_assetid(asset_id)
        min_acceptable = int(asset.buy_price * 0.6)
        bid_price = min_acceptable
        bidders_acc_ids = [
            i.id for i in self.accounts if i.id != 0
            if i.balance >= min_acceptable
            and self.get_players_mort_assets(i.id) == 0
        ]
        if len(bidders_acc_ids) == 0:
            self.logObj.printer("No eligible player is there for auction.")
            return -1
        elif len(bidders_acc_ids) == 1:
            self.logObj.printer(
                "Only Player-%d is eligible for this auction." %
                bidders_acc_ids[0])
            player_buyconsent = self.PlayerBuyMenu.runMenu()
            if player_buyconsent == 1:
                self.accounts[bidders_acc_ids[0]].withdraw(
                    min_acceptable, "Asset %s purchase from Bank" % asset.name)
                self.accounts[0].deposit(
                    min_acceptable, "Asset %s sale to Player-%d" %
                    (asset.name, bidders_acc_ids[0]))
                asset.owner = bidders_acc_ids[0]
                self.prop_vacancy_set(bidders_acc_ids[0], asset)
                self.logObj.printer(color_coded[11] + "Purchase done" +
                                    color_coded[8])
                return bidders_acc_ids[0]
            else:
                self.logObj.printer(color_coded[13] +
                                    "Player-%d not interested in purchase." %
                                    player_id + color_coded[8])
            return 0
        else:
            turnid = 0
            bidmenu = MenuBox("Bid Menu", self.logPath)
            price_dict = {1: 1, 2: 10, 3: 50, 4: 100, 5: 200, 6: 500}
            while len(bidders_acc_ids) > 1:
                bidmenu.cleanOptions()
                self.logObj.printer("\nPlayer-%d" % bidders_acc_ids[turnid])
                self.logObj.printer("Current Bid Price = %d" % bid_price)
                for i in range(1, 7):
                    if self.accounts[bidders_acc_ids[
                            turnid]].balance >= bid_price + price_dict[i]:
                        bidmenu.addOption('+' + str(price_dict[i]))
                    else:
                        break
                if bidmenu.getoptioncount() == 1:
                    self.logObj.printer(
                        "Player-%d is out of auction process now." %
                        bidders_acc_ids[turnid])
                    del bidders_acc_ids[turnid]
                    turnid %= len(bidders_acc_ids)
                else:
                    opt = bidmenu.runMenu()
                    if opt != bidmenu.getoptioncount():
                        bid_price += price_dict[opt]
                        self.logObj.printer("Your Bid Price = %d" % bid_price)
                        turnid = (turnid + 1) % len(bidders_acc_ids)
                    else:
                        self.logObj.printer(
                            "Player-%d is out of auction process now." %
                            bidders_acc_ids[turnid])
                        del bidders_acc_ids[turnid]
                        turnid %= len(bidders_acc_ids)
            self.logObj.printer("Player-%d is purchasing %s" %
                                (bidders_acc_ids[0], asset.name))
            self.accounts[bidders_acc_ids[0]].withdraw(
                bid_price, "Asset %s purchase from Bank" % asset.name)
            self.accounts[0].deposit(
                bid_price, "Asset %s sale to Player-%d" %
                (asset.name, bidders_acc_ids[0]))
            asset.owner = bidders_acc_ids[0]
            self.prop_vacancy_set(bidders_acc_ids[0], asset)
            self.logObj.printer(color_coded[11] + "Purchase done" +
                                color_coded[8])
            return bidders_acc_ids[0]

    def sell_building_to_player(self, player_id, asset_id):
        asset = self.get_asset_by_assetid(asset_id)
        if asset.owner == player_id:
            if asset.prop_vacancy:
                if self.accounts[player_id].isenoughbalance(asset.prop_price):
                    try:
                        asset.prop_count += 1
                        self.accounts[player_id].withdraw(
                            asset.prop_price,
                            "Building purchase on %s" % asset.name)
                        self.accounts[0].deposit(
                            asset.prop_price,
                            "Building sale to Player-%d" % player_id)
                        self.prop_vacancy_set(player_id, asset)
                        self.prop_sell_set(player_id, asset)
                        self.logObj.printer(
                            color_coded[11] +
                            "Building purchase done. Remaining balance = $%d" %
                            self.accounts[player_id].balance + color_coded[8])
                    except ValueError:
                        self.logObj.printer(
                            color_coded[10] +
                            "You can not raise more buildings on %s. Already 4."
                            % asset.name + color_coded[8])
                else:
                    self.logObj.printer(
                        color_coded[10] +
                        "You don't have sufficient balance to raise building on %s"
                        % asset.name + color_coded[8])
            else:
                self.logObj.printer(color_coded[10] + "No more building allowed on %s. It has either 4 buildings or more building " \
                                    "than your other sites of same color." % asset.name + color_coded[8])
        elif asset.owner == player_id + 10:
            self.logObj.printer(
                color_coded[10] +
                "You can not raise building on your mortgaged property (%s)." %
                asset.name + color_coded[8])
        else:
            self.logObj.printer(
                color_coded[10] +
                "You can not raise building on property (%s) as not owner." %
                asset.name + color_coded[8])

    def get_building_from_player(self, player_id, asset_id):
        asset = self.get_asset_by_assetid(asset_id)
        if asset.owner == player_id:
            sell_price = asset.prop_price / 2
            if asset.prop_sell:
                if self.accounts[0].isenoughbalance(sell_price):
                    try:
                        asset.prop_count -= 1
                        self.accounts[0].withdraw(
                            sell_price,
                            "Building re-purchase from Player-%d" % player_id)
                        self.accounts[player_id].deposit(
                            sell_price, "Building sale from %s" % asset.name)
                        self.prop_vacancy_set(player_id, asset)
                        self.prop_sell_set(player_id, asset)
                        self.logObj.printer(
                            color_coded[11] +
                            "Building sell done. Remaining balance = $%d" %
                            self.accounts[player_id].balance + color_coded[8])
                    except ValueError:
                        self.logObj.printer(
                            color_coded[10] +
                            "You can not sell more buildings on %s. Already 0."
                            % asset.name + color_coded[8])
                else:
                    self.logObj.printer(
                        color_coded[10] +
                        "Bank doesn't have sufficient balance to purchase your building on %s"
                        % asset.name + color_coded[8])
            else:
                self.logObj.printer(color_coded[10] + "You can not sell buildings on %s as it has no building or lesser buildings " \
                                    "than your other properties of same color." % asset.name + color_coded[8])
        else:
            self.logObj.printer(
                color_coded[10] +
                "You can not sell buildings on %s as not owner." % asset.name +
                color_coded[8])
            raise ValueError

    def mortgage_asset_of_player(self, player_id, asset_id):
        asset = self.get_asset_by_assetid(asset_id)
        if asset.owner == player_id:
            mort_amount = asset.mortgage_val
            if self.accounts[0].isenoughbalance(mort_amount):
                asset.owner = player_id + 10
                asset.prop_vacancy = False
                self.accounts[0].withdraw(
                    mort_amount, "Asset %s mortgage from Player-%d" %
                    (asset.name, player_id))
                self.accounts[player_id].deposit(
                    mort_amount, "Asset %s mortgaged to bank" % asset.name)
                self.logObj.printer(
                    color_coded[11] +
                    "Asset mortgage done. Remaining balance = $%d" %
                    self.accounts[player_id].balance + color_coded[8])
            else:
                self.logObj.printer(
                    color_coded[10] +
                    "Bank doesn't have sufficient balance to give mortgage value of %s"
                    % asset.name + color_coded[8])
        else:
            self.logObj.printer(color_coded[10] +
                                "You can not mortgage other player's asset" +
                                color_coded[8])
            print "player id = %d" % player_id
            print "asset id = %d" % asset_id
            raise ValueError

    def redeem_asset_of_player(self, player_id, asset_id):
        asset = self.get_asset_by_assetid(asset_id)
        if asset.owner == player_id + 10:
            mort_amount = int(asset.mortgage_val * 1.1)
            if self.accounts[player_id].isenoughbalance(mort_amount):
                asset.owner = player_id
                self.prop_vacancy_set(player_id, asset)
                self.prop_sell_set(player_id, asset)
                self.accounts[player_id].withdraw(
                    mort_amount, "Asset %s redeemed from Bank" % (asset.name))
                self.accounts[0].deposit(
                    mort_amount,
                    "Asset %s redeemed by Player-%d" % (asset.name, player_id))
                self.logObj.printer(
                    color_coded[11] +
                    "Asset redemption done. Remaining balance = $%d" %
                    self.accounts[player_id].balance + color_coded[8])
            else:
                self.logObj.printer(
                    color_coded[10] +
                    "Player-%d doesn't have sufficient balance to redeem %s" %
                    (player_id, asset.name) + color_coded[8])
        else:
            self.logObj.printer(
                color_coded[10] +
                "You can not redeem other player's mortgaged asset." %
                asset.name + color_coded[8])
            raise ValueError

    def prop_vacancy_set(self, player_id, asset):
        if asset.issite():
            col_grp_count = len([
                1 for i in self.asset_list if i.issite()
                if i.owner == player_id and i.color_grp == asset.color_grp
            ])
            if col_grp_count >= 3:
                prop_cnt_list = [
                    i.prop_count for i in self.asset_list if i.issite()
                    if i.owner == player_id and i.color_grp == asset.color_grp
                ]
                fl_list = [
                    True if i == min(prop_cnt_list) and min(prop_cnt_list) != 4
                    else False for i in prop_cnt_list
                ]
                for i in self.asset_list:
                    if i.issite():
                        if i.owner == player_id and i.color_grp == asset.color_grp:
                            i.prop_vacancy = fl_list[0]
                            del fl_list[0]

    def prop_sell_set(self, player_id, asset):
        if asset.issite():
            prop_cnt_list = [
                i.prop_count for i in self.asset_list if i.issite()
                if i.owner == player_id and i.color_grp == asset.color_grp
            ]
            fl_list = [
                True if i == max(prop_cnt_list) and max(prop_cnt_list) != 0
                else False for i in prop_cnt_list
            ]
            for i in self.asset_list:
                if i.issite():
                    if i.owner == player_id and i.color_grp == asset.color_grp:
                        i.prop_sell = fl_list[0]
                        del fl_list[0]

    def payreward(self, player_id, amount, msg):
        if self.accounts[0].isenoughbalance(amount) is False:
            return [0]
        self.accounts[0].withdraw(amount, msg)
        self.accounts[player_id].deposit(amount, msg)
        return []

    def p2ptransaction(self, payee_id, recep_id, amount, msg):
        if amount == -1:
            factor = 1
            if msg == "custom duty": factor = 2
            amount = self.get_players_countries(payee_id) * 50 * factor
            if amount > 500 * factor:
                amount = 500 * factor
        if self.accounts[payee_id].isenoughbalance(amount) is False:
            if self.raise_cash(payee_id, amount) is False:
                return [payee_id]
        self.accounts[payee_id].withdraw(amount, msg)
        self.accounts[recep_id].deposit(amount, msg)
        return []
Exemple #6
0
 def __init__(self, id, name, balance=0):
     self.id = id
     self.name = name
     self.balance = balance
     self.transaction_statement = Printer()
     self.state = True
Exemple #7
0
from Smartcontroller import Smartcontroller
from MenuBox import MenuBox, Printer, DBhandler, color_coded
import os

if not os.path.exists("business_game_logs"): os.makedirs("business_game_logs")
logPath = "./business_game_logs/business.logs"
p = Printer(logPath)
try:
    dbuser = raw_input(color_coded[11] +
                       "Enter the username for MySQL DB (default root): " +
                       color_coded[8])
    if dbuser == "": dbuser = '******'
    dbpassword = raw_input(color_coded[11] +
                           "Enter the password for MySQL DB (default root): " +
                           color_coded[8])
    if dbpassword == "": dbpassword = '******'
    dx = None
    try:
        dx = DBhandler(dbuser, dbpassword)
    except:
        p.printer(
            color_coded[10] +
            "Connection failed to MySQL server. You will not be able to save the ongoing game for later."
            + color_coded[8])
    gameretrieve = MenuBox("INTERNATIONAL BUSINESS GAME", logPath)
    gameStartMenu = MenuBox("Start Game:", logPath)
    gameStartMenu.addOptions(["4 Player ", "3 Player ", "2 Player "])
    if dx is not None:
        gameretrieve.addOptions(["Retrieve saved game", "New Game"])
        optionRecv = 4
        option = gameretrieve.runMenu()