python discord.py二十一点游戏,输了就给硬币

问题描述 投票:1回答:1

[我制作了一个discord.py 4甲板二十一点游戏,您从/blackjack <bet>开始,然后在其中进行/blackjack hit/blackjack stand/blackjack double/blackjack split之类的动作。


############################
# Setup stuff like imports #
############################

def setcoins(uid, value, *, raw=False):
    '''Set the amount of coins someone has.'''
    try:
        if raw:
            coins[uid][0] = value
        elif value > getcoins(uid): # increased coins
            ## there is a perk that you can get that increases your earnings by 0.8% per level ( which is stored in coins[uid][7][2] )
            earned_raw = (value - getcoins(uid)) * (1 + 0.008*coins[uid][7][2])
            earned, earned_frac = int(earned_raw), (earned_raw - int(earned_raw))
            # round randomly
            print(f'Value {value} Bonus {coins[uid][7][2]} EarnedRaw {earned_raw}')
            if coinrandom.random() > earned_frac:
                earned_frac = 0
            else:
                earned_frac = 1
            coins[uid][0] = getcoins(uid) + earned + earned_frac
        else:
            coins[uid][0] = value
    except Exception as e:
        print(e)
        coins[uid] = [value, time.time()+1, time.time()+1, 0, 320, time.time()+600, 0, [False, 0, 0, 0, time.time()+600]]

## this seems to be working fine
def get_blackjack_sum(cards):
    '''Get the value of the player's cards.'''
    total = 0
    aces = 0
    for i in cards:
        i = i[:-1]
        if i == 'A':
            total += 11
            aces += 1
        elif i in ('2','3','4','5','6','7','8','9'):
            total += int(i)
        elif i in ('10','J','Q','K'):
            total += 10
    while total > 21 and aces >= 1:
        total -= 10
        aces -= 1
    return total

## this seems to be working fine
def get_blackjack_outcome(deck, player_cards, dealer_cards, *, name='Anonymous', amount=2):
    '''Return a list [a, b] where :a: is the feedback message and :b: is playerwin:True tie:0 dealerwin:False'''
    # get totals
    player = get_blackjack_sum(player_cards)
    dealer = get_blackjack_sum(dealer_cards)
    # dealer getting cards phase
    while dealer < 17:
        dealer_cards.append(deck.pop())
        dealer = get_blackjack_sum(dealer_cards)
    # show final outcome
    player_graphic = '`' + '` `'.join(player_cards) + f'`\n**Total**: {player}'
    dealer_graphic = '`' + '` `'.join(dealer_cards) + f'`\n**Total**: {dealer}'
    embed = discord.Embed(title=f"**{name}'s** blackjack game ({amount} coins)", description='`/blackjack [hit | stand | surrender | double]`', color=0x00aa00)
    embed.add_field(name='**You**', value=player_graphic, inline=True)
    embed.add_field(name='**Dealer**', value=dealer_graphic, inline=True)
    # win or lose checking
    if player > 21:
        return '**You busted! You lose!**', False, embed
    elif dealer > 21:
        return '**The dealer busted! You win!**', True, embed
    elif player > dealer:
        return f'**You beat the dealer, {player} to {dealer}! You win!**', True, embed
    elif player < dealer:
        return f'**The dealer beat you, {player} to {dealer}. You lose!**', False, embed
    elif player == dealer:
        return f'**It was a tie, {player} to {dealer}. You push and nothing happens.**', 0, embed

#############################
# other functions and stuff #
#############################

@client.event
async def on_message(message):
    '''Main bot code running on message.'''
    if message.author == client.user:
        return
    global searchusers, bank_cooldown, blackjack_games, embed_builds
    if message.content.startswith('/'):
        user = message.author.id
        name = message.author.display_name
        text = message.content[1:].strip()
        command = text.split(' ')[0]
        subcommand = text.split(' ')[1:]

        ######################
        # other bot commands #
        ######################

        if command == 'blackjack': # no events triggered
            if len(subcommand) < 1:
                await message.channel.send('Missing arguments! `/blackjack <amount>` or `/blackjack <action>`')
            elif user in blackjack_games['split'].keys() and user not in blackjack_games.keys():
                #################################################################################
                # this stuff is basically the same thing as the code below so i wont include it #
                #################################################################################

            elif user in blackjack_games.keys():
                amount = blackjack_games[user][0]
                deck = blackjack_games[user][1]
                player = blackjack_games[user][2]
                dealer = blackjack_games[user][3]
                if subcommand[0] == 'hit':
                    player.append(deck.pop())
                    player_graphic = '`' + '` `'.join(player) + f'`\n**Total**: {get_blackjack_sum(player)}'
                    dealer_graphic = f'`[?]` `{dealer[1]}`\n**Total**: [?]'
                    embed = discord.Embed(title=f"**{name}**'s blackjack game ({amount} coins)", description='`/blackjack [end | hit | stand | surrender | double | split]`', color=0x00aa00)
                    embed.add_field(name='**You**', value=player_graphic, inline=True)
                    embed.add_field(name='**Dealer**', value=dealer_graphic, inline=True)
                    await message.channel.send(embed=embed)
                    if get_blackjack_sum(player) > 21:
                        await message.channel.send('**You busted! You lose!**')
                        if user in blackjack_games['split'].keys():
                            await message.channel.send(f'**{name}**, type `/blackjack split` to play your split hand.')
                        del blackjack_games[user]
                elif subcommand[0] == 'stand' or subcommand[0] == 'end':
                    feedback, status, embed = get_blackjack_outcome(deck, player, dealer, name=name, amount=amount)
                    await message.channel.send(embed=embed)
                    await message.channel.send(f'**{feedback} {status}**')
                    if status:
                        setcoins(user, getcoins(user)+2*amount)
                    elif status == 0:
                        setcoins(user, getcoins(user)+amount)
                    if user in blackjack_games['split'].keys():
                        await message.channel.send(f'**{name}**, type `/blackjack split` to play your split hand.')
                    del blackjack_games[user]
                elif subcommand[0] == 'surrender':
                    if len(player) == 2:
                        await message.channel.send('**You surrendered this hand. You will receive half your original bet back.**')
                        setcoins(user, int(getcoins(user)+0.5*amount))
                        del blackjack_games[user]
                    else:
                        await message.channel.send('You can only surrender on your first two cards! Try again with a different action.')
                elif subcommand[0] == 'double':
                    if getcoins(user) < amount:
                        await message.channel.send("You don't have enough money to double! Try again with a different action.")
                    elif len(player) != 2:
                        await message.channel.send('You can only double on your first two cards! Try again with a different action.')
                    else:
                        amount = amount * 2
                        setcoins(user, int(getcoins(user)-0.5*amount))
                        player.append(deck.pop())
                        feedback, status, embed = get_blackjack_outcome(deck, player, dealer, name=name, amount=amount)
                        await message.channel.send(embed=embed)
                        await message.channel.send(f'**{feedback}**')
                        if status:
                            setcoins(user, getcoins(user)+2*amount)
                        elif status == 0:
                            setcoins(user, getcoins(user)+amount)
                        del blackjack_games[user]
                elif subcommand[0] == 'split':
                    if getcoins(user) < amount:
                        await message.channel.send("You don't have enough money to double! Try again with a different action.")
                    elif len(player) != 2:
                        await message.channel.send('You can only split on your first two cards! Try again with a different action.')
                    elif get_blackjack_sum(player) % 2 == 0:
                        player.insert(1, deck.pop())
                        splithand = [player.pop(), deck.pop()]
                        blackjack_games['split'][user] = [amount, deck, splithand, None]
                        setcoins(user, getcoins(user)-amount)
                        player_graphic = '`' + '` `'.join(player) + f'`\n**Total**: {get_blackjack_sum(player)}'
                        dealer_graphic = f'`[?]` `{dealer[1]}`\n**Total**: [?]'
                        embed = discord.Embed(title=f"**{name}**'s blackjack game ({amount} coins)", description='`/blackjack [end | hit | stand | surrender | double | split]`', color=0x00aa00)
                        embed.add_field(name='**You**', value=player_graphic, inline=True)
                        embed.add_field(name='**Dealer**', value=dealer_graphic, inline=True)
                        await message.channel.send(embed=embed)
                #######################################################
                # some stuff about starting new games that works fine #
                #######################################################
                else:
                    await message.channel.send('Invalid action! `/blackjack [end | hit | stand | surrender | double | split]`.\nIf you want to end the game, use `/blackjack end`.')

###########################################################################
# a bunch of dumb stuff including run commands, background processes, etc #
###########################################################################

这里是显示游戏示例的屏幕截图:enter image description here

我开始游戏,做某事,然后以/blackjack stand结尾。 (余额100,000和100个硬币的下注)庄家击败了我,机器人告诉我我输了。当我随后立即查看余额时,它说我的余额为100,002(再次尝试时为100,001)。

似乎在游戏开始后(现在的余额为99,900),并且我在输入/blackjack stand后被发牌人殴打特别地输了,它使我的余额再增加100,而津贴增加了1.6%余额中,我的余额中以100,001(40%)或100,002(60%)硬币结尾。我已经检查了当我丢失这种方式时get_blackjack_outcome函数是否正在返回False的(正确)值,这在if status:if status == 0:行上不应执行任何操作。

我制作了一个以/ blackjack 开始的discord.py 4甲板二十一点游戏,然后在其中进行诸如/ blackjack hit,/ blackjack stand,/ blackjack double和/ blackjack split的操作。 ######### ...]]

python python-3.x discord discord.py blackjack
1个回答
0
投票

根据文档,布尔值是int的子类:True的行为类似于1False的行为类似于0

在我的行if status == 0:上,输入False时满足条件。通过更改get_blackjack_outcome功能进行了修正,如果玩家获胜,被推或庄家分别获胜,则返回1、2或3。

© www.soinside.com 2019 - 2024. All rights reserved.