File size: 6,487 Bytes
a61c8c2
784add3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a61c8c2
784add3
 
 
 
 
a61c8c2
784add3
 
 
 
 
 
 
2c6b833
 
a61c8c2
 
 
2c6b833
784add3
 
 
 
 
 
 
 
 
 
 
 
2c6b833
 
a61c8c2
 
2c6b833
784add3
2c6b833
784add3
a61c8c2
 
 
784add3
 
2c6b833
a61c8c2
784add3
a61c8c2
 
 
 
 
 
784add3
2c6b833
 
 
 
 
 
 
 
 
bd783b5
 
a61c8c2
bd783b5
 
 
 
 
 
 
 
 
 
a9ae883
 
 
 
 
 
 
 
 
 
 
 
5296ecf
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import os
import random
import streamlit as st

# Define the game rules
NUM_ROUNDS = 26
CARD_VALUES = {
    'A': 14,
    'K': 13,
    'Q': 12,
    'J': 11,
    '10': 10,
    '9': 9,
    '8': 8,
    '7': 7,
    '6': 6,
    '5': 5,
    '4': 4,
    '3': 3,
    '2': 2,
}

# Define the game mechanics
def shuffle_deck():
    """Returns a shuffled deck of cards."""
    deck = [(value, suit) for value in CARD_VALUES for suit in ['♠', '♡', '♢', '♣']]
    random.shuffle(deck)
    return deck

def draw_card(deck):
    """Draws a card from the top of the deck and removes it from the deck."""
    if len(deck) == 0:
        return None
    return deck.pop(0)

def compare_cards(card1, card2):
    """Compares the values of two cards and returns the winner."""
    value1 = CARD_VALUES[card1[0]]
    value2 = CARD_VALUES[card2[0]]
    if value1 > value2:
        return 'player'
    elif value2 > value1:
        return 'ai'
    else:
        return 'tie'

def determine_winner(player_card, ai_card):
    """Determines the winner of the round based on the values of the cards."""
    if player_card is None:
        return 'ai'
    elif ai_card is None:
        return 'player'
    else:
        return compare_cards(player_card, ai_card)

# Define the game UI
def game_ui():
    """Displays the game UI and updates the game state."""
    player_cards = game_state['player_cards']
    ai_cards = game_state['ai_cards']
    player_card = player_cards[-1] if len(player_cards) > 0 else None
    ai_card = ai_cards[-1] if len(ai_cards) > 0 else None

    st.write('# Peace and Love')
    st.write('---')

    st.write('**Player**')
    st.write('Cards: ', ' '.join([f"{card[0]}{card[1]}" for card in player_cards]))
    st.write('Score: ', game_state['player_score'])
    st.write('---')

    st.write('**Dealer**')
    st.write('Cards: ', ' '.join([f"🂠" if len(ai_cards) == 1 else f"{card[0]}{card[1]}" for card in ai_cards]))
    st.write('Score: ', game_state['ai_score'])
    st.write('---')

    if st.button('Draw'):
        st.write('---')
        st.write('You drew:', f"{player_card[0]}{player_card[1]}")
        st.write('Dealer drew:', f"🂠" if len(ai_cards) == 1 else f"{ai_card[0]}{ai_card[1]}")
        winner = determine_winner(player_card, ai_card)
        if winner == 'player':
            st.write('You won this round!')
            game_state['player_cards'].extend([player_card, ai_card])
            game_state['player_score'] += 2
        elif winner == 'ai':
            st.write('Dealer won this round!')
            game_state['ai_cards'].extend([player_card, ai_card])
            game_state['ai_score'] += 2
    
        else:
            st.write('Tie!')
            game_state['player_cards'].append(player_card)
            game_state['ai_cards'].append(ai_card)

        game_state['rounds_played'] += 1

        # Save game state to file
        with open('game_state.txt', 'w') as f:
            if not os.path.exists('game_state.txt'):
                f.write('player_cards,ai_cards,player_score,ai_score,rounds_played\n')
            f.write(','.join([str(game_state[key]) for key in game_state.keys()]) + '\n')

    st.sidebar.write('---')
    if st.sidebar.button('New Game'):
        # Reset game state
        game_state['player_cards'] = []
        game_state['ai_cards'] = []
        game_state['player_score'] = 0
        game_state['ai_score'] = 0
        game_state['rounds_played'] = 0
        deck = shuffle_deck()
        game_state['player_cards'] = deck[:26]
        game_state['ai_cards'] = deck[26:]

        # Save game state to file
        with open('game_state.txt', 'w') as f:
            f.write('player_cards,ai_cards,player_score,ai_score,rounds_played\n')
            f.write(','.join([str(game_state[key]) for key in game_state.keys()]) + '\n')

    if st.sidebar.button('Save'):
        # Save game state to file
        with open('game_state.txt', 'w') as f:
            if not os.path.exists('game_state.txt'):
                f.write('player_cards,ai_cards,player_score,ai_score,rounds_played\n')
            f.write(','.join([str(game_state[key]) for key in game_state.keys()]) + '\n')

    if st.sidebar.button('Reload'):
        # Reload game state from file
        game_state = {'player_cards': [], 'ai_cards': [], 'player_score': 0, 'ai_score': 0, 'rounds_played': 0}
        with open('game_state.txt', 'r') as f:
            headers = f.readline().strip().split(',')
            data = f.readlines()
            if len(data) > 0:
                last_line = data[-1].strip().split(',')
                for i in range(len(headers)):
                    game_state[headers[i]] = eval(last_line[i])

    # Show game history
    st.write('# Game History')
    if not st.checkbox('Show game history'):
        return
    with open('game_state.txt', 'r') as f:
        lines = f.readlines()
        headers = [header.strip() for header in lines[0].strip().split(',')]
        data = [[cell.strip() for cell in line.strip().split(',')] for line in lines[1:]]
        st.write(st.dataframe(data, columns=headers))

# Play the game
game_state = {'player_cards': [], 'ai_cards': [], 'player_score': 0, 'ai_score': 0, 'rounds_played': 0}
while game_state['rounds_played'] < NUM_ROUNDS and len(game_state['player_cards']) + len(game_state['ai_cards']) == 52:
    game_ui()

    player_card = draw_card(game_state['player_cards'])
    ai_card = draw_card(game_state['ai_cards'])
    winner = determine_winner(player_card, ai_card)

    if winner == 'player':
        game_state['player_cards'].extend([player_card, ai_card])
        game_state['player_score'] += 2
    else:
        game_state['player_cards'].append(player_card)
        game_state['ai_cards'].append(ai_card)

    game_state['rounds_played'] += 1

    # Save game state to file
    with open('game_state.txt', 'w') as f:
        if not os.path.exists('game_state.txt'):
            f.write('player_cards,ai_cards,player_score,ai_score,rounds_played\n')
        f.write(','.join([str(game_state[key]) for key in game_state.keys()]) + '\n')

import base64

def create_download_link(filename):
    with open(filename, 'r') as f:
        text = f.read()
    b64 = base64.b64encode(text.encode()).decode()
    href = f'<a href="data:file/txt;base64,{b64}" download="{filename}">Download {filename}</a>'
    return href

if st.sidebar.button('Download Game State'):
    st.sidebar.markdown(create_download_link('game_state.txt'), unsafe_allow_html=True)