Spaces:
Sleeping
Sleeping
File size: 6,903 Bytes
039e681 0c5342d 039e681 0c5342d 039e681 5a67dc5 039e681 |
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 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
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() |