Of course! Here is a complete, playable text-based farming simulator game written in Python.
This game includes the following features:
A farm with multiple plots.
Different types of crops with unique growth times and prices.
A day/night cycle (advancing time).
A shop to buy seeds and sell harvested crops.
An inventory system for your seeds and produce.
A persistent game state (money, inventory, and field status).
I've added extensive comments to the code so you can understand how each part works.
How to Play
Save the code below as a Python file (e.g., farm_sim.py).
Run it from your terminal: python farm_sim.py
Follow the on-screen prompts. The goal is to make money by planting, growing, and selling crops.
The Code
python
import time
import os
import random
# --- Game Configuration ---
# A dictionary defining the properties of each crop
# 'seed_price': Cost to buy one seed.
# 'sell_price': Price for one harvested crop.
# 'growth_time': How many days it takes to grow.
# 'icon': A character to represent the crop on the farm display.
CROPS = {
"wheat": {"seed_price": 5, "sell_price": 10, "growth_time": 3, "icon": "🌾"},
"corn": {"seed_price": 10, "sell_price": 25, "growth_time": 5, "icon": "🌽"},
"potato": {"seed_price": 7, "sell_price": 15, "growth_time": 4, "icon": "🥔"},
"carrot": {"seed_price": 8, "sell_price": 20, "growth_time": 4, "icon": "🥕"},
"tomato": {"seed_price": 12, "sell_price": 30, "growth_time": 6, "icon": "🍅"},
"strawberry": {"seed_price": 20, "sell_price": 50, "growth_time": 7, "icon": "🍓"},
}
INITIAL_MONEY = 100
INITIAL_SEEDS = {"wheat": 5, "corn": 2}
FARM_SIZE = 6
# --- Helper Functions ---
def clear_screen():
"""Clears the terminal screen."""
os.system('cls' if os.name == 'nt' else 'clear')
def print_slow(text, delay=0.03):
"""Prints text with a typewriter effect."""
for char in text:
print(char, end='', flush=True)
time.sleep(delay)
print()
# --- Core Game Classes ---
class Plot:
"""Represents a single plot of land on the farm."""
def __init__(self):
self.crop = None
self.growth_stage = 0
def is_empty(self):
"""Check if the plot is empty."""
return self.crop is None
def plant(self, crop_name):
"""Plant a seed in the plot."""
self.crop = crop_name
self.growth_stage = 0
def grow(self):
"""Advance the growth of the crop by one day."""
if not self.is_empty():
self.growth_stage += 1
def is_ready_for_harvest(self):
"""Check if the crop is fully grown."""
if self.is_empty():
return False
return self.growth_stage >= CROPS[self.crop]['growth_time']
def harvest(self):
"""Harvest the crop, returning its name and resetting the plot."""
if self.is_ready_for_harvest():
crop_name = self.crop
self.crop = None
self.growth_stage = 0
return crop_name
return None
def get_display(self):
"""Get the string representation for the plot's current state."""
if self.is_empty():
return "[ --- ]"
elif self.is_ready_for_harvest():
icon = CROPS[self.crop]['icon']
return f"[{icon}READY{icon}]"
else:
icon = CROPS[self.crop]['icon']
growth_time = CROPS[self.crop]['growth_time']
return f"[{icon}({self.growth_stage}/{growth_time}){icon}]"
class Game:
"""The main class that orchestrates the entire game."""
def __init__(self):
self.money = INITIAL_MONEY
self.day = 1
self.plots = [Plot() for _ in range(FARM_SIZE)]
self.inventory = {
"seeds": INITIAL_SEEDS.copy(),
"harvested": {}
}
def display_status(self):
"""Displays the main game screen with farm status and player info."""
clear_screen()
print("="*40)
print(f"☀️ Day: {self.day} | 💰 Money: ${self.money}")
print("="*40)
print("\n🌱 Your Farm 🌱")
# Display plots in a grid-like fashion
for i in range(0, len(self.plots), 3):
# Plot numbers
plot_numbers = " ".join([f" Plot {j+1:<3}" for j in range(i, min(i+3, len(self.plots)))])
print(plot_numbers)
# Plot status
plot_displays = " ".join([self.plots[j].get_display() for j in range(i, min(i+3, len(self.plots)))])
print(plot_displays)
print() # Spacer
print("\n🎒 Inventory:")
print(" Seeds:")
if not self.inventory["seeds"]:
print(" - None")
else:
for seed, count in self.inventory["seeds"].items():
print(f" - {seed.capitalize()}: {count}")
print(" Harvested Crops:")
if not self.inventory["harvested"]:
print(" - None")
else:
for crop, count in self.inventory["harvested"].items():
print(f" - {crop.capitalize()}: {count}")
print("\n" + "="*40)
def main_menu(self):
"""Displays the main menu and handles user choices."""
print("\nWhat would you like to do?")
print("1. Plant a crop")
print("2. Harvest a crop")
print("3. Visit the Shop")
print("4. Go to the next day")
print("5. Quit Game")
choice = input("Enter your choice (1-5): ")
return choice
def plant_crop(self):
"""Handles the logic for planting a crop."""
self.display_status()
print("\n--- Plant a Crop ---")
# Check if player has any seeds
if not self.inventory["seeds"]:
print_slow("You don't have any seeds to plant! Visit the shop to buy some.")
time.sleep(2)
return
# Get plot choice
try:
plot_choice = int(input(f"Which plot do you want to plant in (1-{FARM_SIZE})? ")) - 1
if not 0 <= plot_choice < FARM_SIZE:
raise ValueError
except ValueError:
print_slow("Invalid plot number.")
time.sleep(1.5)
return
if not self.plots[plot_choice].is_empty():
print_slow("This plot is not empty.")
time.sleep(1.5)
return
# Get seed choice
print("Which seed would you like to plant?")
available_seeds = list(self.inventory["seeds"].keys())
for i, seed in enumerate(available_seeds):
print(f"{i+1}. {seed.capitalize()}")
try:
seed_choice_idx = int(input("Enter your choice: ")) - 1
if not 0 <= seed_choice_idx < len(available_seeds):
raise ValueError
seed_to_plant = available_seeds[seed_choice_idx]
except (ValueError, IndexError):
print_slow("Invalid seed choice.")
time.sleep(1.5)
return
# Plant the crop
self.plots[plot_choice].plant(seed_to_plant)
self.inventory["seeds"][seed_to_plant] -= 1
if self.inventory["seeds"][seed_to_plant] == 0:
del self.inventory["seeds"][seed_to_plant]
print_slow(f"You have planted {seed_to_plant} in plot {plot_choice + 1}.")
time.sleep(2)
def harvest_crop(self):
"""Handles the logic for harvesting a crop."""
self.display_status()
print("\n--- Harvest a Crop ---")
try:
plot_choice = int(input(f"Which plot do you want to harvest (1-{FARM_SIZE})? ")) - 1
if not 0 <= plot_choice < FARM_SIZE:
raise ValueError
except ValueError:
print_slow("Invalid plot number.")
time.sleep(1.5)
return
if self.plots[plot_choice].is_empty():
print_slow("This plot is empty. Nothing to harvest.")
time.sleep(1.5)
return
if not self.plots[plot_choice].is_ready_for_harvest():
print_slow("This crop is not ready for harvest yet.")
time.sleep(1.5)
return
harvested_crop = self.plots[plot_choice].harvest()
if harvested_crop:
# Add to harvested inventory
self.inventory["harvested"][harvested_crop] = self.inventory["harvested"].get(harvested_crop, 0) + 1
print_slow(f"You harvested a {harvested_crop.capitalize()} from plot {plot_choice + 1}!")
time.sleep(2)
def visit_shop(self):
"""Handles the shop logic for buying and selling."""
while True:
self.display_status()
print("\n--- Welcome to the General Store! ---")
print("1. Buy Seeds")
print("2. Sell Harvested Crops")
print("3. Leave Shop")
choice = input("What would you like to do? ")
if choice == '1': # Buy Seeds
print("\n--- Seeds for Sale ---")
for crop, details in CROPS.items():
print(f"- {crop.capitalize()}: ${details['seed_price']}")
try:
crop_to_buy = input("What would you like to buy? (or 'back') ").lower()
if crop_to_buy == 'back':
continue
if crop_to_buy not in CROPS:
print_slow("Sorry, we don't sell that seed.")
time.sleep(1.5)
continue
amount = int(input(f"How many {crop_to_buy} seeds? "))
if amount <= 0:
raise ValueError
cost = CROPS[crop_to_buy]["seed_price"] * amount
if self.money >= cost:
self.money -= cost
self.inventory["seeds"][crop_to_buy] = self.inventory["seeds"].get(crop_to_buy, 0) + amount
print_slow(f"You bought {amount} {crop_to_buy} seed(s) for ${cost}.")
else:
print_slow("You don't have enough money.")
time.sleep(2)
except ValueError:
print_slow("Invalid input.")
time.sleep(1.5)
elif choice == '2': # Sell Crops
if not self.inventory["harvested"]:
print_slow("You have no harvested crops to sell.")
time.sleep(2)
continue
print("\n--- Sell Your Crops ---")
for crop, count in self.inventory["harvested"].items():
sell_price = CROPS[crop]['sell_price']
print(f"- {crop.capitalize()}: {count} available (sells for ${sell_price} each)")
try:
crop_to_sell = input("What would you like to sell? (or 'back') ").lower()
if crop_to_sell == 'back':
continue
if crop_to_sell not in self.inventory["harvested"]:
print_slow("You don't have any of that crop.")
time.sleep(1.5)
continue
amount = int(input(f"How many {crop_to_sell} to sell? "))
if amount <= 0 or amount > self.inventory["harvested"][crop_to_sell]:
print_slow("Invalid amount.")
time.sleep(1.5)
continue
earnings = CROPS[crop_to_sell]["sell_price"] * amount
self.money += earnings
self.inventory["harvested"][crop_to_sell] -= amount
if self.inventory["harvested"][crop_to_sell] == 0:
del self.inventory["harvested"][crop_to_sell]
print_slow(f"You sold {amount} {crop_to_sell}(s) for ${earnings}!")
time.sleep(2)
except ValueError:
print_slow("Invalid input.")
time.sleep(1.5)
elif choice == '3':
print_slow("Thanks for visiting!")
time.sleep(1)
break
else:
print_slow("Invalid choice, please try again.")
time.sleep(1)
def next_day(self):
"""Advances the game to the next day, growing all crops."""
print_slow("The sun sets on another day...", 0.05)
time.sleep(1)
self.day += 1
for plot in self.plots:
plot.grow()
# Random event chance
if random.random() < 0.15: # 15% chance of a random event
self.random_event()
else:
print_slow("A new day dawns!", 0.05)
time.sleep(1)
def random_event(self):
"""Triggers a random event for the new day."""
events = ["rain", "pest", "bonus"]
event = random.choice(events)
if event == "rain":
print_slow("🌧️ Overnight rain has accelerated your crops' growth!", 0.05)
for plot in self.plots:
plot.grow() # Extra growth
elif event == "pest":
non_empty_plots = [p for p in self.plots if not p.is_empty()]
if non_empty_plots:
plot_affected = random.choice(non_empty_plots)
plot_affected.growth_stage = max(0, plot_affected.growth_stage - 1)
print_slow(f"🐛 Oh no! Pests have attacked your {plot_affected.crop}, setting its growth back a day.", 0.05)
elif event == "bonus":
bonus_money = random.randint(10, 50)
self.money += bonus_money
print_slow(f"🎉 You found a lost wallet on your farm containing ${bonus_money}!", 0.05)
time.sleep(3)
def run(self):
"""The main game loop."""
clear_screen()
print_slow("="*40)
print_slow(" Welcome to Python Farming Simulator! ", 0.05)
print_slow("="*40)
print_slow("\nYour goal is to manage your farm and make money.", 0.05)
print_slow("Buy seeds, plant them, watch them grow, and sell the harvest.", 0.05)
time.sleep(3)
while True:
self.display_status()
choice = self.main_menu()
if choice == '1':
self.plant_crop()
elif choice == '2':
self.harvest_crop()
elif choice == '3':
self.visit_shop()
elif choice == '4':
self.next_day()
elif choice == '5':
print_slow("Thanks for playing! Come back to the farm soon!", 0.05)
break
else:
print_slow("Invalid choice. Please enter a number from 1 to 5.", 0.03)
time.sleep(2)
# --- Start the Game ---
if __name__ == "__main__":
game = Game()
game.run()