Spaces:
Sleeping
Sleeping
# Import necessary libraries | |
import streamlit as st | |
import random | |
import time | |
# Initialize game state and player names | |
def initialize_game(): | |
with open("game_state.txt", "w") as f: | |
f.write("Player 1:100,Player 2:100,Player 1") | |
with open("player1_actions.txt", "w") as f: | |
f.write("") | |
with open("player2_actions.txt", "w") as f: | |
f.write("") | |
# Read game state | |
def read_game_state(): | |
with open("game_state.txt", "r") as f: | |
state = f.readline().split(',') | |
p1_name, p1_hp = state[0].split(':') | |
p2_name, p2_hp = state[1].split(':') | |
turn = state[2] | |
return p1_name, int(p1_hp), p2_name, int(p2_hp), turn | |
# Write player action | |
def write_action(player, action): | |
if player == "Player 1": | |
with open("player1_actions.txt", "w") as f: | |
f.write(action) | |
else: | |
with open("player2_actions.txt", "w") as f: | |
f.write(action) | |
# Update game state based on actions | |
def update_game_state(): | |
p1_name, p1_hp, p2_name, p2_hp, turn = read_game_state() | |
# Read Player 1's action | |
with open("player1_actions.txt", "r") as f: | |
p1_action = f.readline().strip() | |
# Read Player 2's action | |
with open("player2_actions.txt", "r") as f: | |
p2_action = f.readline().strip() | |
# Update game based on actions | |
if turn == "Player 1" and p1_action: | |
if p1_action == "Attack": | |
damage = random.randint(5, 15) | |
p2_hp -= damage | |
elif p1_action == "Heal": | |
heal = random.randint(5, 10) | |
p1_hp += heal | |
turn = "Player 2" | |
elif turn == "Player 2" and p2_action: | |
if p2_action == "Attack": | |
damage = random.randint(5, 15) | |
p1_hp -= damage | |
elif p2_action == "Heal": | |
heal = random.randint(5, 10) | |
p2_hp += heal | |
turn = "Player 1" | |
# Write updated game state | |
with open("game_state.txt", "w") as f: | |
f.write(f"{p1_name}:{p1_hp},{p2_name}:{p2_hp},{turn}") | |
# Streamlit Interface | |
def app(): | |
st.title("Text Battle!") | |
# Initialize game if not already initialized | |
if not st.session_state.get("initialized"): | |
initialize_game() | |
st.session_state.initialized = True | |
p1_name, p1_hp, p2_name, p2_hp, turn = read_game_state() | |
st.write(f"{p1_name} HP: {p1_hp}") | |
st.write(f"{p2_name} HP: {p2_hp}") | |
if p1_hp <= 0: | |
st.write(f"{p2_name} Wins!") | |
st.stop() | |
elif p2_hp <= 0: | |
st.write(f"{p1_name} Wins!") | |
st.stop() | |
# Player actions | |
if turn == "Player 1": | |
action = st.selectbox("Player 1, choose your action:", ["", "Attack", "Heal", "Pass"]) | |
if st.button("Submit"): | |
write_action("Player 1", action) | |
update_game_state() | |
else: | |
action = st.selectbox("Player 2, choose your action:", ["", "Attack", "Heal", "Pass"]) | |
if st.button("Submit"): | |
write_action("Player 2", action) | |
update_game_state() | |
# Refresh game state every 3 seconds | |
time.sleep(3) | |
st.experimental_rerun() | |
# Run the Streamlit app | |
app() | |