Skip to content

Instantly share code, notes, and snippets.

@luizbills
Last active July 12, 2024 01:47
Show Gist options
  • Save luizbills/4b689e9a0966491ca0a2a22f80ca20cd to your computer and use it in GitHub Desktop.
Save luizbills/4b689e9a0966491ca0a2a22f80ca20cd to your computer and use it in GitHub Desktop.
Simple text dungeon crawl made in JavaScript
/**
* Simple Dungeon Crawl Text Adventure Game
*
* @author Luiz Bills <luizbills@pm.me>
* @license MIT
*/
// Game constants
const GOBLIN_HEALTH = 5;
const GOBLIN_ATTACK = 1;
const PLAYER_HEALTH = 20;
const PLAYER_ATTACK_MIN = 1;
const PLAYER_ATTACK_MAX = 6;
// Function to generate random numbers
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Function to roll six-sided dice
function d6(times = 1) {
let total = 0;
while (times-- > 0) {
total += getRandomInt(1, 6);
}
return total;
}
// Goblin class
class Goblin {
constructor() {
this.health = GOBLIN_HEALTH;
}
attack(player) {
player.health -= GOBLIN_ATTACK;
}
}
// Player class
class Player {
constructor() {
this.health = PLAYER_HEALTH;
this.potions = 0;
}
attack(enemy, damage) {
enemy.health -= damage;
}
usePotion() {
this.health = Math.min(PLAYER_HEALTH, this.health + 10);
this.potions--;
}
isAlive() {
return this.health > 0;
}
}
// Function to populate a room with 1-3 enemies
function createRoom() {
const numEnemies = getRandomInt(1, 3);
return Array.from({ length: numEnemies }, () => new Goblin());
}
// Game logic handler
function playGame() {
const numRooms = d6(2) + 3;
const player = new Player();
let currentRoom = 0;
let goblins = [];
let gameFinished = false;
// UI Elements
const roomInfoElement = document.getElementById("room-info");
const playerStatusElement = document.getElementById("player-status");
const gameLogElement = document.getElementById("game-log");
const attackButton = document.getElementById("attack-btn");
const potionButton = document.getElementById("potion-btn");
// Function to update the game UI
function updateGameUI() {
const diff = numRooms - currentRoom;
roomInfoElement.textContent = `You are in room ${currentRoom} (${
diff > 0 ? "there are " + diff + " rooms left" : "this is the last room"
}).`;
playerStatusElement.textContent = `You have ${player.health} health points and ${player.potions} potions.`;
}
// Function to log a message in the game log
function logMessage(message) {
const messageElement = document.createElement("p");
messageElement.textContent = message;
gameLogElement.appendChild(messageElement);
window.scrollTo(0, document.body.scrollHeight);
}
// Function to handle the player's action
function handlePlayerAction(action) {
if (gameFinished) return;
if (!player.isAlive()) return;
if (action === "attack") {
const damage = getRandomInt(PLAYER_ATTACK_MIN, PLAYER_ATTACK_MAX);
player.attack(goblins[0], damage);
logMessage(`You attacked a goblin and dealt ${damage} damage.`);
if (goblins[0].health <= 0) {
logMessage("You defeated a goblin!");
goblins.shift();
if (d6() === 1) {
logMessage("The goblin dropped a potion!");
player.potions++;
}
}
enemiesTurn();
} else if (action === "potion") {
if (player.potions > 0) {
player.usePotion();
logMessage("You used a potion and recovered 10 health points.");
enemiesTurn();
} else {
logMessage("You don't have any potions.");
}
}
updateGameUI();
if (player.health <= 0) {
logMessage("You have been defeated!");
return;
}
}
function enemiesTurn() {
if (goblins.length > 0) {
// logMessage(`There are still ${goblins.length} goblins in this room.`)
for (const goblin of goblins) {
goblin.attack(player);
logMessage(`A goblin attacked you and dealt ${GOBLIN_ATTACK} damage.`);
}
} else {
logMessage("You have defeated all the goblins in this room");
startNewRoom();
}
}
// Function to start a new room
function startNewRoom() {
currentRoom++;
if (currentRoom <= numRooms) {
goblins = createRoom();
logMessage(`--- Room #${currentRoom} ---`);
logMessage(`You entered a room with ${goblins.length} goblins.`);
updateGameUI();
} else {
logMessage("Congratulations! You have completed the dungeon.");
gameFinished = true;
}
}
// Add event listeners to the buttons
attackButton.addEventListener("click", () => handlePlayerAction("attack"));
potionButton.addEventListener("click", () => handlePlayerAction("potion"));
// Start the game
logMessage("You begin to explore the dungeon...");
startNewRoom();
}
// Start the game
playGame();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Text Dungeon Crawl</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="game-container">
<h1 id="game-title">Text Dungeon Crawl</h1>
<div id="game-log"></div>
<hr/>
<p id="room-info"></p>
<p id="player-status"></p>
<div id="action-buttons">
<button id="attack-btn">Attack</button>
<button id="potion-btn">Drink Potion</button>
</div>
</div>
<script src="game.js"></script>
</body>
</html>
The MIT License (MIT)
Copyright © 2024 Luiz Bills
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
html {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans,
Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
font-size: 18px;
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
padding: 1rem;
background: #222;
color: #ddd;
}
body * {
font-family: inherit;
}
button {
appearance: none;
background: transparent;
color: #ddd;
border: 1px solid currentcolor;
padding: 0.75em 1em;
font-size: 0.9em;
border-radius: 0.25em;
}
@keyframes fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
#game-title {
margin-top: 0;
font-size: 2em;
}
#game-log p,
button {
animation-name: fade-in;
animation-iteration-count: 1;
animation-duration: 800ms;
}
#game-container {
max-width: 32rem;
margin: auto;
}
#room-info,
#player-status {
font-style: italic;
}
@luizbills
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment