circuit-clicker
Version:
a simple clicker game.
117 lines (116 loc) • 3.86 kB
JavaScript
import { cursors, Game, upgrades } from "./index.js";
import readline from "readline";
import chalk from "chalk";
import fs from "fs";
import path from "path";
const SAVE_FILE = path.resolve(process.cwd(), "game_save.json");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let screen = "";
let upgrading = false;
function saveGame(game) {
try {
fs.writeFileSync(SAVE_FILE, game.toString(), "utf-8");
}
catch (err) {
console.error("Failed to save game:", err);
}
}
function loadGame() {
try {
if (fs.existsSync(SAVE_FILE)) {
const data = fs.readFileSync(SAVE_FILE, "utf-8");
return Game.fromString(data);
}
}
catch (err) {
console.error("Failed to load save file:", err);
}
return new Game();
}
const game = loadGame();
function render() {
console.clear();
console.log(chalk.hex("#ffcc00")(`${game.getScore()} score!`));
console.log(chalk.hex("#ffcc000")(screen));
console.log(chalk.hex("#ccff00")("What do you want to do? (click, upgrade, home, exit): "));
rl.prompt(true);
}
function tick() {
game.tick();
saveGame(game);
render();
}
setInterval(tick, 1000);
function requestInput() {
return new Promise((resolve) => {
rl.question("", (str) => {
const cmd = str.trim().toLowerCase();
if (upgrading) {
const choice = parseInt(str);
if (!isNaN(choice)) {
if (choice >= 0 && choice < upgrades.length) {
if (game.upgrade(upgrades[choice])) {
saveGame(game);
}
screen = "";
upgrading = false;
render();
resolve();
return;
}
else if (choice >= upgrades.length &&
choice < upgrades.length + cursors.length) {
const cursorIndex = choice - upgrades.length;
if (game.cursor(cursors[cursorIndex])) {
saveGame(game);
}
screen = "";
upgrading = false;
render();
resolve();
return;
}
}
screen = "Invalid selection, please enter a valid number.";
render();
resolve();
return;
}
switch (cmd) {
case "click":
game.click();
saveGame(game);
break;
case "upgrade":
screen = `Upgrades (To buy enter the number on the left of the upgrade):
${upgrades
.map((u, i) => `${i}. ${u.getName()}, Price: ${u.getPrice()}, CPS: ${u.getCPS()}`)
.join("\n")}
${cursors
.map((u, i) => `${i + upgrades.length}. ${u.getName()}, Price: ${u.getPrice()}, Clickpower: ${u.getClickpower()}`)
.join("\n")}`;
upgrading = true;
break;
case "home":
console.log("Returning home...");
upgrading = false;
screen = "";
break;
case "exit":
console.log("Goodbye!");
rl.close();
process.exit(0);
default:
console.log("Unknown command");
}
render();
resolve();
});
}).then(requestInput);
}
render();
requestInput();