import React, { useEffect, useState } from "https://esm.sh/react";
import { createRoot } from "https://esm.sh/react-dom/client";
const EMOTIONS = {
happy: "π",
sad: "π’",
angry: "π ",
hungry: "π½οΈ",
sleepy: "π΄",
};
const FOODS = ["π", "π", "π₯", "π", "π£"];
function App() {
const [pet, setPet] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchPet();
}, []);
const fetchPet = async () => {
const response = await fetch("/pet");
const data = await response.json();
setPet(data);
setLoading(false);
};
const interact = async (action) => {
const response = await fetch("/interact", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action }),
});
const data = await response.json();
setPet(data);
};
if (loading) return <div>Loading your pet...</div>;
if (!pet) return <div>Error loading pet</div>;
return (
<div className="container">
<h1>Virtual Pet Simulator</h1>
<div className="pet-container">
<div className="pet">
{pet.species === "cat" ? "π±" : "πΆ"}
{EMOTIONS[pet.emotion]}
</div>
<div>Name: {pet.name}</div>
<div>Health: {pet.health}</div>
<div>Happiness: {pet.happiness}</div>
<div>Last fed: {new Date(pet.lastFed).toLocaleString()}</div>
</div>
<div className="actions">
<button onClick={() => interact("pet")}>Pet</button>
<button onClick={() => interact("play")}>Play</button>
<button onClick={() => interact("sleep")}>Sleep</button>
<div className="food-options">
{FOODS.map((food, index) => (
<button key={index} onClick={() => interact(`feed_${index}`)}>
Feed {food}
</button>
))}
</div>
</div>
<a href={import.meta.url.replace("esm.town", "val.town")} target="_blank" rel="noopener noreferrer">
View Source
</a>
</div>
);
}
function client() {
createRoot(document.getElementById("root")).render(<App />);
}
if (typeof document !== "undefined") {
client();
}
async function server(request: Request): Promise<Response> {
const { sqlite } = await import("https://esm.town/v/stevekrouse/sqlite");
const SCHEMA_VERSION = 1;
const KEY = new URL(import.meta.url).pathname.split("/").at(-1);
await sqlite.execute(`
CREATE TABLE IF NOT EXISTS ${KEY}_pets_${SCHEMA_VERSION} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
species TEXT NOT NULL,
health INTEGER NOT NULL,
happiness INTEGER NOT NULL,
emotion TEXT NOT NULL,
lastFed DATETIME NOT NULL