CoolFace
Apppublic

awacke1/CardGameActivity-TwoPlayerAndAI

sourceHugging Facemitupdated 4y agoView on Hugging Face
1likes
app.py194 linesDownload Raw Back to root
1import os2import random3import streamlit as st4import base645 6# Define the game rules7NUM_ROUNDS = 268CARD_VALUES = {9    'A': 14,10    'K': 13,11    'Q': 12,12    'J': 11,13    '10': 10,14    '9': 9,15    '8': 8,16    '7': 7,17    '6': 6,18    '5': 5,19    '4': 4,20    '3': 3,21    '2': 2,22}23 24# Define the game mechanics25def shuffle_deck():26    """Returns a shuffled deck of cards."""27    deck = [(value, suit) for value in CARD_VALUES for suit in ['♠', '♡', '♢', '♣']]28    random.shuffle(deck)29    return deck30 31def draw_card(deck):32    """Draws a card from the top of the deck and removes it from the deck."""33    if len(deck) == 0:34        return None35    return deck.pop(0)36 37def compare_cards(card1, card2):38    """Compares the values of two cards and returns the winner."""39    value1 = CARD_VALUES[card1[0]]40    value2 = CARD_VALUES[card2[0]]41    if value1 > value2:42        return 'player'43    elif value2 > value1:44        return 'ai'45    else:46        return 'tie'47 48def determine_winner(player_card, ai_card):49    """Determines the winner of the round based on the values of the cards."""50    if player_card is None:51        return 'ai'52    elif ai_card is None:53        return 'player'54    else:55        return compare_cards(player_card, ai_card)56 57def create_download_link(filename):58    with open(filename, 'r') as f:59        text = f.read()60    b64 = base64.b64encode(text.encode()).decode()61    href = f'<a href="data:file/txt;base64,{b64}" download="{filename}">Download {filename}</a>'62    return href63 64def start_game():65    """Initializes the game state and starts the game."""66    game_state = {'player_cards': [], 'ai_cards': [], 'player_score': 0, 'ai_score': 0, 'rounds_played': 0}67    deck = shuffle_deck()68    game_state['player_cards'] = deck[:26]69    game_state['ai_cards'] = deck[26:]70    return game_state71 72# Define the game UI73def game_ui(game_state):74    """Displays the game UI and updates the game state."""75    player_cards = game_state['player_cards']76    ai_cards = game_state['ai_cards']77    player_card = player_cards[-1] if len(player_cards) > 0 else None78    ai_card = ai_cards[-1] if len(ai_cards) > 0 else None79 80    st.write('# Peace and Love')81    st.write('---')82 83    st.write('**Player**')84    st.write('Cards: ', ' '.join([f"{card[0]}{card[1]}" for card in player_cards]))85    st.write('Score: ', game_state['player_score'])86    st.write('---')87 88    st.write('**Dealer**')89    st.write('Cards: ', ' '.join([f"🂠" if len(ai_cards) == 1 else f"{card[0]}{card[1]}" for card in ai_cards]))90    st.write('Score: ', game_state['ai_score'])91    st.write('---')92 93    if st.button('Play'):94        if player_card is None:95            st.write('Out of cards!')96            return97 98        winner = determine_winner(player_card, ai_card)99 100        if winner == 'player':101            st.write('Player wins!')102            game_state['player_cards'].extend([player_card, ai_card])103            game_state['player_score'] += 2104        elif winner == 'ai':105            st.write('Dealer wins!')106            game_state['ai_cards'].extend([player_card, ai_card])107            game_state['ai_score'] += 2108        else:109            st.write('Tie!')110            game_state['player_cards'].append(player_card)111            game_state['ai_cards'].append(ai_card)112 113        game_state['rounds_played'] += 1114 115        # Save game state to file116        with open('game_state.txt', 'w') as f:117            if not os.path.exists('game_state.txt'):118                f.write('player_cards,ai_cards,player_score,ai_score,rounds_played\n')119            f.write(','.join([str(game_state[key]) for key in game_state.keys()]) + '\n')120 121    st.sidebar.write('---')122    if st.sidebar.button('New Game'):123        # Reset game state124        game_state = start_game()125 126        # Save game state to file127        with open('game_state.txt', 'w') as f:128            f.write('player_cards,ai_cards,player_score,ai_score,rounds_played\n')129            f.write(','.join([str(game_state[key]) for key in game_state.keys()]) + '\n')130 131    if st.sidebar.button('Reset Game'):132        # Reset game state133        game_state = start_game()134 135        # Truncate game_state.txt file by deleting it and reloading it136        os.remove('game_state.txt')137        open('game_state.txt', 'w').close()138 139        # Save game state to file140        with open('game_state.txt', 'w') as f:141            f.write('player_cards,ai_cards,player_score,ai_score,rounds_played\n')142            f.write(','.join([str(game_state[key]) for key in game_state.keys()]) + '\n')143 144    if st.sidebar.button('Save'):145        # Save game state to file146        with open('game_state.txt', 'w') as f:147            if not os.path.exists('game_state.txt'):148                f.write('player_cards,ai_cards,player_score,ai_score,rounds_played\n')149            f.write(','.join([str(game_state[key]) for key in game_state.keys()]) + '\n')150 151    if st.sidebar.button('Reload'):152        # Reload game state from file153        game_state = {'player_cards': [], 'ai_cards': [], 'player_score': 0, 'ai_score': 0, 'rounds_played': 0}154        with open('game_state.txt', 'r') as f:155            headers = f.readline().strip().split(',')156            data = f.readlines()157            if len(data) > 0:158                last_line = data[-1].strip().split(',')159                for i in range(len(headers)):160                    game_state[headers[i]] = eval(last_line[i])161 162    # Show game history163    st.write('# Game History')164    if not st.checkbox('Show game history'):165        if checkbox:166            with open('game_state.txt', 'r') as f:167                lines = f.readlines()168                headers = [header.strip() for header in lines[0].strip().split(',')]169                data = [170                    [eval(cell) if cell.isdigit() else cell for cell in line.strip().split(',')]171                    for line in lines[1:]172                ]173            st.dataframe(data, columns=headers)174 175    # Add download button for game history176    if st.sidebar.button('Download Game History'):177        st.sidebar.markdown(create_download_link('game_state.txt'), unsafe_allow_html=True)178 179# Load game state from file or start new game180if os.path.exists('game_state.txt'):181    game_state = {'player_cards': [], 'ai_cards': [], 'player_score': 0, 'ai_score': 0, 'rounds_played': 0}182    with open('game_state.txt', 'r') as f:183        headers = f.readline().strip().split(',')184        data = f.readlines()185        if len(data) > 0:186            last_line = data[-1].strip().split(',')187#            for i in range(len(headers)):188#                game_state[headers[i]] = eval(last_line[i])189else:190    game_state = start_game()191 192game_state = start_game()193game_ui(game_state)194