import streamlit as st import random import json import time import os from datetime import datetime import pandas as pd # File to store game history HISTORY_FILE = "farming_game_history.json" PLAYER_FILE = "player_data.json" # Initialize session state if 'player_name' not in st.session_state: # Generate random farmer name prefixes = ["Happy", "Busy", "Lucky", "Sunny", "Green", "Golden"] nouns = ["Farmer", "Gardener", "Harvester", "Planter", "Grower"] st.session_state.player_name = f"{random.choice(prefixes)}{random.choice(nouns)}{random.randint(100,999)}" def load_game_data(): if os.path.exists(PLAYER_FILE): with open(PLAYER_FILE, 'r') as f: return json.load(f) return {} def save_game_data(data): with open(PLAYER_FILE, 'w') as f: json.dump(data, f) def load_history(): if os.path.exists(HISTORY_FILE): with open(HISTORY_FILE, 'r') as f: return json.load(f) return [] def save_history(history): with open(HISTORY_FILE, 'w') as f: json.dump(history, f) def initialize_player(player_name): return { "name": player_name, "coins": 1000, "crops": {}, "inventory": { "wheat_seeds": 5, "corn_seeds": 5, "potato_seeds": 5 }, "score": 0, "last_action": time.time() } class FarmGame: def __init__(self): self.crops = { "wheat": {"growth_time": 5, "value": 100, "seed_cost": 20, "emoji": "🌾"}, "corn": {"growth_time": 7, "value": 150, "seed_cost": 30, "emoji": "🌽"}, "potato": {"growth_time": 4, "value": 80, "seed_cost": 15, "emoji": "🥔"} } def plant_crop(self, player_data, crop_type): seed_name = f"{crop_type}_seeds" if player_data["inventory"].get(seed_name, 0) > 0: player_data["inventory"][seed_name] -= 1 plant_time = time.time() if crop_type not in player_data["crops"]: player_data["crops"][crop_type] = [] player_data["crops"][crop_type].append(plant_time) player_data["score"] += 5 return True return False def harvest_crop(self, player_data, crop_type): if crop_type in player_data["crops"] and player_data["crops"][crop_type]: current_time = time.time() growth_time = self.crops[crop_type]["growth_time"] # Check for harvestable crops harvestable = [plant_time for plant_time in player_data["crops"][crop_type] if current_time - plant_time >= growth_time] if harvestable: # Remove harvested crop player_data["crops"][crop_type].remove(harvestable[0]) # Add coins player_data["coins"] += self.crops[crop_type]["value"] # Add score player_data["score"] += 20 return True return False def buy_seeds(self, player_data, crop_type): seed_name = f"{crop_type}_seeds" seed_cost = self.crops[crop_type]["seed_cost"] if player_data["coins"] >= seed_cost: player_data["coins"] -= seed_cost player_data["inventory"][seed_name] = player_data["inventory"].get(seed_name, 0) + 1 return True return False def main(): st.title("🌾 Multiplayer Farming Simulator") # Load game data game_data = load_game_data() player_name = st.session_state.player_name # Initialize player if needed if player_name not in game_data: game_data[player_name] = initialize_player(player_name) # Create game instance game = FarmGame() # Sidebar with player information and scores st.sidebar.title("👨‍🌾 Players") st.sidebar.write(f"Your name: {player_name}") # Display all players' scores scores_df = pd.DataFrame([ {"Player": name, "Score": data["score"], "Coins": data["coins"]} for name, data in game_data.items() ]).sort_values("Score", ascending=False) st.sidebar.dataframe(scores_df) # Main game area col1, col2 = st.columns(2) with col1: st.subheader("🌱 Plant Crops") for crop_type in game.crops: if st.button(f"Plant {crop_type} {game.crops[crop_type]['emoji']}"): if game.plant_crop(game_data[player_name], crop_type): st.success(f"Planted {crop_type}!") else: st.error("Not enough seeds!") with col2: st.subheader("🏪 Buy Seeds") for crop_type in game.crops: seed_cost = game.crops[crop_type]["seed_cost"] if st.button(f"Buy {crop_type} seeds (${seed_cost})"): if game.buy_seeds(game_data[player_name], crop_type): st.success(f"Bought {crop_type} seeds!") else: st.error("Not enough coins!") # Display current crops st.subheader("🌾 Your Farm") col3, col4 = st.columns(2) with col3: st.write("Growing Crops:") current_time = time.time() for crop_type, plant_times in game_data[player_name]["crops"].items(): for plant_time in plant_times: # Convert progress to 0-1 range instead of 0-100 growth_progress = min(1.0, (current_time - plant_time) / game.crops[crop_type]["growth_time"]) st.progress(growth_progress) # Display percentage for user (0-100) progress_percent = growth_progress * 100 st.write(f"{game.crops[crop_type]['emoji']} {crop_type}: {progress_percent:.1f}% grown") with col4: st.write("Harvest Ready Crops:") for crop_type in game.crops: if st.button(f"Harvest {crop_type} {game.crops[crop_type]['emoji']}"): if game.harvest_crop(game_data[player_name], crop_type): st.success(f"Harvested {crop_type}!") else: st.error("No crops ready to harvest!") # Display inventory st.subheader("📦 Inventory") inventory_df = pd.DataFrame([ {"Item": item, "Quantity": quantity} for item, quantity in game_data[player_name]["inventory"].items() ]) st.dataframe(inventory_df) # Save game data save_game_data(game_data) # Add to history history = load_history() history.append({ "timestamp": datetime.now().isoformat(), "player": player_name, "score": game_data[player_name]["score"], "coins": game_data[player_name]["coins"] }) save_history(history) # Auto-refresh time.sleep(1) st.rerun() if __name__ == "__main__": main()