awacke1 commited on
Commit
039e681
Β·
verified Β·
1 Parent(s): 68b3e73

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +199 -0
app.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import random
3
+ import json
4
+ import time
5
+ import os
6
+ from datetime import datetime
7
+ import pandas as pd
8
+
9
+ # File to store game history
10
+ HISTORY_FILE = "farming_game_history.json"
11
+ PLAYER_FILE = "player_data.json"
12
+
13
+ # Initialize session state
14
+ if 'player_name' not in st.session_state:
15
+ # Generate random farmer name
16
+ prefixes = ["Happy", "Busy", "Lucky", "Sunny", "Green", "Golden"]
17
+ nouns = ["Farmer", "Gardener", "Harvester", "Planter", "Grower"]
18
+ st.session_state.player_name = f"{random.choice(prefixes)}{random.choice(nouns)}{random.randint(100,999)}"
19
+
20
+ def load_game_data():
21
+ if os.path.exists(PLAYER_FILE):
22
+ with open(PLAYER_FILE, 'r') as f:
23
+ return json.load(f)
24
+ return {}
25
+
26
+ def save_game_data(data):
27
+ with open(PLAYER_FILE, 'w') as f:
28
+ json.dump(data, f)
29
+
30
+ def load_history():
31
+ if os.path.exists(HISTORY_FILE):
32
+ with open(HISTORY_FILE, 'r') as f:
33
+ return json.load(f)
34
+ return []
35
+
36
+ def save_history(history):
37
+ with open(HISTORY_FILE, 'w') as f:
38
+ json.dump(history, f)
39
+
40
+ def initialize_player(player_name):
41
+ return {
42
+ "name": player_name,
43
+ "coins": 1000,
44
+ "crops": {},
45
+ "inventory": {
46
+ "wheat_seeds": 5,
47
+ "corn_seeds": 5,
48
+ "potato_seeds": 5
49
+ },
50
+ "score": 0,
51
+ "last_action": time.time()
52
+ }
53
+
54
+ class FarmGame:
55
+ def __init__(self):
56
+ self.crops = {
57
+ "wheat": {"growth_time": 5, "value": 100, "seed_cost": 20, "emoji": "🌾"},
58
+ "corn": {"growth_time": 7, "value": 150, "seed_cost": 30, "emoji": "🌽"},
59
+ "potato": {"growth_time": 4, "value": 80, "seed_cost": 15, "emoji": "πŸ₯”"}
60
+ }
61
+
62
+ def plant_crop(self, player_data, crop_type):
63
+ seed_name = f"{crop_type}_seeds"
64
+ if player_data["inventory"].get(seed_name, 0) > 0:
65
+ player_data["inventory"][seed_name] -= 1
66
+ plant_time = time.time()
67
+ if crop_type not in player_data["crops"]:
68
+ player_data["crops"][crop_type] = []
69
+ player_data["crops"][crop_type].append(plant_time)
70
+ player_data["score"] += 5
71
+ return True
72
+ return False
73
+
74
+ def harvest_crop(self, player_data, crop_type):
75
+ if crop_type in player_data["crops"] and player_data["crops"][crop_type]:
76
+ current_time = time.time()
77
+ growth_time = self.crops[crop_type]["growth_time"]
78
+
79
+ # Check for harvestable crops
80
+ harvestable = [plant_time for plant_time in player_data["crops"][crop_type]
81
+ if current_time - plant_time >= growth_time]
82
+
83
+ if harvestable:
84
+ # Remove harvested crop
85
+ player_data["crops"][crop_type].remove(harvestable[0])
86
+ # Add coins
87
+ player_data["coins"] += self.crops[crop_type]["value"]
88
+ # Add score
89
+ player_data["score"] += 20
90
+ return True
91
+ return False
92
+
93
+ def buy_seeds(self, player_data, crop_type):
94
+ seed_name = f"{crop_type}_seeds"
95
+ seed_cost = self.crops[crop_type]["seed_cost"]
96
+
97
+ if player_data["coins"] >= seed_cost:
98
+ player_data["coins"] -= seed_cost
99
+ player_data["inventory"][seed_name] = player_data["inventory"].get(seed_name, 0) + 1
100
+ return True
101
+ return False
102
+
103
+ def main():
104
+ st.title("🌾 Multiplayer Farming Simulator")
105
+
106
+ # Load game data
107
+ game_data = load_game_data()
108
+ player_name = st.session_state.player_name
109
+
110
+ # Initialize player if needed
111
+ if player_name not in game_data:
112
+ game_data[player_name] = initialize_player(player_name)
113
+
114
+ # Create game instance
115
+ game = FarmGame()
116
+
117
+ # Sidebar with player information and scores
118
+ st.sidebar.title("πŸ‘¨β€πŸŒΎ Players")
119
+ st.sidebar.write(f"Your name: {player_name}")
120
+
121
+ # Display all players' scores
122
+ scores_df = pd.DataFrame([
123
+ {"Player": name, "Score": data["score"], "Coins": data["coins"]}
124
+ for name, data in game_data.items()
125
+ ]).sort_values("Score", ascending=False)
126
+
127
+ st.sidebar.dataframe(scores_df)
128
+
129
+ # Main game area
130
+ col1, col2 = st.columns(2)
131
+
132
+ with col1:
133
+ st.subheader("🌱 Plant Crops")
134
+ for crop_type in game.crops:
135
+ if st.button(f"Plant {crop_type} {game.crops[crop_type]['emoji']}"):
136
+ if game.plant_crop(game_data[player_name], crop_type):
137
+ st.success(f"Planted {crop_type}!")
138
+ else:
139
+ st.error("Not enough seeds!")
140
+
141
+ with col2:
142
+ st.subheader("πŸͺ Buy Seeds")
143
+ for crop_type in game.crops:
144
+ seed_cost = game.crops[crop_type]["seed_cost"]
145
+ if st.button(f"Buy {crop_type} seeds (${seed_cost})"):
146
+ if game.buy_seeds(game_data[player_name], crop_type):
147
+ st.success(f"Bought {crop_type} seeds!")
148
+ else:
149
+ st.error("Not enough coins!")
150
+
151
+ # Display current crops
152
+ st.subheader("🌾 Your Farm")
153
+ col3, col4 = st.columns(2)
154
+
155
+ with col3:
156
+ st.write("Growing Crops:")
157
+ current_time = time.time()
158
+ for crop_type, plant_times in game_data[player_name]["crops"].items():
159
+ for plant_time in plant_times:
160
+ growth_progress = min(100, ((current_time - plant_time) / game.crops[crop_type]["growth_time"]) * 100)
161
+ st.progress(growth_progress)
162
+ st.write(f"{game.crops[crop_type]['emoji']} {crop_type}: {growth_progress:.1f}% grown")
163
+
164
+ with col4:
165
+ st.write("Harvest Ready Crops:")
166
+ for crop_type in game.crops:
167
+ if st.button(f"Harvest {crop_type} {game.crops[crop_type]['emoji']}"):
168
+ if game.harvest_crop(game_data[player_name], crop_type):
169
+ st.success(f"Harvested {crop_type}!")
170
+ else:
171
+ st.error("No crops ready to harvest!")
172
+
173
+ # Display inventory
174
+ st.subheader("πŸ“¦ Inventory")
175
+ inventory_df = pd.DataFrame([
176
+ {"Item": item, "Quantity": quantity}
177
+ for item, quantity in game_data[player_name]["inventory"].items()
178
+ ])
179
+ st.dataframe(inventory_df)
180
+
181
+ # Save game data
182
+ save_game_data(game_data)
183
+
184
+ # Add to history
185
+ history = load_history()
186
+ history.append({
187
+ "timestamp": datetime.now().isoformat(),
188
+ "player": player_name,
189
+ "score": game_data[player_name]["score"],
190
+ "coins": game_data[player_name]["coins"]
191
+ })
192
+ save_history(history)
193
+
194
+ # Auto-refresh
195
+ time.sleep(1)
196
+ st.experimental_rerun()
197
+
198
+ if __name__ == "__main__":
199
+ main()