awacke1's picture
Update app.py
9b5a354
import os
import random
import streamlit as st
import base64
# 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)
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
def start_game():
"""Initializes the game state and starts the game."""
game_state = {'player_cards': [], 'ai_cards': [], 'player_score': 0, 'ai_score': 0, 'rounds_played': 0}
deck = shuffle_deck()
game_state['player_cards'] = deck[:26]
game_state['ai_cards'] = deck[26:]
return game_state
# Define the game UI
def game_ui(game_state):
"""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('Play'):
if player_card is None:
st.write('Out of cards!')
return
winner = determine_winner(player_card, ai_card)
if winner == 'player':
st.write('Player wins!')
game_state['player_cards'].extend([player_card, ai_card])
game_state['player_score'] += 2
elif winner == 'ai':
st.write('Dealer wins!')
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 = start_game()
# 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('Reset Game'):
# Reset game state
game_state = start_game()
# Truncate game_state.txt file by deleting it and reloading it
os.remove('game_state.txt')
open('game_state.txt', 'w').close()
# 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'):
if checkbox:
with open('game_state.txt', 'r') as f:
lines = f.readlines()
headers = [header.strip() for header in lines[0].strip().split(',')]
data = [
[eval(cell) if cell.isdigit() else cell for cell in line.strip().split(',')]
for line in lines[1:]
]
st.dataframe(data, columns=headers)
# Add download button for game history
if st.sidebar.button('Download Game History'):
st.sidebar.markdown(create_download_link('game_state.txt'), unsafe_allow_html=True)
# Load game state from file or start new game
if os.path.exists('game_state.txt'):
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])
else:
game_state = start_game()
game_state = start_game()
game_ui(game_state)