Compare commits

...

9 Commits

Author SHA1 Message Date
Valithor Obsidion
c06a9bbed6 Update routing and error handlers 2025-08-15 09:34:27 -04:00
Valithor Obsidion
c615a978e4 Update path to database 2025-08-15 03:03:16 -04:00
Valithor Obsidion
51a65506c1 Throw extension if required ext is missing 2025-08-15 02:50:16 -04:00
Valithor Obsidion
bcb9139995 Update routers 2025-08-15 02:43:24 -04:00
Valithor Obsidion
6028f50cd1 Update return types 2025-08-14 17:08:36 -04:00
Valithor Obsidion
f0fc0f257b Update return types 2025-08-14 16:53:51 -04:00
Valithor Obsidion
d40b826dfa Fix imports, throw exceptions 2025-08-14 16:49:20 -04:00
Valithor Obsidion
4d5c345528 functions.php 2025-08-14 15:47:25 -04:00
Valithor Obsidion
feba005335 Creates classes, updates folders and scope 2025-08-14 13:55:37 -04:00
63 changed files with 5801 additions and 4754 deletions

36
.gitignore vendored
View File

@ -1,5 +1,37 @@
# general
.env
.DS_Store
test*.php
.idea
.phplint-cache
dump.html
.vscode
# dragon-knight
.installed
logs
database.db
database.db-*
.env
logs
# phive
/tools
.phive
# composer
/vendor
composer.lock
# docs
/build
.phpdoc
# php-cs-fixer
.php_cs.cache
.php_cs
.php-cs-fixer.php
.php-cs-fixer.cache
# phpunit
phpunit.log
/.phpunit*
/coverage

102
.php-cs-fixer.dist.php Normal file
View File

@ -0,0 +1,102 @@
<?php
$header = <<<'EOF'
This file is a part of the Dragon-Knight project.
Copyright (c) 2024-present Sharkk
This file is subject to the MIT license that is bundled
with this source code in the LICENSE.md file.
EOF;
$fixers = [
'blank_line_after_namespace',
'braces',
'class_definition',
'elseif',
'encoding',
'full_opening_tag',
'function_declaration',
'lowercase_keywords',
'method_argument_space',
'no_closing_tag',
'no_spaces_after_function_name',
'no_spaces_inside_parenthesis',
'no_trailing_whitespace',
'no_trailing_whitespace_in_comment',
'single_blank_line_at_eof',
'single_class_element_per_statement',
'single_import_per_statement',
'single_line_after_imports',
'switch_case_semicolon_to_colon',
'switch_case_space',
'visibility_required',
'blank_line_after_opening_tag',
'no_multiline_whitespace_around_double_arrow',
'no_empty_statement',
'include',
'no_trailing_comma_in_list_call',
'not_operator_with_successor_space',
'no_leading_namespace_whitespace',
'no_blank_lines_after_class_opening',
'no_blank_lines_after_phpdoc',
'object_operator_without_whitespace',
'binary_operator_spaces',
'phpdoc_indent',
'general_phpdoc_tag_rename',
'phpdoc_inline_tag_normalizer',
'phpdoc_tag_type',
'phpdoc_no_access',
'phpdoc_no_package',
'phpdoc_scalar',
'phpdoc_summary',
'phpdoc_trim',
'phpdoc_var_without_name',
'no_leading_import_slash',
'no_trailing_comma_in_singleline_array',
'single_blank_line_before_namespace',
'single_quote',
'no_singleline_whitespace_before_semicolons',
'cast_spaces',
'standardize_not_equals',
'ternary_operator_spaces',
'trim_array_spaces',
'unary_operator_spaces',
'no_unused_imports',
'no_useless_else',
'no_useless_return',
'phpdoc_no_empty_return',
'no_extra_blank_lines',
'multiline_whitespace_before_semicolons',
];
$rules = [
'concat_space' => ['spacing' => 'none'],
'phpdoc_no_alias_tag' => ['replacements' => ['type' => 'var']],
'array_syntax' => ['syntax' => 'short'],
'binary_operator_spaces' => ['align_double_arrow' => true, 'align_equals' => true],
'header_comment' => ['header' => $header],
'indentation_type' => true,
'phpdoc_align' => [
'align' => 'vertical',
'tags' => ['param', 'property', 'property-read', 'property-write', 'return', 'throws', 'type', 'var', 'method'],
],
'blank_line_before_statement' => ['statements' => ['return']],
'constant_case' => ['case' => 'lower'],
'echo_tag_syntax' => ['format' => 'long'],
'trailing_comma_in_multiline' => ['elements' => ['arrays']],
];
foreach ($fixers as $fix) {
$rules[$fix] = true;
}
$config = new PhpCsFixer\Config();
return $config
->setRules($rules)
->setFinder(
PhpCsFixer\Finder::create()
->exclude('examples')
->in(__DIR__)
);

36
composer.json Normal file
View File

@ -0,0 +1,36 @@
{
"name": "valgorithms/dragon-knight",
"description": "@todo",
"license": "MIT",
"authors": [
{
"name": "Valithor Obsidion",
"email": "valithor@discordphp.org"
}
],
"require": {
"php": "^8.3",
"team-reflex/discord-php": "^10.18.45"
},
"autoload": {
"files": [
"src/DragonKnight/functions.php",
"src/DragonKnight/DragonKnight.php"
],
"psr-4": {
"DragonKnight\\": "src/DragonKnight"
}
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^3",
"phpunit/phpunit": "^9.4.4",
"laravel/pint": "^1.21"
},
"scripts": {
"pint": ["./vendor/bin/pint --config ./pint.json ./src"],
"cs": ["./vendor/bin/php-cs-fixer fix"],
"cs-unsupported": ["./vendor/bin/php-cs-fixer fix --allow-unsupported-php-version yes"],
"unit": ["./vendor/bin/phpunit --testdox"],
"coverage": ["XDEBUG_MODE=coverage ./vendor/bin/phpunit --coverage-html coverage --testdox"]
}
}

27
phpdoc.dist.xml Normal file
View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8" ?>
<phpdocumentor
configVersion="3"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://www.phpdoc.org"
xsi:noNamespaceSchemaLocation="https://docs.phpdoc.org/latest/phpdoc.xsd"
>
<title>DiscordPHP Documentation</title>
<paths>
<output>build</output>
</paths>
<version number="latest">
<api>
<source dsn=".">
<path>src</path>
</source>
<output>reference</output>
</api>
<guide>
<source dsn=".">
<path>guide</path>
</source>
<output>guide</output>
</guide>
</version>
<setting name="guides.enabled" value="true"/>
</phpdocumentor>

6
pint.json Normal file
View File

@ -0,0 +1,6 @@
{
"preset": "psr12",
"rules": {
"declare_strict_types": true
}
}

View File

@ -1,8 +1,51 @@
<?php
// index.php :: Primary program script, evil alien overlord, you decide.
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
require_once '../src/bootstrap.php';
namespace DragonKnight;
use DragonKnight\Actions\Fight;
use DragonKnight\Actions\Forum;
use DragonKnight\Actions\Help;
use DragonKnight\Actions\Install;
use DragonKnight\Actions\Towns;
use DragonKnight\Actions\Users;
use DragonKnight\Actions\Admin;
ini_set('display_errors', 1);
error_reporting(E_ALL);
set_time_limit(0);
ignore_user_abort(true);
ini_set('max_execution_time', 0);
ini_set('memory_limit', '-1'); // Unlimited memory usage
if (! $autoloader = require file_exists(__DIR__.'/../vendor/autoload.php') ? __DIR__.'/../vendor/autoload.php' : __DIR__.'/../../autoload.php') {
throw new \Exception('Composer autoloader not found. Run `composer install` and try again.');
}
env_load(__DIR__.'/../.env');
// Check required extensions
$requiredExtensions = [
'sqlite3',
];
if ($missing = array_filter($requiredExtensions, fn($ext) => !extension_loaded($ext))) {
throw new \Exception(
'Required PHP extensions missing: ' . implode(', ', $missing) .
'. Please enable them in your PHP configuration.'
);
}
$uri = explode('/', trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/'));
// Do an early return with babblebox data if that's what's being requested
if ($uri[0] === 'babblebox' && (isset($uri[1]) && $uri[1] === 'messages')) {
@ -12,22 +55,23 @@ if ($uri[0] === 'babblebox' && (isset($uri[1]) && $uri[1] === 'messages')) {
$r = new Router;
$r->get('/', 'index');
$r->post('/move', 'Explore\move');
$r->get('/spell/:id', 'healspells');
$r->get('/character', 'show_character_info');
$r->get('/character/:id', 'show_character_info');
$r->get('/showmap', 'show_map');
$r->form('/babblebox', 'babblebox');
$r->get('/babblebox/messages', 'babblebox_messages');
$r->get(['/', '/index.php'], fn() => \DragonKnight\index());
$r->get('/register', fn() => \DragonKnight\Actions\Users::register());
$r->post('/move', fn() => \DragonKnight\Actions\Explore::move());
$r->get('/spell/:id', fn($id) => \DragonKnight\Actions\Heal::healspells($id));
$r->get('/character', fn() => \DragonKnight\show_character_info());
$r->get('/character/:id', fn($id) => \DragonKnight\show_character_info($id));
$r->get('/showmap', fn() => \DragonKnight\show_map());
$r->form('/babblebox', fn() => \DragonKnight\babblebox());
$r->get('/babblebox/messages', fn() => \DragonKnight\babblebox_messages());
Towns\register_routes($r);
Fights\register_routes($r);
Users\register_routes($r);
Help\register_routes($r);
Forum\register_routes($r);
Install\register_routes($r);
Admin\register_routes($r);
Admin::register_routes($r);
Fight::register_routes($r);
Forum::register_routes($r);
Help::register_routes($r);
Install::register_routes($r);
Towns::register_routes($r);
Users::register_routes($r);
/*
NINJA! 🥷
@ -39,97 +83,12 @@ $r->get('/ninja', function() {
// [code, handler, params, middleware]
$l = $r->lookup($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);
if (is_int($l)) exit("Error: $l");
if (is_int($l)) {
error_log($path = $_SERVER['REQUEST_METHOD'] . ' ' . $_SERVER['REQUEST_URI']);
exit("Error: $l at `$path`");
}
if (! isset($l['handler'])) {
error_log($path = $_SERVER['REQUEST_METHOD'] . ' ' . $_SERVER['REQUEST_URI']);
exit("Error: Missing handler: $path");
}
echo render_response($uri, $l['handler'](...$l['params'] ?? []));
exit;
/**
* Return a page for a couple generic actions.
*/
function index(): string
{
if (user()->currentaction === "In Town") {
$page = Towns\town();
} elseif (user()->currentaction === "Exploring") {
$page = Explore\explore();
} elseif (user()->currentaction === "Fighting") {
redirect('/fight');
}
return $page;
}
/**
* Show a character's info. Defaults to the currently logged in user.
*/
function show_character_info(int $id = 0): string
{
$user = $id !== 0 ? User::find($id) : user();
if ($user === false) exit('Failed to show info for user ID '.$id);
$level = db()->query("SELECT `{$user->charclass}_exp` FROM levels WHERE id=? LIMIT 1;", [$user->level + 1])->fetchArray(SQLITE3_ASSOC);
$spells = $user->spells();
$magic_list = 'None';
if (!empty($spells)) {
$magic_list = '';
foreach ($spells as $spell) $magic_list .= $spell['name'].'<br>';
}
$showchar = render('show_char', [
'char' => $user,
'level' => $level,
'magic_list' => $magic_list
]);
return render('layouts/minimal', ['content' => $showchar, 'title' => $user->username.' Information']);
}
/**
* Show the user their position on the current world map. Only works with a game size of 250 and the default towns 😅
*/
function show_map()
{
$pos = sprintf(
'<div style="position: absolute; width: 5px; height: 5px; border-radius: 1000px; border: solid 1px black; background-color: red; left: %dpx; top: %dpx;"></div>',
round(258 + user()->longitude * (500 / 500) - 3),
round(258 - user()->latitude * (500 / 500) - 3)
);
echo render('layouts/minimal', [
'content' => '<img src="/img/map.gif" alt="Map">'.$pos,
'title' => 'Map'
]);
}
/**
* Handle a POST request to send a new babblebox message.
*/
function babblebox()
{
if (is_post()) {
$content = trim($_POST["babble"]);
if (!empty($content)) {
db()->query('INSERT INTO babble (posttime, author, babble) VALUES (CURRENT_TIMESTAMP, ?, ?);',
[user()->username, $content]);
}
return babblebox_messages();
}
}
/**
* The handler that is polled by HTMX for new babblebox messages.
*/
function babblebox_messages(): string
{
if (user() === false) return '';
$query = db()->query('SELECT * FROM babble ORDER BY id ASC LIMIT 40;');
$has_chats = false;
$messages = '';
while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
$has_chats = true;
$messages .= '<div class="message">[<b>' . $row['author'] . '</b>] ' . make_safe($row['babble']) . '</div>';
}
if (!$has_chats) $messages = 'There are no messages. :(';
return $messages;
}

62
public/install.php Normal file
View File

@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight;
use DragonKnight\Actions\Install;
ini_set('display_errors', 1);
error_reporting(E_ALL);
set_time_limit(0);
ignore_user_abort(true);
ini_set('max_execution_time', 0);
ini_set('memory_limit', '-1'); // Unlimited memory usage
function loadEnv(string $filePath = __DIR__.'/../.env'): void
{
if (! file_exists($filePath)) {
throw new \Exception('The .env file does not exist.');
}
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$trimmedLines = array_map('trim', $lines);
$filteredLines = array_filter($trimmedLines, fn ($line) => $line && ! str_starts_with($line, '#'));
array_walk($filteredLines, function ($line) {
[$name, $value] = array_map('trim', explode('=', $line, 2));
if (! array_key_exists($name, $_ENV)) {
putenv(sprintf('%s=%s', $name, $value));
}
});
}
loadEnv(__DIR__.'/../../.env');
if (! $autoloader = require file_exists(__DIR__.'/../vendor/autoload.php') ? __DIR__.'/../vendor/autoload.php' : __DIR__.'/../../autoload.php') {
throw new \Exception('Composer autoloader not found. Run `composer install` and try again.');
}
if (! extension_loaded('sqlite3')) {
throw new \Exception('The SQLite3 extension is required but not loaded. Please enable it in your PHP configuration.');
}
Install::second();
Install::fourth([
'username' => 'admin',
'email' => 'admin@example.com',
'confirm_email' => 'admin@example.com',
'password' => 'password',
'confirm_password' => 'password',
'charclass' => '1', // [1 => 'Mage', 2 => 'Warrior', 3 => 'Paladin']
]);
Install::fifth();

View File

@ -0,0 +1,617 @@
<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight\Actions;
use DragonKnight\Router;
use SQLite3Result;
use function DragonKnight\db;
use function DragonKnight\env;
use function DragonKnight\get_drop;
use function DragonKnight\get_item;
use function DragonKnight\get_monster;
use function DragonKnight\get_spell;
use function DragonKnight\get_town_by_id;
use function DragonKnight\is_post;
use function DragonKnight\make_safe;
use function DragonKnight\page_title;
use function DragonKnight\render;
use function DragonKnight\ul_from_validate_errors;
use function DragonKnight\user;
use function DragonKnight\validate;
class Admin
{
public static function register_routes(Router $r): Router
{
if (user() !== false && user()->authlevel === 1) {
$r->get('/admin', fn() => \DragonKnight\Actions\Admin::donothing());
$r->form('/admin/main', fn() => \DragonKnight\Actions\Admin::primary());
$r->get('/admin/items', fn() => \DragonKnight\Actions\Admin::items());
$r->form('/admin/items/:id', fn($id) => \DragonKnight\Actions\Admin::edit_item($id));
$r->get('/admin/drops', fn() => \DragonKnight\Actions\Admin::drops());
$r->form('/admin/drops/:id', fn($id) => \DragonKnight\Actions\Admin::edit_drop($id));
$r->get('/admin/towns', fn() => \DragonKnight\Actions\Admin::towns());
$r->form('/admin/towns/:id', fn($id) => \DragonKnight\Actions\Admin::edit_town($id));
$r->get('/admin/monsters', fn() => \DragonKnight\Actions\Admin::monsters());
$r->form('/admin/monsters/:id', fn($id) => \DragonKnight\Actions\Admin::edit_monster($id));
$r->get('/admin/levels', fn() => \DragonKnight\Actions\Admin::levels());
$r->post('/admin/levels', fn() => \DragonKnight\Actions\Admin::edit_level());
$r->get('/admin/spells', fn() => \DragonKnight\Actions\Admin::spells());
$r->form('/admin/spells/:id', fn($id) => \DragonKnight\Actions\Admin::edit_spell($id));
$r->get('/admin/users', fn() => \DragonKnight\Actions\Admin::users());
$r->form('/admin/users/:id', fn($id) => \DragonKnight\Actions\Admin::edit_user($id));
$r->form('/admin/news', fn() => \DragonKnight\Actions\Admin::add_news());
}
return $r;
}
/**
* Home page for the admin panel.
*/
public static function donothing(): string
{
page_title('Admin');
return <<<HTML
Welcome to the administration section. Use the links on the left bar to control and edit various
elements of the game.
<br><br>
Please note that the control panel has been created mostly as a shortcut for certain individual settings. It is
meant for use primarily with editing one thing at a time. If you need to completely replace an entire table
(say, to replace all stock monsters with your own new ones), it is suggested that you use a more in-depth
database tool such as <a href="https://sqlitebrowser.org/" target="_new">SQLite Browser</a>.
<br><br>
Also, you should be aware that certain portions of the DK code are dependent on the formatting of certain
database results (for example, the special attributes on item drops). While I have attempted to point these out
throughout the admin script, you should definitely pay attention and be careful when editing some fields,
because mistakes in the database content may result in script errors or your game breaking completely.
HTML;
}
/**
* Main settings that get written to .env.
*/
public static function primary(): string
{
if (is_post()) {
$form = validate($_POST, [
'gamename' => ['alphanum-spaces'],
'gamesize' => ['int', 'min:5'],
'class1name' => ['alpha-spaces'],
'class2name' => ['alpha-spaces'],
'class3name' => ['alpha-spaces'],
'gameopen' => ['bool'],
'verifyemail' => ['bool'],
'shownews' => ['bool'],
'showonline' => ['bool'],
'showbabble' => ['bool'],
]);
if ($form['valid']) {
$form = $form['data'];
if (($form['gamesize'] % 5) != 0) {
exit('Map size must be divisible by five.');
}
// @todo
// write changes to .env
$page = 'Main settings updated.';
} else {
$error_list = ul_from_validate_errors($form['errors']);
$page = <<<HTML
<b>Errors:</b><br>
<div style="color: red;">{$error_list}</div><br>
Please go back and try again.
HTML;
}
} else {
$page = render('admin/main_settings');
}
page_title('Admin: Main Settings');
return $page;
}
/**
* Show the full list of items that can be edited.
*/
public static function items(): string
{
$items = db()->query('SELECT * FROM items ORDER BY id;');
$page = "<h2>Edit Items</h2>Click an item's name or ID to edit it.<br><br>\n";
$page .= self::build_bulk_table($items, 'name', '/admin/items');
page_title('Admin: Items');
return $page;
}
/**
* Shows the form for editing an item via GET, processes edits via POST.
*/
public static function edit_item(int $id): string
{
$item = get_item($id);
$page = is_post()
? self::handle_edit_form($id, 'items', validate($_POST, [
'name' => [],
'type' => ['int', 'in:1,2,3'],
'buycost' => ['int', 'min:0'],
'attribute' => ['int', 'min:0'],
'special' => ['default:X'],
]))
: render('admin/edit_item', ['item' => $item]);
page_title('Admin: Editing '.$item['name']);
return $page;
}
/**
* Show the full list of drops that can be edited.
*/
public static function drops(): string
{
$drops = db()->query('SELECT * FROM drops ORDER BY id;');
$page = "<h2>Edit Drops</h2>Click an item's name to edit it.<br><br>\n";
$page .= self::build_bulk_table($drops, 'name', '/admin/drops');
page_title('Admin: Drops');
return $page;
}
/**
* Show the form to edit drops via GET, process those edits via POST.
*/
public static function edit_drop(int $id): string
{
$drop = get_drop($id);
if (is_post()) {
$page = self::handle_edit_form($id, 'drops', validate($_POST, [
'name' => [],
'mlevel' => ['int', 'min:1'],
'attribute1' => [],
'attribute2' => ['default:X'],
]));
} else {
$page = render('admin/edit_drop', ['drop' => $drop]);
}
page_title('Admin: Editing '.$drop['name']);
return $page;
}
/**
* Generate the list of towns that can be edited.
*/
public static function towns(): string
{
$towns = db()->query('SELECT * FROM towns ORDER BY id;');
$page = "<h2>Edit Towns</h2>Click an town's name or ID to edit it.<br><br>\n";
$page .= self::build_bulk_table($towns, 'name', '/admin/towns');
page_title('Admin: Towns');
return $page;
}
/**
* Save any changes to the town made.
*/
public static function edit_town(int $id): string
{
$town = get_town_by_id($id);
if (is_post()) {
$page = self::handle_edit_form($id, 'towns', validate($_POST, [
'name' => [],
'latitude' => ['int', 'min:0', 'max:'.env('game_size')],
'longitude' => ['int', 'min:0', 'max:'.env('game_size')],
'innprice' => ['int', 'min:0'],
'mapprice' => ['int', 'min:0'],
'travelpoints' => ['int', 'min:0'],
'itemslist' => ['optional'],
]));
} else {
$page = render('admin/edit_town', ['town' => $town]);
}
page_title('Admin: Editing '.$town['name']);
return $page;
}
/**
* List the monsters available to edit.
*/
public static function monsters(): string
{
$max_level = db()->query('SELECT level FROM monsters ORDER BY level DESC LIMIT 1;')->fetchArray(SQLITE3_ASSOC)['level'];
$monsters = db()->query('SELECT * FROM monsters ORDER BY id;');
$page = '<h2>Edit Monsters</h2>';
$page .= ((env('game_size') / 5) !== $max_level)
? '<span class="highlight">Note:</span> Your highest monster level does not match with your entered map size. Highest monster level should be '.(env('game_size') / 5).", yours is $max_level. Please fix this before opening the game to the public.<br>"
: 'Monster level and map size match. No further actions are required for map compatibility.<br>';
$page .= "Click an monster's name or ID to edit it.<br><br>\n";
$page .= self::build_bulk_table($monsters, 'name', '/admin/monsters');
page_title('Admin: Monsters');
return $page;
}
/**
* Handle the actual editing of the monster.
*/
public static function edit_monster(int $id): string
{
$monster = get_monster($id);
$page = (is_post())
? self::handle_edit_form($id, 'monsters', validate($_POST, [
'name' => [],
'maxhp' => ['int', 'min:1'],
'maxdam' => ['int', 'min:0'],
'armor' => ['int', 'min:0'],
'level' => ['int', 'min:1'],
'maxexp' => ['int', 'min:0'],
'maxgold' => ['int', 'min:0'],
'immune' => ['in:0,1,2'],
]))
: render('admin/edit_monster', ['monster' => $monster]);
page_title('Admin: Editing '.$monster['name']);
return $page;
}
/**
* List all spells available to edit.
*/
public static function spells(): string
{
$page = "<h2>Edit Spells</h2>Click an spell's name to edit it.<br><br>\n";
$spells = db()->query('SELECT * FROM spells ORDER BY id;');
$page .= self::build_bulk_table($spells, 'name', '/admin/spells');
page_title('Admin: Spells');
return $page;
}
/**
* Handle the editing of an individual spell.
*/
public static function edit_spell(int $id): string
{
$spell = get_spell($id);
$page = (is_post())
? self::handle_edit_form($id, 'spells', validate($_POST, [
'name' => [],
'mp' => ['int', 'min:0'],
'attribute' => ['int', 'min:0'],
'type' => ['in:1,2,3,4,5'],
]))
: render('admin/edit_spell', ['spell' => $spell]);
page_title('Admin: Editing '.$spell['name']);
return $page;
}
/**
* List all editable levels.
*/
public static function levels(): string
{
$max_level = db()->query('SELECT id FROM levels ORDER BY id DESC LIMIT 1;')->fetchArray(SQLITE3_ASSOC)['id'];
$page = <<<HTML
<h2>Edit Levels</h2>
Select a level number from the dropdown box to edit it.<br><br>
<form action="/admin/levels" method="post" hx-post="/admin/levels" hx-target="#main">
<select name="level">
HTML;
for ($i = 2; $i < $max_level; $i++) {
$page .= "<option value=\"$i\">$i</option>\n";
}
$page .= <<<HTML
</select>
<button type="submit">Edit</button>
</form>
HTML;
page_title('Admin: Levels');
return $page;
}
/**
* Handle the editing of a level.
*/
public static function edit_level(): string|false
{
if (! isset($_POST['level'])) {
return 'No level to edit.';
}
$id = $_POST['level'];
$level = db()->query('SELECT * FROM levels WHERE id=? LIMIT 1;', [$id])->fetchArray(SQLITE3_ASSOC);
if (is_post() && isset($_POST['save'])) {
unset($_POST['save']);
unset($_POST['level']);
$page = self::handle_edit_form($id, 'levels', validate($_POST, [
'1_exp' => ['int', 'min:0'],
'1_hp' => ['int', 'min:0'],
'1_mp' => ['int', 'min:0'],
'1_tp' => ['int', 'min:0'],
'1_strength' => ['int', 'min:0'],
'1_dexterity' => ['int', 'min:0'],
'1_spells' => ['int', 'min:0'],
'2_exp' => ['int', 'min:0'],
'2_hp' => ['int', 'min:0'],
'2_mp' => ['int', 'min:0'],
'2_tp' => ['int', 'min:0'],
'2_strength' => ['int', 'min:0'],
'2_dexterity' => ['int', 'min:0'],
'2_spells' => ['int', 'min:0'],
'3_exp' => ['int', 'min:0'],
'3_hp' => ['int', 'min:0'],
'3_mp' => ['int', 'min:0'],
'3_tp' => ['int', 'min:0'],
'3_strength' => ['int', 'min:0'],
'3_dexterity' => ['int', 'min:0'],
'3_spells' => ['int', 'min:0'],
]), 'Level <b>'.$id.'</b> updated.');
} else {
$page = render('admin/edit_level', ['level' => $level]);
}
page_title('Admin: Editing Level '.$id);
return $page;
}
public static function users(): string
{
$users = db()->query('SELECT * FROM users ORDER BY id;');
$page = '<h2>Edit Users</h2>Click a username or ID to edit the account.<br><br><div class="table-wrapper">';
$page .= self::build_bulk_table($users, 'username', '/admin/users');
page_title('Admin: Users');
return $page.'</div>';
}
/**
* Handle editing a user.
*/
public static function edit_user(int $id): string
{
$user = db()->query('SELECT * FROM users WHERE id = ? LIMIT 1;', [$id])->fetchArray(SQLITE3_ASSOC);
if (is_post()) {
$form = validate($_POST, [
'username' => ['length:3-18', 'alpha-spaces', 'unique:users,username'],
'verify' => [],
'authlevel' => ['int'],
'email' => ['email', 'unique:users,email'],
'charclass' => ['in:1,2,3'],
'latitude' => ['int', 'min:0', 'max:'.env('game_size')],
'longitude' => ['int', 'min:0', 'max:'.env('game_size')],
'currentaction' => [],
'currentfight' => ['int'],
'currentmonster' => ['int'],
'currentmonsterhp' => ['int'],
'currentmonstersleep' => ['int'],
'currentmonsterimmune' => ['int'],
'currentuberdamage' => ['int'],
'currentuberdefense' => ['int'],
'currenthp' => ['int', 'min:0'],
'currentmp' => ['int', 'min:0'],
'currenttp' => ['int', 'min:0'],
'maxhp' => ['int', 'min:1'],
'maxmp' => ['int', 'min:1'],
'maxtp' => ['int', 'min:1'],
'level' => ['int', 'min:1'],
'gold' => ['int', 'min:0'],
'experience' => ['int', 'min:0'],
'goldbonus' => ['int'],
'expbonus' => ['int'],
'strength' => ['int'],
'dexterity' => ['int'],
'attackpower' => ['int'],
'defensepower' => ['int'],
'weaponid' => ['int'],
'armorid' => ['int'],
'shieldid' => ['int'],
'slot1id' => ['int'],
'slot2id' => ['int'],
'slot3id' => ['int'],
'weaponname' => ['default:None'],
'armorname' => ['default:None'],
'shieldname' => ['default:None'],
'slot1name' => ['default:None'],
'slot2name' => ['default:None'],
'slot3name' => ['default:None'],
'dropcode' => ['int', 'min:0', 'default:0'],
'spells' => ['optional'],
'towns' => ['optional'],
]);
if ($form['valid']) {
self::save_data_row('users', $form['data'], $id);
$page = 'User <b>'.$user['username'].'</b> updated.';
} else {
$error_list = ul_from_validate_errors($form['errors']);
$page = <<<HTML
<b>Errors:</b><br>
<div style="color: red;">{$error_list}</div><br>
Please go back and try again.
HTML;
}
} else {
$page = render('admin/edit_user', ['user' => $user]);
}
page_title('Admin: Editing '.$user['username']);
return $page;
}
/**
* Handling adding news posts.
*/
public static function add_news(): string
{
if (is_post()) {
$c = trim($_POST['content'] ?? '');
$errors = [];
if (empty($c)) {
$errors[] = 'Content is required.';
}
if (count($errors) === 0) {
db()->query('INSERT INTO news (author, content) VALUES (?, ?);', [user()->username, $c]);
$page = 'News post added.';
} else {
$error_list = implode('<br>', $errors);
$page = "<b>Errors:</b><br><div style=\"color:red;\">$error_list</div><br>Please go back and try again.";
}
} else {
$page = <<<HTML
<h2>Add a News Post</h2>
<form action="/admin/news" method="post" hx-post="/admin/news" hx-target="#main">
Type your post below and then click Submit to add it.<br>
<textarea name="content" rows="5" cols="50"></textarea><br>
<button type="submit">Submit</button>
<button type="reset">Clear</button>
</form>
HTML;
}
page_title('Admin: Add News');
return $page;
}
/**
* Build an HTML table containing all columns and rows of a given data structure. Takes a SQLiteResult3 of a SELECT
* query.
*/
public static function build_bulk_table(SQLite3Result $query_data, string $edit_column, string $edit_link): string
{
$data = [];
$data_count = 0;
while ($row = $query_data->fetchArray(SQLITE3_ASSOC)) {
$data[$data_count++] = $row;
}
if ($data_count === 0) {
return 'No data.';
}
$columns = array_diff(array_keys($data[0]), ['password']);
$html_parts = [
'<table><colgroup>',
str_repeat('<col>', count($columns)),
'</colgroup><thead><tr>',
];
foreach ($columns as $column) {
$html_parts[] = '<th>'.
make_safe($column === 'id' ? 'ID' : ucfirst($column)).
'</th>';
}
$html_parts[] = '</tr></thead><tbody>';
$is_edit_column = array_flip(['id', $edit_column]);
foreach ($data as $row) {
$html_parts[] = '<tr>';
foreach ($columns as $column) {
$name = make_safe($row[$column]);
$html_parts[] = isset($is_edit_column[$column])
? "<td><a href=\"{$edit_link}/{$row['id']}\" hx-get=\"{$edit_link}/{$row['id']}\" hx-target=\"#main\">{$name}</a></td>"
: "<td>{$name}</td>";
}
$html_parts[] = '</tr>';
}
$html_parts[] = '</tbody></table>';
return implode('', $html_parts);
}
/**
* Save a row of data to it's table from the data supplied.
*/
public static function save_data_row(string $table, array $data, int $id): SQLite3Result|false
{
$data = array_filter($data, fn ($value) => $value !== null && $value !== '');
if (empty($data)) {
return false;
}
$fields = implode(',', array_map(fn ($key) => "`$key`=?", array_keys($data)));
$values = array_values($data);
$values[] = $id;
return db()->query("UPDATE $table SET $fields WHERE id=?", $values);
}
/**
* Handle the result of a generic edit form.
*/
public static function handle_edit_form(int $id, string $table, array $form, string $updated_message = ''): string
{
if ($form['valid']) {
self::save_data_row($table, $form['data'], $id);
$page = $updated_message ?: '<b>'.$form['data']['name'].'</b> updated.';
} else {
$error_list = ul_from_validate_errors($form['errors']);
$page = <<<HTML
<b>Errors:</b><br>
<div style="color: red;">{$error_list}</div><br>
Please go back and try again.
HTML;
}
return $page;
}
}

View File

@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight\Actions;
use function DragonKnight\env;
use function DragonKnight\get_town_by_xy;
use function DragonKnight\index;
use function DragonKnight\page_title;
use function DragonKnight\redirect;
use function DragonKnight\ul_from_validate_errors;
use function DragonKnight\user;
use function DragonKnight\validate;
class Explore
{
/**
* Just spit out a blank exploring page. Exploring without a GET string is normally when they first log in, or when
* they've just finished fighting.
*/
public static function explore(): string
{
page_title('Exploring');
return <<<HTML
<div class="title"><img src="/img/title_exploring.gif" alt="Exploring"></div>
You are exploring the map, and nothing has happened. Continue exploring using the direction buttons or the Travel To menus.
HTML;
}
public static function move(): string|false
{
// Early exit if fighting
if (user()->currentaction == 'Fighting') {
redirect('/fight');
}
// Validate direction
$form = validate($_POST, ['direction' => ['in:north,west,east,south']]);
if (! $form['valid']) {
return ul_from_validate_errors($form['errors']);
}
// Current game state
$game_size = env('game_size');
$latitude = user()->latitude;
$longitude = user()->longitude;
$direction = $form['data']['direction'];
// Calculate new coordinates with boundary checks
switch ($direction) {
case 'north':
$latitude = min($latitude + 1, $game_size);
break;
case 'south':
$latitude = max($latitude - 1, -$game_size);
break;
case 'east':
$longitude = min($longitude + 1, $game_size);
break;
case 'west':
$longitude = max($longitude - 1, -$game_size);
break;
}
// Check for town
$town = get_town_by_xy($longitude, $latitude);
if ($town !== false) {
return Towns::travelto($town['id'], false);
}
// Determine action (1 in 5 chance of fighting)
if (rand(1, 5) === 1) {
user()->currentaction = 'Fighting';
user()->currentfight = 1;
} else {
user()->currentaction = 'Exploring';
}
user()->latitude = $latitude;
user()->longitude = $longitude;
user()->save();
return index();
}
}

View File

@ -0,0 +1,567 @@
<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight\Actions;
use DragonKnight\Router;
use function DragonKnight\db;
use function DragonKnight\get_drop;
use function DragonKnight\get_monster;
use function DragonKnight\get_spell;
use function DragonKnight\page_title;
use function DragonKnight\redirect;
use function DragonKnight\render;
use function DragonKnight\user;
class Fight
{
public static function register_routes(Router $r): Router
{
$r->form('/fight', fn() => \DragonKnight\Actions\Fight::fight());
$r->get('/victory', fn() => \DragonKnight\Actions\Fight::victory());
$r->form('/drop', fn() => \DragonKnight\Actions\Fight::drop());
$r->get('/dead', fn() => \DragonKnight\Actions\Fight::dead());
return $r;
}
/**
* One big long public static function that determines the outcome of the fight.
*/
public static function fight(): string|false
{
if (user()->currentaction !== 'Fighting') {
exit('Cheat attempt detected.<br><br>Get a life, loser.');
}
$page = ['magiclist' => '', 'yourturn' => '', 'monsterturn' => '', 'monsterhp' => '', 'command' => ''];
$playerisdead = 0;
// Generate spell list
$user_spells = user()->spells();
if (! empty($user_spells)) {
$page['magiclist'] = '<select name="userspell">';
foreach ($user_spells as $spell) {
$page['magiclist'] .= "<option value=\"{$spell['id']}\">{$spell['name']}</option>\n";
}
$page['magiclist'] .= '</select> <input type="submit" name="spell" value="Spell"><br><br>';
}
// Determine initial combat parameters
$chancetoswingfirst = rand(1, 10) + (int) ceil(sqrt(user()->dexterity));
if (user()->currentfight === 1) {
$maxlevel = (int) floor(max(abs(user()->latitude) + 5, abs(user()->longitude) + 5) / 5);
$minlevel = max(1, $maxlevel - 2);
$monster = db()->query('SELECT * FROM monsters WHERE level >= ? AND level <= ? ORDER BY RANDOM() LIMIT 1;', [
$minlevel, $maxlevel,
])->fetchArray(SQLITE3_ASSOC);
user()->currentmonster = $monster['id'];
user()->currentmonsterhp = rand((int) (($monster['maxhp'] / 5) * 4), $monster['maxhp']);
user()->currentmonstersleep = 0;
user()->currentmonsterimmune = $monster['immune'];
$chancetoswingfirst = ($chancetoswingfirst > (rand(1, 7) + (int) ceil(sqrt($monster['maxdam'])))) ? 1 : 0;
}
// Get monster statistics
$monster = get_monster(user()->currentmonster);
$page['monstername'] = $monster['name'];
// Run action
if (isset($_POST['run'])) {
$chancetorun = rand(4, 10) + (int) ceil(sqrt(user()->dexterity));
if ($chancetorun <= (rand(1, 5) + (int) ceil(sqrt($monster['maxdam'])))) {
$page['yourturn'] = 'You tried to run away, but were blocked in front!<br><br>';
$page['monsterhp'] = "Monster's HP: ".user()->currentmonsterhp.'<br><br>';
// Monster turn logic (similar to original public static function)
$page['monsterturn'] = self::handleMonsterTurn($userrow, $monster);
user()->currentaction = 'Exploring';
user()->save();
redirect('/');
}
}
// Fight action
if (isset($_POST['fight'])) {
// Player's attack
$min = (int) (user()->attackpower * 0.75);
$max = (int) (user()->attackpower / 3);
$tohit = (int) ceil(mt_rand(min($min, $max), max($min, $max)));
$toexcellent = rand(1, 150);
if ($toexcellent <= sqrt(user()->strength)) {
$tohit *= 2;
$page['yourturn'] .= 'Excellent hit!<br>';
}
$min = (int) ($monster['armor'] * 0.75);
$max = (int) $monster['armor'];
$toblock = (int) ceil(rand(min($min, $max), max($min, $max)) / 3);
$tododge = rand(1, 100);
$monsterdamage = max(1, $tohit - $toblock);
if ($tododge <= sqrt($monster['armor'])) {
$monsterdamage = 0;
$page['yourturn'] .= 'The monster is dodging. No damage has been scored.<br>';
}
if (user()->currentuberdamage != 0) {
$monsterdamage += (int) ceil($monsterdamage * (user()->currentuberdamage / 100));
}
user()->currentmonsterhp -= $monsterdamage;
$page['yourturn'] .= "You attack the monster for $monsterdamage damage.<br><br>";
$page['monsterhp'] = "Monster's HP: ".user()->currentmonsterhp.'<br><br>';
// Check for monster defeat
if (user()->currentmonsterhp <= 0) {
user()->currentmonsterhp = 0;
user()->save();
redirect('/victory');
}
// Monster's turn
$page['monsterturn'] = self::handleMonsterTurn($userrow, $monster);
}
// Spell action
if (isset($_POST['spell'])) {
$pickedspell = $_POST['userspell'];
if ($pickedspell == 0) {
return 'You must select a spell first. Please go back and try again.';
}
$newspellrow = get_spell($pickedspell);
$spell = in_array($pickedspell, explode(',', user()->spells));
if (! $spell) {
return 'You have not yet learned this spell. Please go back and try again.';
}
if (user()->currentmp < $newspellrow['mp']) {
return 'You do not have enough Magic Points to cast this spell. Please go back and try again.';
}
// Spell type handling (similar to original public static function)
$page['yourturn'] = self::handleSpellCast($userrow, $newspellrow);
$page['monsterhp'] = "Monster's HP: ".user()->currentmonsterhp.'<br><br>';
// Check for monster defeat
if (user()->currentmonsterhp <= 0) {
user()->currentmonsterhp = 0;
user()->save();
redirect('/victory');
}
// Monster's turn
$page['monsterturn'] = self::handleMonsterTurn($userrow, $monster);
}
// Monster's turn if player lost first swing
if (! isset($_POST['run']) && ! isset($_POST['fight']) && ! isset($_POST['spell']) && $chancetoswingfirst == 0) {
$page['yourturn'] = 'The monster attacks before you are ready!<br><br>';
$page['monsterhp'] = "Monster's HP: ".user()->currentmonsterhp.'<br><br>';
$page['monsterturn'] = self::handleMonsterTurn($userrow, $monster);
}
// Prepare command or death message
if ($playerisdead != 1) {
$page['command'] = <<<HTML
Command?<br><br>
<form action="/fight" method="post" hx-post="/fight" hx-target="#middle">
<input type="submit" name="fight" value="Fight"><br><br>
{$page['magiclist']}
<input type="submit" name="run" value="Run"><br><br>
</form>
HTML;
user()->currentfight += 1;
} else {
$page['command'] = <<<HTML
<b>You have died.</b><br><br>
As a consequence, you've lost half of your gold. However, you have been given back a portion of your hit points to continue your journey.<br><br>
You may now continue back to <a href="/" hx-get="/" hx-target="#middle">town</a>, and we hope you fair better next time.
HTML;
}
user()->save();
// Finalize page and display it
$page = render('fight', ['page' => $page]);
return $page;
}
public static function victory(): string
{
if (user()->currentmonsterhp != 0) {
redirect('/fight');
}
if (user()->currentfight == 0) {
redirect('/');
}
$monsterrow = get_monster(user()->currentmonster);
$min = (int) (($monsterrow['maxexp'] / 6) * 5);
$max = (int) $monsterrow['maxexp'];
$exp = mt_rand(min($min, $max), max($min, $max));
if ($exp < 1) {
$exp = 1;
}
if (user()->expbonus != 0) {
$exp += ceil((user()->expbonus / 100) * $exp);
}
$min = (int) (($monsterrow['maxgold'] / 6) * 5);
$max = (int) $monsterrow['maxgold'];
$gold = mt_rand(min($min, $max), max($min, $max));
if ($gold < 1) {
$gold = 1;
}
if (user()->goldbonus != 0) {
$gold += ceil((user()->goldbonus / 100) * $exp);
}
if (user()->experience + $exp < 16777215) {
$newexp = user()->experience += $exp;
$warnexp = '';
} else {
$newexp = user()->experience;
$exp = 0;
$warnexp = 'You have maxed out your experience points.';
}
if (user()->gold + $gold < 16777215) {
$newgold = user()->gold += $gold;
$warngold = '';
} else {
$newgold = user()->gold;
$gold = 0;
$warngold = 'You have maxed out your gold.';
}
$levelrow = db()->query('SELECT * FROM levels WHERE id=? LIMIT 1;', [user()->level + 1])->fetchArray(SQLITE3_ASSOC);
$page = '';
if (user()->level < 100) {
if ($newexp >= $levelrow[user()->charclass.'_exp']) {
user()->maxhp += $levelrow[user()->charclass.'_hp'];
user()->maxmp += $levelrow[user()->charclass.'_mp'];
user()->maxtp += $levelrow[user()->charclass.'_tp'];
user()->strength += $levelrow[user()->charclass.'_strength'];
user()->dexterity += $levelrow[user()->charclass.'_dexterity'];
user()->attackpower += $levelrow[user()->charclass.'_strength'];
user()->defensepower += $levelrow[user()->charclass.'_dexterity'];
user()->level += 1;
$newlevel = $levelrow['id'];
if ($levelrow[user()->charclass.'_spells'] != 0) {
user()->spells .= ','.$levelrow[user()->charclass.'_spells'];
$spelltext = 'You have learned a new spell.<br>';
} else {
$spelltext = '';
$newspell = '';
}
$page = 'Congratulations. You have defeated the '.$monsterrow['name'].".<br>You gain $exp experience. $warnexp <br>You gain $gold gold. $warngold <br><br><b>You have gained a level!</b><br><br>You gain ".$levelrow[user()->charclass.'_hp'].' hit points.<br>You gain '.$levelrow[user()->charclass.'_mp'].' magic points.<br>You gain '.$levelrow[user()->charclass.'_tp'].' travel points.<br>You gain '.$levelrow[user()->charclass.'_strength'].' strength.<br>You gain '.$levelrow[user()->charclass.'_dexterity']." dexterity.<br>$spelltext<br>You can now continue <a href=\"/\" hx-get=\"/\" hx-target=\"#middle\">exploring</a>.";
$title = 'Courage and Wit have served thee well!';
$dropcode = '';
} else {
$page = 'Congratulations. You have defeated the '.$monsterrow['name'].".<br>You gain $exp experience. $warnexp <br>You gain $gold gold. $warngold <br><br>";
if (rand(1, 30) === 1) {
$droprow = db()->query('SELECT * FROM drops WHERE mlevel <= ? ORDER BY RANDOM() LIMIT 1;', [$monsterrow['level']])->fetchArray(SQLITE3_ASSOC);
$dropcode = "dropcode='".$droprow['id']."',";
$page .= 'This monster has dropped an item. <a href="/drop" hx-get="/drop" hx-target="#middle">Click here</a> to reveal and equip the item, or you may also move on and continue <a href="/" hx-get="/" hx-target="#middle">exploring</a>.';
} else {
$dropcode = '';
$page .= 'You can now continue <a href="/" hx-get="/" hx-target="#middle">exploring</a>.';
}
$title = 'Victory!';
}
}
user()->currentaction = 'Exploring';
user()->currentfight = 0;
user()->currentuberdamage = 0;
user()->currentuberdefense = 0;
user()->currentmonstersleep = 0;
user()->currentmonsterimmune = 0;
user()->save();
page_title($title);
return $page;
}
public static function drop(): string
{
if (user()->dropcode == 0) {
redirect('/');
}
$droprow = get_drop(user()->dropcode);
if (isset($_POST['submit'])) {
$slot = $_POST['slot'];
if ($slot === 0) {
return 'Please go back and select an inventory slot to continue.';
}
$slotstr = 'slot'.$slot.'id';
if (user()->$slotstr != 0) {
$slotrow = get_drop(user()->$slotstr);
$old1 = explode(',', $slotrow['attribute1']);
if ($slotrow['attribute2'] != 'X') {
$old2 = explode(',', $slotrow['attribute2']);
} else {
$old2 = [0 => 'maxhp',1 => 0];
}
$new1 = explode(',', $droprow['attribute1']);
if ($droprow['attribute2'] != 'X') {
$new2 = explode(',', $droprow['attribute2']);
} else {
$new2 = [0 => 'maxhp',1 => 0];
}
user()->$old1[0] -= $old1[1];
user()->$old2[0] -= $old2[1];
if ($old1[0] == 'strength') {
user()->attackpower -= $old1[1];
}
if ($old1[0] == 'dexterity') {
user()->defensepower -= $old1[1];
}
if ($old2[0] == 'strength') {
user()->attackpower -= $old2[1];
}
if ($old2[0] == 'dexterity') {
user()->defensepower -= $old2[1];
}
user()->$new1[0] += $new1[1];
user()->$new2[0] += $new2[1];
if ($new1[0] == 'strength') {
user()->attackpower += $new1[1];
}
if ($new1[0] == 'dexterity') {
user()->defensepower += $new1[1];
}
if ($new2[0] == 'strength') {
user()->attackpower += $new2[1];
}
if ($new2[0] == 'dexterity') {
user()->defensepower += $new2[1];
}
if (user()->currenthp > user()->maxhp) {
user()->currenthp = user()->maxhp;
}
if (user()->currentmp > user()->maxmp) {
user()->currentmp = user()->maxmp;
}
if (user()->currenttp > user()->maxtp) {
user()->currenttp = user()->maxtp;
}
$slot_s = 'slot'.$_POST['slot'];
$slot_name = "{$slot_s}name";
$slot_id = "{$slot_s}id";
user()->$slot_name = $droprow['name'];
user()->$slot_id = $droprow['id'];
} else {
$new1 = explode(',', $droprow['attribute1']);
if ($droprow['attribute2'] != 'X') {
$new2 = explode(',', $droprow['attribute2']);
} else {
$new2 = [0 => 'maxhp',1 => 0];
}
user()->$new1[0] += $new1[1];
user()->$new2[0] += $new2[1];
if ($new1[0] == 'strength') {
user()->attackpower += $new1[1];
}
if ($new1[0] == 'dexterity') {
user()->defensepower += $new1[1];
}
if ($new2[0] == 'strength') {
user()->attackpower += $new2[1];
}
if ($new2[0] == 'dexterity') {
user()->defensepower += $new2[1];
}
$slot_s = 'slot'.$_POST['slot'];
$slot_name = "{$slot_s}name";
$slot_id = "{$slot_s}id";
user()->$slot_name = $droprow['name'];
user()->$slot_id = $droprow['id'];
}
user()->save();
return 'The item has been equipped. You can now continue <a href="/" hx-get="/" hx-target="#middle">exploring</a>.';
}
$attributearray = ['maxhp' => 'Max HP',
'maxmp' => 'Max MP',
'maxtp' => 'Max TP',
'defensepower' => 'Defense Power',
'attackpower' => 'Attack Power',
'strength' => 'Strength',
'dexterity' => 'Dexterity',
'expbonus' => 'Experience Bonus',
'goldbonus' => 'Gold Bonus'];
$page = 'The monster dropped the following item: <b>'.$droprow['name'].'</b><br><br>';
$page .= 'This item has the following attribute(s):<br>';
$attribute1 = explode(',', $droprow['attribute1']);
$page .= $attributearray[$attribute1[0]];
if ($attribute1[1] > 0) {
$page .= ' +'.$attribute1[1].'<br>';
} else {
$page .= $attribute1[1].'<br>';
}
if ($droprow['attribute2'] != 'X') {
$attribute2 = explode(',', $droprow['attribute2']);
$page .= $attributearray[$attribute2[0]];
if ($attribute2[1] > 0) {
$page .= ' +'.$attribute2[1].'<br>';
} else {
$page .= $attribute2[1].'<br>';
}
}
$page .= '<br>Select an inventory slot from the list below to equip this item. If the inventory slot is already full, the old item will be discarded.';
$page .= '<form action="/drop" method="post"><select name="slot"><option value="0">Choose One</option><option value="1">Slot 1: '.user()->slot1name.'</option><option value="2">Slot 2: '.user()->slot2name.'</option><option value="3">Slot 3: '.user()->slot3name.'</option></select> <input type="submit" name="submit" value="Submit" /></form>';
$page .= 'You may also choose to just continue <a href="/" hx-get="/" hx-target="#middle">exploring</a> and give up this item.';
return $page;
}
public static function dead(): string
{
return <<<HTML
<b>You have died.</b><br><br>
As a consequence, you've lost half of your gold. However, you have been given back a portion of your hit points
to continue your journey.<br><br>
You may now continue back to <a href="/" hx-get="/" hx-target="#middle">town</a>, and we hope you fair better next time.
HTML;
}
public static function handleMonsterTurn(&$userrow, $monsterrow): string
{
$pagearray = '';
if (user()->currentmonstersleep != 0) {
$chancetowake = rand(1, 15);
if ($chancetowake > user()->currentmonstersleep) {
user()->currentmonstersleep = 0;
$pagearray .= 'The monster has woken up.<br>';
} else {
$pagearray .= 'The monster is still asleep.<br>';
}
}
if (user()->currentmonstersleep == 0) {
$tohit = (int) ceil(mt_rand((int) ($monsterrow['maxdam'] * 0.5), (int) $monsterrow['maxdam']));
$toblock = (int) ceil(mt_rand((int) (user()->defensepower * 0.75), (int) user()->defensepower) / 4);
$tododge = rand(1, 150);
if ($tododge <= sqrt(user()->dexterity)) {
$tohit = 0;
$pagearray .= "You dodge the monster's attack. No damage has been scored.<br>";
$persondamage = 0;
} else {
$persondamage = max(1, $tohit - $toblock);
if (user()->currentuberdefense != 0) {
$persondamage -= (int) ceil($persondamage * (user()->currentuberdefense / 100));
}
$persondamage = max(1, $persondamage);
}
$pagearray .= "The monster attacks you for $persondamage damage.<br><br>";
user()->currenthp -= $persondamage;
if (user()->currenthp <= 0) {
$newgold = (int) ceil(user()->gold / 2);
$newhp = (int) ceil(user()->maxhp / 4);
db()->query("UPDATE users SET currenthp=?, currentaction='In Town', currentmonster=0, currentmonsterhp=0, currentmonstersleep=0, currentmonsterimmune=0, currentfight=0, latitude=0, longitude=0, gold=? WHERE id=?;", [
$newhp, $newgold, $userrow['id'],
]);
self::dead();
}
}
return $pagearray;
}
public static function handleSpellCast(&$userrow, $newspellrow): string
{
$pagearray = '';
switch ($newspellrow['type']) {
case 1: // Heal spell
$newhp = min(user()->currenthp + $newspellrow['attribute'], user()->maxhp);
user()->currenthp = $newhp;
user()->currentmp -= $newspellrow['mp'];
$pagearray = "You have cast the {$newspellrow['name']} spell, and gained {$newspellrow['attribute']} Hit Points.<br><br>";
break;
case 2: // Hurt spell
if (user()->currentmonsterimmune == 0) {
$monsterdamage = mt_rand((int) (($newspellrow['attribute'] / 6) * 5), $newspellrow['attribute']);
user()->currentmonsterhp -= $monsterdamage;
$pagearray = "You have cast the {$newspellrow['name']} spell for $monsterdamage damage.<br><br>";
} else {
$pagearray = "You have cast the {$newspellrow['name']} spell, but the monster is immune to it.<br><br>";
}
user()->currentmp -= $newspellrow['mp'];
break;
case 3: // Sleep spell
if (user()->currentmonsterimmune != 2) {
user()->currentmonstersleep = $newspellrow['attribute'];
$pagearray = "You have cast the {$newspellrow['name']} spell. The monster is asleep.<br><br>";
} else {
$pagearray = "You have cast the {$newspellrow['name']} spell, but the monster is immune to it.<br><br>";
}
user()->currentmp -= $newspellrow['mp'];
break;
case 4: // +Damage spell
user()->currentuberdamage = $newspellrow['attribute'];
user()->currentmp -= $newspellrow['mp'];
$pagearray = "You have cast the {$newspellrow['name']} spell, and will gain {$newspellrow['attribute']}% damage until the end of this fight.<br><br>";
break;
case 5: // +Defense spell
user()->currentuberdefense = $newspellrow['attribute'];
user()->currentmp -= $newspellrow['mp'];
$pagearray = "You have cast the {$newspellrow['name']} spell, and will gain {$newspellrow['attribute']}% defense until the end of this fight.<br><br>";
break;
}
return $pagearray;
}
}

View File

@ -0,0 +1,144 @@
<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight\Actions;
use DragonKnight\Router;
use function DragonKnight\db;
use function DragonKnight\page_title;
use function DragonKnight\pretty_date;
use function DragonKnight\redirect;
use function DragonKnight\ul_from_validate_errors;
use function DragonKnight\user;
use function DragonKnight\validate;
class Forum
{
public static function register_routes(Router $r): Router
{
$r->get('/forum/thread/:x/:x', fn($x, $y) => \DragonKnight\Actions\Forum::showthread($x, $y));
$r->form('/forum/new', fn() => \DragonKnight\Actions\Forum::newthread());
$r->post('/forum/reply', fn() => \DragonKnight\Actions\Forum::reply());
$r->get('/forum/list/:x', fn($x) => \DragonKnight\Actions\Forum::donothing($x));
$r->get('/forum', fn() => \DragonKnight\Actions\Forum::donothing());
return $r;
}
public static function donothing($start = 0): string
{
$query = db()->query('SELECT * FROM forum WHERE parent=0 ORDER BY newpostdate DESC LIMIT 20 OFFSET ?;', [20 * $start]);
$page = <<<HTML
<table width="100%">
<tr>
<td style="padding: 1px; background-color: black;">
<table width="100%" style="margins: 0px;" cellspacing="1" cellpadding="3">
<tr>
<th colspan="3" style="background-color: #ddd;">
<center><a href="/forum/new" hx-get="/forum/new" hx-target="#middle">New Thread</a></center>
</th>
</tr>
<tr>
<th width="50%" style="background-color:#dddddd;">Thread</th>
<th width="10%" style="background-color:#dddddd;">Replies</th>
<th style="background-color:#dddddd;">Last Post</th>
</tr>
HTML;
$hasRows = false;
while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
$hasRows = true;
$page .= <<<HTML
<tr>
<td style="background-color: white;"><a href="/forum/thread/{$row['id']}/0" hx-get="/forum/thread/{$row['id']}/0" hx-target="#middle">{$row['title']}</a></td>
<td style="background-color: white;">{$row['replies']}</td>
<td style="background-color: white;">{$row['newpostdate']}</td>
</tr>
HTML;
}
if (! $hasRows) {
$page .= '<tr><td style="background-color:#ffffff;" colspan="3"><b>No threads in forum.</b></td></tr>';
}
$page .= '</table></td></tr></table>';
page_title('Forum');
return $page;
}
public static function showthread($id, $start): string
{
$posts = db()->query('SELECT * FROM forum WHERE id=? OR parent=? ORDER BY id LIMIT 15 OFFSET ?;', [$id, $id, $start * 15]);
$title = db()->query('SELECT title FROM forum WHERE id=? LIMIT 1;', [$id])->fetchArray(SQLITE3_ASSOC);
$page = '<table width="100%"><tr><td style="padding:1px; background-color:black;"><table width="100%" style="margins:0px;" cellspacing="1" cellpadding="3"><tr><td colspan="2" style="background-color:#dddddd;"><b><a href="/forum" hx-get="/forum" hx-target="#middle">Forum</a> :: '.$title['title']."</b></td></tr>\n";
while ($row = $posts->fetchArray(SQLITE3_ASSOC)) {
$page .= '<tr><td width="25%" style="background-color:#ffffff; vertical-align:top;"><span class="small"><b>'.$row['author'].'</b><br><br>'.pretty_date($row['postdate']).'</td><td style="background-color:#ffffff; vertical-align:top;">'.nl2br($row['content'])."</td></tr>\n";
}
$page .= '</table></td></tr></table><br>';
$page .= "<table width=\"100%\"><tr><td><b>Reply To This Thread:</b><br><form action=\"/forum/reply\" method=\"post\" hx-post=\"/forum/reply\" hx-target=\"#middle\"><input type=\"hidden\" name=\"parent\" value=\"$id\" /><input type=\"hidden\" name=\"title\" value=\"Re: ".$title['title'].'" /><textarea name="content" rows="7" cols="40"></textarea><br><input type="submit" name="submit" value="Submit" /> <input type="reset" name="reset" value="Reset" /></form></td></tr></table>';
page_title('Forum: '.$title['title']);
return $page;
}
public static function reply(): string
{
$form = validate($_POST, [
'title' => [],
'content' => [],
]);
if (! $form['valid']) {
exit(ul_from_validate_errors($form['errors']));
}
$form = $form['data'];
db()->query('INSERT INTO forum (author, title, content, parent) VALUES (?, ?, ?, ?);', [
user()->username, $form['title'], $form['content'], $form['parent'],
]);
db()->query('UPDATE forum SET newpostdate=CURRENT_TIMESTAMP, replies=replies + 1 WHERE id=?;', [$form['parent']]);
return self::showthread($form['parent'], 0);
}
public static function newthread()
{
if (isset($_POST['submit'])) {
$form = validate($_POST, [
'title' => ['length:2-30'],
'content' => [],
]);
if (! $form['valid']) {
exit(ul_from_validate_errors($form['errors']));
}
$form = $form['data'];
db()->query('INSERT INTO forum (author, title, content) VALUES (?, ?, ?);', [
user()->username, $form['title'], $form['content'],
]);
redirect('/forum/thread/'.db()->lastInsertRowID().'/0');
}
page_title('Form: New Thread');
return '<table width="100%"><tr><td><b>Make A New Post:</b><br><br/ ><form action="/forum/new" method="post" hx-post="/forum/new" hx-target="#middle">Title:<br><input type="text" name="title" size="50" maxlength="50" /><br><br>Message:<br><textarea name="content" rows="7" cols="40"></textarea><br><br><input type="submit" name="submit" value="Submit" /> <input type="reset" name="reset" value="Reset" /></form></td></tr></table>';
}
}

View File

@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight\Actions;
use function DragonKnight\get_spell;
use function DragonKnight\page_title;
use function DragonKnight\user;
class Heal
{
public static function healspells(int $id): string
{
$user_spells = user()->spells();
$spell = get_spell($id);
$has_spell = false;
foreach ($user_spells as $us) {
if ($us['id'] === $id) {
$has_spell = true;
}
}
if ($has_spell !== true) {
$page = 'You have not yet learned this spell. Please go back and try again.';
} elseif ($spell['type'] !== 1) {
$page = 'This is not a healing spell. Please go back and try again.';
} elseif (user()->currentmp < $spell['mp']) {
$page = 'You do not have enough Magic Points to cast this spell. Please go back and try again.';
} elseif (user()->currentaction === 'Fighting') {
$page = 'You cannot use the Quick Spells list during a fight. Please go back and select the Healing Spell you wish to use from the Spells box on the main fighting screen to continue.';
} elseif (user()->currenthp == user()->maxhp) {
$page = 'Your HP is already full. You don\'t need to use a Healing spell now.';
} else {
$restored = user()->restore_hp($spell['attribute']);
user()->currentmp -= $spell['mp'];
user()->save();
$page = <<<HTML
You have cast the {$spell['name']} spell, and gained {$restored} HP. You can now continue <a href="/" hx-get="/" hx-target="#middle">exploring</a>.
HTML;
}
page_title('Casting '.$spell['name']);
return $page;
}
}

View File

@ -0,0 +1,521 @@
<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight\Actions;
use DragonKnight\DragonKnight;
use DragonKnight\Router;
use function DragonKnight\db;
use function DragonKnight\render;
use function DragonKnight\special_to_string;
class Help
{
public static function register_routes(Router $r): Router
{
$r->get('/help', fn() => \DragonKnight\Actions\Help::main());
$r->get('/help/items', fn() => \DragonKnight\Actions\Help::items());
$r->get('/help/spells', fn() => \DragonKnight\Actions\Help::spells());
$r->get('/help/monsters', fn() => \DragonKnight\Actions\Help::monsters());
$r->get('/help/levels', fn() => \DragonKnight\Actions\Help::levels());
return $r;
}
public static function main(): string|false
{
$page = <<<HTML
<h3>Table of Contents</h3>
<ul>
<li><a href="#intro">Introduction</a></li>
<li><a href="#classes">Character Classes</a></li>
<li><a href="#intown">Playing The Game: In Town</a></li>
<li><a href="#exploring">Playing The Game: Exploring & Fighting</a></li>
<li><a href="#status">Playing The Game: Status Panels</a></li>
<li><a href="#items">Spoilers: Items & Drops</a></li>
<li><a href="#monsters">Spoilers: Monsters</a></li>
<li><a href="#spells">Spoilers: Spells</a></li>
<li><a href="#levels">Spoilers: Levels</a></li>
<li><a href="#credits">Credits</a></li>
</ul>
<hr>
<h3><a name="intro"></a>Introduction</h3>
Firstly, I'd like to say thank you for playing my game. The <i>Dragon Knight</i> game engine is the result of several months of
planning, coding and testing. The original idea was to create a web-based tribute to the NES game, <i>Dragon
Warrior</i>. In its current iteration, only the underlying fighting system really resembles that game, as almost
everything else in DK has been made bigger and better. But you should still recognize bits and pieces as stemming
from <i>Dragon Warrior</i> and other RPGs of old.<br><br>
This is the first game I've ever written, and it has definitely been a positive experience. It got difficult at
times, admittedly, but it was still a lot of fun to write, and even more fun to play. And I hope to use this
experience so that if I ever want to create another game it will be even better than this one.<br><br>
If you are a site administrator, and would like to install a copy of DK on your own server, you may visit the
<a href="http://dragon.se7enet.com/dev.php" target="_new">development site</a> for <i>Dragon Knight</i>. This page
includes the downloadable game souce code, as well as some other resources that developers and administrators may
find valuable.<br><br>
Once again, thanks for playing!<br><br>
<i>Jamin Seven</i><br>
<i>Dragon Knight creator</i><br>
<a href="http://www.se7enet.com" target="_new">My Homepage</a><br>
<a href="http://dragon.se7enet.com/dev.php" target="_new">Dragon Knight Homepage</a><br ><br>
[ <a href="#top">Top</a> ]
<br><br><hr>
<h3><a name="classes"></a>Character Classes</h3>
There are three character classes in the game. The main differences between the classes are what spells you get
access to, the speed with which you level up, and the amount of HP/MP/strength/dexterity you gain per level. Below
is a basic outline of each of the character classes. For more detailed information about the characters, please
view the Levels table at the bottom of this page. Also, note that the outline below refers to the stock class setup
for the game. If your administrator has used his/her own class setup, this information may not be accurate.<br><br>
<b>{env('class_1_name')}</b>
<ul>
<li>Fast level-ups</li>
<li>High hit points</li>
<li>High magic points</li>
<li>Low strength</li>
<li>Low dexterity</li>
<li>5 heal spells</li>
<li>5 hurt spells</li>
<li>3 sleep spells</li>
<li>3 +defense spells</li>
<li>0 +attack spells</li>
</ul>
<b>{env('class_2_name')}</b>
<ul>
<li>Medium level-ups</li>
<li>Medium hit points</li>
<li>Low magic points</li>
<li>High strength</li>
<li>Low dexterity</li>
<li>3 heal spells</li>
<li>3 hurt spells</li>
<li>2 sleep spells</li>
<li>3 +defense spells</li>
<li>3 +attack spells</li>
</ul>
<b>{env('class_3_name')}</b>
<ul>
<li>Slow level-ups</li>
<li>Medium hit points</li>
<li>Medium magic points</li>
<li>Low strength</li>
<li>High dexterity</li>
<li>4 heal spells</li>
<li>4 hurt spells</li>
<li>3 sleep spells</li>
<li>2 +defense spells</li>
<li>2 +attack spells</li>
</ul>
[ <a href="#top">Top</a> ]
<br><br><hr>
<h3><a name="intown"></a>Playing The Game: In Town</h3>
When you begin a new game, the first thing you see is the Town screen. Towns serve four primary public static functions: healing, buying items,
buying maps, and displaying game information.<br><br>
To heal yourself, click the "Rest at the Inn" link at the top of the town screen. Each town's Inn has a different price - some towns
are cheap, others are expensive. No matter what town you're in, the Inns always serve the same public static function: they restore your current
hit points, magic points, and travel points to their maximum amounts. Out in the field, you are free to use healing spells to restore
your hit points, but when you run low on magic points, the only way to restore them is at an Inn.<br><br>
Buying weapons and armor is accomplished through the appropriately-named "Buy Weapons/Armor" link. Not every item is available in
every town, so in order to get the most powerful items, you'll need to explore some of the outer towns. Once you've clicked the link,
you are presented with a list of items available in this town's store. To the left of each item is an icon that represents its type:
weapon, armor or shield. The amount of attack/defense power, as well as the item's price, are displayed to the right of the item name.
You'll notice that some items have a red asterisk (<span class="highlight">*</span>) next to their names. These are items that come
with special attributes that modify other parts of your character profile. See the Items & Drops table at the bottom of this page for
more information about special items.<br><br>
Maps are the third public static function in towns. Buying a map to a town places the town in your Travel To box in the left status panel. Once
you've purchased a town's map, you can click its name from your Travel To box and you will jump to that town. Travelling this way
costs travel points, though, and you'll only be able to visit towns if you have enough travel points.<br><br>
The final public static function in towns is displaying game information and statistics. This includes the latest news post made by the game
administrator, a list of players who have been online recently, and the Babble Box.<br><br>
[ <a href="#top">Top</a> ]
<br><br><hr>
<h3><a name="exploring"></a>Playing The Game: Exploring & Fighting</h3>
Once you're done in town, you are free to start exploring the world. Use the compass buttons on the left status panel to move around.
The game world is basically a big square, divided into four quadrants. Each quadrant is {{gamesize}} spaces
square. The first town is usually located at (0N,0E). Click the North button from the first town, and now you'll be at (1N,0E).
Likewise, if you now click the West button, you'll be at (1N,1W). Monster levels increase with every 5 spaces you move outward
from (0N,0E).<br><br>
While you're exploring, you will occasionally run into monsters. As in pretty much any other RPG game, you and the monster take turns
hitting each other in an attempt to reduce each other's hit points to zero. Once you run into a monster, the Exploring screen changes
to the Fighting screen.<br><br>
When a fight begins, you'll see the monster's name and hit points, and the game will ask you for your first command. You then get to
pick whether you want to fight, use a spell, or run away. Note, though, that sometimes the monster has the chance to hit you
first.<br><br>
The Fight button is pretty straightforward: you attack the monster, and the amount of damage dealt is based on your attack power and
the monster's armor. On top of that, there are two other things that can happen: an Excellent Hit, which doubles your total attack
damage; and a monster dodge, which results in you doing no damage to the monster.<br><br>
The Spell button allows you to pick an available spell and cast it. See the Spells list at the bottom of this page for more information
about spells.<br><br>
Finally, there is the Run button, which lets you run away from a fight if the monster is too powerful. Be warned, though: it is
possible for the monster to block you from running and attack you. So if your hit points are low, you may fare better by staying
around monsters that you know can't do much damage to you.<br><br>
Once you've had your turn, the monster also gets his turn. It is also possible for you to dodge the monster's attack and take no
damage.<br><br>
The end result of a fight is either you or the monster being knocked down to zero hit points. If you win, the monster dies and will
give you a certain amount of experience and gold. There is also a chance that the monster will drop an item, which you can put into
one of the three inventory slots to give you extra points in your character profile. If you lose and die, half of your gold is taken
away - however, you are given back a few hit points to help you make it back to town (for example, if you don't have enough gold to
pay for an Inn, and need to kill a couple low-level monsters to get the money).<br><br>
When the fight is over, you can continue exploring until you find another monster to beat into submission.<br><br>
[ <a href="#top">Top</a> ]
<br><br><hr>
<h3><a name="status"></a>Playing The Game: Status Panels</h3>
There are two status panels on the game screen: left and right.<br><br>
The left panel inclues your current location and play status (In Town, Exploring, Fighting), compass buttons for movement, and the
Travel To list for jumping between towns. At the bottom of the left panel is also a list of game public static functions.<br><br>
The right panel displays some character statistics, your inventory, and quick spells.<br><br>
The Character section shows the most important character statistics. It also displays the status bars for your current hit points,
magic points and travel points. These status bars are colored either green, yellow or red depending on your current amount of each
stat. There is also a link to pop up your list of extended statistics, which shows more detailed character information.<br><br>
The Fast Spells section lists any Heal spells you've learned. You may use these links any time you are in town or exploring to cast
the heal spell. These may not be used during fights, however - you have to use the Spells box on the fight screen for that.
[ <a href="#top">Top</a> ]
<br><br><hr>
<h3><a name="items"></a>Spoilers: Items & Drops</h3>
<a href="/help/items">Click here</a> for the Items & Drops spoiler page.<br><br>
[ <a href="#top">Top</a> ]
<br><br><hr>
<h3><a name="monsters"></a>Spoilers: Monsters</h3>
<a href="/help/monsters">Click here</a> for the Monsters spoiler page.<br><br>
[ <a href="#top">Top</a> ]
<br><br><hr>
<h3><a name="spells"></a>Spoilers: Spells</h3>
<a href="/help/spells">Click here</a> for the Spells spoiler page.<br><br>
[ <a href="#top">Top</a> ]
<br><br><hr>
<h3><a name="levels"></a>Spoilers: Levels</h3>
<a href="/help/levels">Click here</a> for the Levels spoiler page.<br><br>
[ <a href="#top">Top</a> ]
<br><br><hr>
<h3><a name="credits"></a>Credits</h3>
<ul>
<li><b>All program code and stock graphics for the game were created by Jamin Seven</b>.<br><br></li>
<li>Major props go to a few people on the PHP manual site, for help with various chunks of code. The specific people are listed in the source code.<br><br></li>
<li>Super monkey love goes to Enix and the developers of <i>Dragon Warrior</i>. If it weren't for you guys, my game never would have been made.<br><br></li>
<li>Mega props go to Dalez from GameFAQs for his DW3 experience chart, which was where I got my experience levels from.<br><br></li>
<li>
Mad crazy ninja love goes to the following people for help and support throughout the development process:<br><br>
<b>Ideas:</b> (whether they got used or not)
<ul>
<li>kushet</li>
<li>lghtning</li>
<li>Ebolamonkey3000</li>
<li>Crimson Scythe</li>
<li>SilDeath</li>
</ul>
<b>Beta Testing:</b> (forums name if applicable, character name otherwise)
<ul>
<li>Ebolamonkey3000</li>
<li>lisi</li>
<li>Junglist</li>
<li>Crimson Scythe</li>
<li>Sk8erpunk69</li>
<li>lghtning</li>
<li>kushet</li>
<li>SilDeath</li>
<li>lowrider4life</li>
<li>dubiin</li>
<li>Sam Wise The Great</li>
</ul>
</li>
</ul>
Apologies and lots of happy naked love to anyone I forgot. <br><br>
And of course, thanks to <b>you</b> for playing my game! <br><br>
<a href="/ninja">NINJA!</a> <br><br>
[ <a href="#top">Top</a> ]
<br><br><hr><br>
Please visit the following sites for more information:<br>
<a href="http://www.se7enet.com" target="_new">Se7enet</a> (Jamin's homepage)<br>
<a href="http://dragon.se7enet.com/dev.php" target="_new">Dragon Knight</a> (official DK homepage)<br>
<a href="http://se7enet.com/forums" target="_new">Forums</a> (official DK forums)<br><br>
All original coding and graphics for the <i>Dragon Knight</i> game engine are &copy; 2003-2005 by Jamin Seven.<br><br>
[ <a href="#top">Top</a> ]
HTML;
return self::display_help($page);
}
public static function items(): string|false
{
$page = <<<HTML
<table width="60%" style="border: solid 1px black" cellspacing="0" cellpadding="0">
<tr><td colspan="5" bgcolor="#ffffff"><center><b>Items</b></center></td></tr>
<tr><td><b>Type</b></td><td><b>Name</b></td><td><b>Cost</b></td><td><b>Attribute</b></td><td><b>Special</b></td></tr>
HTML;
$items = db()->query('SELECT * FROM items ORDER BY id;');
$item_types = [1 => ['weapon', 'Attack'], 2 => ['armor', 'Defense'], 3 => ['shield', 'Defense']];
while ($item = $items->fetchArray(SQLITE3_ASSOC)) {
$image = $item_types[$item['type']][0];
$power = $item_types[$item['type']][1];
if ($item['special'] !== 'X') {
$special = explode(',', $item['special']);
$attr = special_to_string($special[0]);
$stat = (($special[1] > 0) ? '+' : '').$special[1];
$bigspecial = "$attr $stat";
} else {
$bigspecial = '<span class="light">None</span>';
}
$page .= "<tr><td width=\"5%\"><img src=\"/img/icon_$image.gif\" alt=\"$image\"></td><td width=\"30%\">".$item['name'].'</td><td width="20%">'.$item['buycost'].' Gold</td><td width="20%">'.$item['attribute']." $power Power</td><td width=\"25%\">$bigspecial</td></tr>\n";
}
$page .= <<<HTML
</table>
<br><br>
<table width="60%" style="border: solid 1px black" cellspacing="0" cellpadding="0">
<tr><td colspan="4" bgcolor="#ffffff"><center><b>Drops</b></center></td></tr>
<tr><td><b>Name</b></td><td><b>Monster Level</b></td><td><b>Attribute 1</b></td><td><b>Attribute 2</b></td></tr>
HTML;
$drops = db()->query('SELECT * FROM drops ORDER BY id;');
while ($drop = $drops->fetchArray(SQLITE3_ASSOC)) {
if ($drop['attribute1'] !== 'X') {
$special = explode(',', $drop['attribute1']);
$attr = special_to_string($special[0]);
$stat = (($special[1] > 0) ? '+' : '').$special[1];
$bigspecial1 = "$attr $stat";
} else {
$bigspecial1 = '<span class="light">None</span>';
}
if ($drop['attribute2'] !== 'X') {
$special = explode(',', $drop['attribute2']);
$attr = special_to_string($special[0]);
$stat = (($special[1] > 0) ? '+' : '').$special[1];
$bigspecial2 = "$attr $stat";
} else {
$bigspecial2 = '<span class="light">None</span>';
}
$page .= '<tr><td width="25%">'.$drop['name'].'</td><td width="15%">'.$drop['mlevel']."</td><td width=\"30%\">$bigspecial1</td><td width=\"30%\">$bigspecial2</td></tr>\n";
}
$page .= '</table>';
return self::display_help($page);
}
public static function spells(): string|false
{
$page = <<<HTML
<table width="50%" style="border: solid 1px black" cellspacing="0" cellpadding="0">
<tr><td colspan="8" bgcolor="#ffffff"><center><b>Spells</b></center></td></tr>
<tr><td><b>Name</b></td><td><b>Cost</b></td><td><b>Type</b></td><td><b>Attribute</b></td></tr>
HTML;
$spells = db()->query('SELECT * FROM spells ORDER BY id;');
$spell_types = ['None', 'Heal', 'Hurt', 'Sleep', '+Damage (%)', '+Defense (%)'];
while ($spell = $spells->fetchArray(SQLITE3_ASSOC)) {
$page .= <<<HTML
<tr><td width="25%">{$spell['name']}</td>
<td width="25%">{$spell['mp']}</td>
<td width="25%">{$spell_types[$spell['type']]}</td>
<td width="25%">{$spell['attribute']}</td></tr>
HTML;
}
$page .= <<<HTML
</table>
<ul>
<li><b>Heal</b> spells always give you the maximum amount possible, until your current HP is full.</li>
<li><b>Hurt</b> spells deal X damage (not always the maximum) to the monster, regardless of the monster's armor.</li>
<li><b>Sleep</b> spells put the monster to sleep. The monster has an X in 15 chance of remaining asleep each turn.</li>
<li><b>+Damage</b> spells increase your total attack damage by X percent until the end of the fight.</li>
<li><b>+Defense</b> spells reduce the total damage you take from the monster by X percent until the end of each fight.</li>
</ul>
HTML;
return self::display_help($page);
}
public static function monsters(): string|false
{
$page = <<<HTML
<table width="75%" style="border: solid 1px black" cellspacing="0" cellpadding="0">
<tr><td colspan="8" bgcolor="#ffffff"><center><b>Monsters</b></center></td></tr>
<tr><td><b>Name</b></td><td><b>Max HP</b></td><td><b>Max Damage</b></td><td><b>Armor</b></td><td><b>Level</b></td><td><b>Max Exp.</b></td><td><b>Max Gold</b></td><td><b>Immunity</b></td></tr>
HTML;
$monsters = db()->query('SELECT * FROM monsters ORDER BY id;');
$immunities = ['<span class="light">None</span>', 'Hurt', 'Hurt & Sleep'];
while ($m = $monsters->fetchArray(SQLITE3_ASSOC)) {
$immune = $immunities[$m['immune']] ?? 'Unknown';
$page .= '<tr><td width="30%">'.$m['name'].'</td><td width="10%">'.$m['maxhp'].'</td><td width="10%">'.$m['maxdam'].'</td><td width="10%">'.$m['armor'].'</td><td width="10%">'.$m['level'].'</td><td width="10%">'.$m['maxexp'].'</td><td width="10%">'.$m['maxgold']."</td><td width=\"20%\">$immune</td></tr>\n";
}
return self::display_help($page.'</table>');
}
public static function levels(): string|false
{
$rows = [];
$levels = db()->query('SELECT * FROM levels ORDER BY id;');
while ($level = $levels->fetchArray(SQLITE3_ASSOC)) {
$class_data = [1 => [], 2 => [], 3 => []];
foreach ($level as $column => $value) {
if ($column === 'id') {
continue;
}
$parts = explode('_', $column);
$class_number = (int) $parts[0];
$attribute = $parts[1];
if (in_array($class_number, [1, 2, 3])) {
$class_data[$class_number][$level['id']][$attribute] = $value;
}
}
$rows[$level['id']] = $class_data;
}
$spells = [];
$spells_query = db()->query('SELECT * FROM spells ORDER BY id;');
while ($spell = $spells_query->fetchArray(SQLITE3_ASSOC)) {
$spells[$spell['id']] = $spell;
}
$page = <<<HTML
<table width="50%" style="border: solid 1px black" cellspacing="0" cellpadding="0">
<tr><td colspan="8" bgcolor="#ffffff"><center><b>{{class1name}} Levels</b></center></td></tr>
<tr><td><b>Level</b><td><b>Exp.</b></td><td><b>HP</b></td><td><b>MP</b></td><td><b>TP</b></td><td><b>Strength</b></td><td><b>Dexterity</b></td><td><b>Spell</b></td></tr>
HTML;
foreach ($rows as $level => $class_data) {
$level_data = $class_data[1][$level];
$spell_name = '';
if (! empty($level_data['spells'])) {
$spell_name = $spells[$level_data['spells']]['name'];
}
$page .= '<tr>';
$page .= '<td>'.$level.'</td>';
$page .= '<td>'.($level_data['exp'] ?? '').'</td>';
$page .= '<td>'.($level_data['hp'] ?? '').'</td>';
$page .= '<td>'.($level_data['mp'] ?? '').'</td>';
$page .= '<td>'.($level_data['tp'] ?? '').'</td>';
$page .= '<td>'.($level_data['strength'] ?? '').'</td>';
$page .= '<td>'.($level_data['dexterity'] ?? '').'</td>';
$page .= '<td>'.(! empty($spell_name) ? $spell_name : '<span class="light">None</span>').'</td>';
$page .= '</tr>';
}
$page .= <<<HTML
</table>
<br><br>
<table width="50%" style="border: solid 1px black" cellspacing="0" cellpadding="0">
<tr><td colspan="8" bgcolor="#ffffff"><center><b>{{class2name}} Levels</b></center></td></tr>
<tr><td><b>Level</b><td><b>Exp.</b></td><td><b>HP</b></td><td><b>MP</b></td><td><b>TP</b></td><td><b>Strength</b></td><td><b>Dexterity</b></td><td><b>Spell</b></td></tr>
HTML;
foreach ($rows as $level => $class_data) {
$level_data = $class_data[2][$level];
$spell_name = '';
if (! empty($level_data['spells'])) {
$spell_name = $spells[$level_data['spells']]['name'];
}
$page .= '<tr>';
$page .= '<td>'.$level.'</td>';
$page .= '<td>'.($level_data['exp'] ?? '').'</td>';
$page .= '<td>'.($level_data['hp'] ?? '').'</td>';
$page .= '<td>'.($level_data['mp'] ?? '').'</td>';
$page .= '<td>'.($level_data['tp'] ?? '').'</td>';
$page .= '<td>'.($level_data['strength'] ?? '').'</td>';
$page .= '<td>'.($level_data['dexterity'] ?? '').'</td>';
$page .= '<td>'.(! empty($spell_name) ? $spell_name : '<span class="light">None</span>').'</td>';
$page .= '</tr>';
}
$page .= <<<HTML
</table>
<br><br>
<table width="50%" style="border: solid 1px black" cellspacing="0" cellpadding="0">
<tr><td colspan="8" bgcolor="#ffffff"><center><b>{{class3name}} Levels</b></center></td></tr>
<tr><td><b>Level</b><td><b>Exp.</b></td><td><b>HP</b></td><td><b>MP</b></td><td><b>TP</b></td><td><b>Strength</b></td><td><b>Dexterity</b></td><td><b>Spell</b></td></tr>
HTML;
foreach ($rows as $level => $class_data) {
$level_data = $class_data[3][$level];
$spell_name = '';
if (! empty($level_data['spells'])) {
$spell_name = $spells[$level_data['spells']]['name'];
}
$page .= '<tr>';
$page .= '<td>'.$level.'</td>';
$page .= '<td>'.($level_data['exp'] ?? '').'</td>';
$page .= '<td>'.($level_data['hp'] ?? '').'</td>';
$page .= '<td>'.($level_data['mp'] ?? '').'</td>';
$page .= '<td>'.($level_data['tp'] ?? '').'</td>';
$page .= '<td>'.($level_data['strength'] ?? '').'</td>';
$page .= '<td>'.($level_data['dexterity'] ?? '').'</td>';
$page .= '<td>'.(! empty($spell_name) ? $spell_name : '<span class="light">None</span>').'</td>';
$page .= '</tr>';
}
$page .= <<<HTML
</table>
<br>
Experience points listed are total values up until that point. All other values are just the new amount that you gain for each level.
HTML;
return self::display_help($page);
}
public static function display_help(string $content): string|false
{
return render('layouts/help', [
'content' => $content,
'version' => DragonKnight::VERSION,
'build' => DragonKnight::BUILD,
]);
}
}

View File

@ -0,0 +1,799 @@
<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight\Actions;
use DragonKnight\Router;
use function DragonKnight\db;
use function DragonKnight\ul_from_validate_errors;
use function DragonKnight\validate;
class Install
{
public static function register_routes(Router $r): Router
{
if (! file_exists(getcwd().'/.installed')) {
$r->get('/install', fn() => \DragonKnight\Actions\Install::first());
$r->get('/install/second', fn() => \DragonKnight\Actions\Install::second());
$r->get('/install/third', fn() => \DragonKnight\Actions\Install::third());
$r->post('/install/fourth', fn() => \DragonKnight\Actions\Install::fourth());
$r->get('/install/fifth', fn() => \DragonKnight\Actions\Install::fifth());
}
return $r;
}
/**
* First page - show warnings and gather info.
*/
public static function first(): string
{
return <<<HTML
<html>
<head>
<title>Dragon Knight Installation</title>
</head>
<body>
<b>Dragon Knight Installation: Page One</b><br><br>
Installation for Dragon Knight is a simple two-step process: set up the database tables, then create the admin user. After that, you're done.<br><br>
<a href="/install/second"><button>Install</button></a>
</body>
</html>
HTML;
}
/**
* Set up database tables.
*/
public static function second(): string
{
if (! is_dir($path = getcwd().'/db')) {
if (mkdir($path, 0777, true) === false) {
throw new \Exception('Failed to create database directory at '.$path.'. Please check permissions.');
}
}
if (file_exists($path = getcwd().'/db/database.db')) {
if (unlink($path) === false) {
throw new \Exception('Failed to delete existing database file at '.$path.'. Please check permissions.');
}
}
$page = '<html><head><title>Dragon Knight Installation</title></head><body><b>Dragon Knight Installation: Page Two</b><br><br>';
$query = db()->exec(<<<SQL
CREATE TABLE babble (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`posttime` TEXT NOT NULL DEFAULT '00:00:00',
`author` TEXT NOT NULL DEFAULT '',
`babble` TEXT NOT NULL DEFAULT ''
);
SQL);
$page .= self::table_status_msg($query === true, 'Babble', 'create');
$query = db()->exec(<<<SQL
CREATE TABLE drops (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` TEXT NOT NULL DEFAULT '',
`mlevel` INTEGER NOT NULL DEFAULT 0,
`type` INTEGER NOT NULL DEFAULT 0,
`attribute1` TEXT NOT NULL DEFAULT '',
`attribute2` TEXT NOT NULL DEFAULT ''
);
SQL);
$page .= self::table_status_msg($query === true, 'Drops', 'create');
$query = db()->exec(<<<SQL
INSERT INTO drops VALUES
(1, 'Life Pebble', 1, 1, 'maxhp,10', 'X'),
(2, 'Life Stone', 10, 1, 'maxhp,25', 'X'),
(3, 'Life Rock', 25, 1, 'maxhp,50', 'X'),
(4, 'Magic Pebble', 1, 1, 'maxmp,10', 'X'),
(5, 'Magic Stone', 10, 1, 'maxmp,25', 'X'),
(6, 'Magic Rock', 25, 1, 'maxmp,50', 'X'),
(7, 'Dragon''s Scale', 10, 1, 'defensepower,25', 'X'),
(8, 'Dragon''s Plate', 30, 1, 'defensepower,50', 'X'),
(9, 'Dragon''s Claw', 10, 1, 'attackpower,25', 'X'),
(10, 'Dragon''s Tooth', 30, 1, 'attackpower,50', 'X'),
(11, 'Dragon''s Tear', 35, 1, 'strength,50', 'X'),
(12, 'Dragon''s Wing', 35, 1, 'dexterity,50', 'X'),
(13, 'Demon''s Sin', 35, 1, 'maxhp,-50', 'strength,50'),
(14, 'Demon''s Fall', 35, 1, 'maxmp,-50', 'strength,50'),
(15, 'Demon''s Lie', 45, 1, 'maxhp,-100', 'strength,100'),
(16, 'Demon''s Hate', 45, 1, 'maxmp,-100', 'strength,100'),
(17, 'Angel''s Joy', 25, 1, 'maxhp,25', 'strength,25'),
(18, 'Angel''s Rise', 30, 1, 'maxhp,50', 'strength,50'),
(19, 'Angel''s Truth', 35, 1, 'maxhp,75', 'strength,75'),
(20, 'Angel''s Love', 40, 1, 'maxhp,100', 'strength,100'),
(21, 'Seraph''s Joy', 25, 1, 'maxmp,25', 'dexterity,25'),
(22, 'Seraph''s Rise', 30, 1, 'maxmp,50', 'dexterity,50'),
(23, 'Seraph''s Truth', 35, 1, 'maxmp,75', 'dexterity,75'),
(24, 'Seraph''s Love', 40, 1, 'maxmp,100', 'dexterity,100'),
(25, 'Ruby', 50, 1, 'maxhp,150', 'X'),
(26, 'Pearl', 50, 1, 'maxmp,150', 'X'),
(27, 'Emerald', 50, 1, 'strength,150', 'X'),
(28, 'Topaz', 50, 1, 'dexterity,150', 'X'),
(29, 'Obsidian', 50, 1, 'attackpower,150', 'X'),
(30, 'Diamond', 50, 1, 'defensepower,150', 'X'),
(31, 'Memory Drop', 5, 1, 'expbonus,10', 'X'),
(32, 'Fortune Drop', 5, 1, 'goldbonus,10', 'X');
SQL);
$page .= self::table_status_msg($query === true, 'Drops', 'populate');
$query = db()->exec(<<<SQL
CREATE TABLE forum (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`postdate` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`newpostdate` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`author` TEXT NOT NULL DEFAULT '',
`parent` INTEGER NOT NULL DEFAULT 0,
`replies` INTEGER NOT NULL DEFAULT 0,
`title` TEXT NOT NULL DEFAULT '',
`content` TEXT NOT NULL
);
SQL);
$page .= self::table_status_msg($query === true, 'Forum', 'create');
$query = db()->exec(<<<SQL
CREATE TABLE items (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`type` INTEGER NOT NULL DEFAULT 0,
`name` TEXT NOT NULL DEFAULT '',
`buycost` INTEGER NOT NULL DEFAULT 0,
`attribute` INTEGER NOT NULL DEFAULT 0,
`special` TEXT NOT NULL DEFAULT ''
);
SQL);
$page .= self::table_status_msg($query === true, 'Items', 'create');
$query = db()->exec(<<<SQL
INSERT INTO items VALUES
(1, 1, 'Stick', 10, 2, 'X'),
(2, 1, 'Branch', 30, 4, 'X'),
(3, 1, 'Club', 40, 5, 'X'),
(4, 1, 'Dagger', 90, 8, 'X'),
(5, 1, 'Hatchet', 150, 12, 'X'),
(6, 1, 'Axe', 200, 16, 'X'),
(7, 1, 'Brand', 300, 25, 'X'),
(8, 1, 'Poleaxe', 500, 35, 'X'),
(9, 1, 'Broadsword', 800, 45, 'X'),
(10, 1, 'Battle Axe', 1200, 50, 'X'),
(11, 1, 'Claymore', 2000, 60, 'X'),
(12, 1, 'Dark Axe', 3000, 100, 'expbonus,-5'),
(13, 1, 'Dark Sword', 4500, 125, 'expbonus,-10'),
(14, 1, 'Bright Sword', 6000, 100, 'expbonus,10'),
(15, 1, 'Magic Sword', 10000, 150, 'maxmp,50'),
(16, 1, 'Destiny Blade', 50000, 250, 'strength,50'),
(17, 2, 'Skivvies', 25, 2, 'goldbonus,10'),
(18, 2, 'Clothes', 50, 5, 'X'),
(19, 2, 'Leather Armor', 75, 10, 'X'),
(20, 2, 'Hard Leather Armor', 150, 25, 'X'),
(21, 2, 'Chain Mail', 300, 30, 'X'),
(22, 2, 'Bronze Plate', 900, 50, 'X'),
(23, 2, 'Iron Plate', 2000, 100, 'X'),
(24, 2, 'Magic Armor', 4000, 125, 'maxmp,50'),
(25, 2, 'Dark Armor', 5000, 150, 'expbonus,-10'),
(26, 2, 'Bright Armor', 10000, 175, 'expbonus,10'),
(27, 2, 'Destiny Raiment', 50000, 200, 'dexterity,50'),
(28, 3, 'Reed Shield', 50, 2, 'X'),
(29, 3, 'Buckler', 100, 4, 'X'),
(30, 3, 'Small Shield', 500, 10, 'X'),
(31, 3, 'Large Shield', 2500, 30, 'X'),
(32, 3, 'Silver Shield', 10000, 60, 'X'),
(33, 3, 'Destiny Aegis', 25000, 100, 'maxhp,50');
SQL);
$page .= self::table_status_msg($query === true, 'Drops', 'populate');
$query = db()->exec(<<<SQL
CREATE TABLE classes (
'id' INTEGER PRIMARY KEY AUTOINCREMENT,
'name' TEXT NOT NULL,
'lore' TEXT NOT NULL,
'exp_rate' INTEGER NOT NULL DEFAULT 3,
'base_hp' INTEGER NOT NULL DEFAULT 15,
'base_mp' INTEGER NOT NULL DEFAULT 10,
'base_str' INTEGER NOT NULL DEFAULT 1,
'base_dex' INTEGER NOT NULL DEFAULT 1,
'hp_rate' INTEGER NOT NULL DEFAULT 2,
'mp_rate' INTEGER NOT NULL DEFAULT 2,
'str_rate' INTEGER NOT NULL DEFAULT 2,
'dex_rate' INTEGER NOT NULL DEFAULT 2
);
SQL);
$page .= self::table_status_msg($query === true, 'Classes', 'create');
$query = db()->exec(<<<SQL
INSERT INTO classes VALUES
(0, 'Adventurer', '', 3, 15, 10, 4, 4, 2, 2, 2, 2),
(1, 'Mage', '', 1, 10, 15, 1, 7, 1, 3, 1, 2),
(2, 'Warrior', '', 2, 20, 5, 7, 1, 3, 1, 3, 1),
(3, 'Paladin', '', 5, 15, 15, 5, 5, 2, 2, 2, 2);
SQL);
$page .= self::table_status_msg($query === true, 'Classes', 'populate');
$query = db()->exec(<<<SQL
CREATE TABLE levels (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`1_exp` INTEGER NOT NULL DEFAULT 0,
`1_hp` INTEGER NOT NULL DEFAULT 0,
`1_mp` INTEGER NOT NULL DEFAULT 0,
`1_tp` INTEGER NOT NULL DEFAULT 0,
`1_strength` INTEGER NOT NULL DEFAULT 0,
`1_dexterity` INTEGER NOT NULL DEFAULT 0,
`1_spells` INTEGER NOT NULL DEFAULT 0,
`2_exp` INTEGER NOT NULL DEFAULT 0,
`2_hp` INTEGER NOT NULL DEFAULT 0,
`2_mp` INTEGER NOT NULL DEFAULT 0,
`2_tp` INTEGER NOT NULL DEFAULT 0,
`2_strength` INTEGER NOT NULL DEFAULT 0,
`2_dexterity` INTEGER NOT NULL DEFAULT 0,
`2_spells` INTEGER NOT NULL DEFAULT 0,
`3_exp` INTEGER NOT NULL DEFAULT 0,
`3_hp` INTEGER NOT NULL DEFAULT 0,
`3_mp` INTEGER NOT NULL DEFAULT 0,
`3_tp` INTEGER NOT NULL DEFAULT 0,
`3_strength` INTEGER NOT NULL DEFAULT 0,
`3_dexterity` INTEGER NOT NULL DEFAULT 0,
`3_spells` INTEGER NOT NULL DEFAULT 0
);
SQL);
$page .= self::table_status_msg($query === true, 'Levels', 'create');
$query = db()->exec(<<<SQL
INSERT INTO levels VALUES
(1, 0, 15, 0, 5, 5, 5, 0, 0, 15, 0, 5, 5, 5, 0, 0, 15, 0, 5, 5, 5, 0),
(2, 15, 2, 5, 1, 0, 1, 1, 18, 2, 4, 1, 2, 1, 1, 20, 2, 5, 1, 0, 2, 1),
(3, 45, 3, 4, 2, 1, 2, 0, 54, 2, 3, 2, 3, 2, 0, 60, 2, 3, 2, 1, 3, 0),
(4, 105, 3, 3, 2, 1, 2, 6, 126, 2, 3, 2, 3, 2, 0, 140, 2, 4, 2, 1, 3, 0),
(5, 195, 2, 5, 2, 0, 1, 0, 234, 2, 4, 2, 2, 1, 6, 260, 2, 4, 2, 0, 2, 6),
(6, 330, 4, 5, 2, 2, 3, 0, 396, 3, 4, 2, 4, 3, 0, 440, 3, 5, 2, 2, 4, 0),
(7, 532, 3, 4, 2, 1, 2, 11, 639, 2, 3, 2, 3, 2, 0, 710, 2, 3, 2, 1, 3, 0),
(8, 835, 2, 4, 2, 0, 1, 0, 1003, 2, 3, 2, 2, 1, 11, 1115, 2, 4, 2, 0, 2, 11),
(9, 1290, 5, 3, 2, 3, 4, 2, 1549, 4, 2, 2, 5, 4, 0, 1722, 4, 2, 2, 3, 5, 0),
(10, 1973, 10, 3, 2, 4, 3, 0, 2369, 10, 2, 2, 6, 3, 0, 2633, 10, 3, 2, 4, 4, 0),
(11, 2997, 5, 2, 2, 3, 4, 0, 3598, 4, 1, 2, 5, 4, 2, 3999, 4, 1, 2, 3, 5, 2),
(12, 4533, 4, 2, 2, 2, 3, 7, 5441, 4, 1, 2, 4, 3, 0, 6047, 4, 2, 2, 2, 4, 0),
(13, 6453, 4, 3, 2, 2, 3, 0, 7745, 4, 2, 2, 4, 3, 0, 8607, 4, 2, 2, 2, 4, 0),
(14, 8853, 5, 4, 2, 3, 4, 17, 10625, 4, 3, 2, 5, 4, 7, 11807, 4, 4, 2, 3, 5, 7),
(15, 11853, 5, 5, 2, 3, 4, 0, 14225, 4, 4, 2, 5, 4, 0, 15808, 4, 4, 2, 3, 5, 0),
(16, 15603, 5, 3, 2, 3, 4, 0, 18725, 5, 2, 2, 5, 4, 0, 20807, 5, 3, 2, 3, 5, 0),
(17, 20290, 4, 2, 2, 2, 3, 12, 24350, 4, 1, 2, 4, 3, 0, 27057, 4, 1, 2, 2, 4, 0),
(18, 25563, 4, 2, 2, 2, 3, 0, 30678, 3, 1, 2, 4, 3, 14, 34869, 3, 2, 2, 2, 4, 17),
(19, 31495, 4, 5, 2, 2, 3, 0, 37797, 3, 4, 2, 4, 3, 0, 43657, 3, 4, 2, 2, 4, 0),
(20, 38169, 10, 6, 2, 3, 3, 0, 45805, 10, 5, 2, 5, 3, 0, 53543, 10, 6, 2, 3, 4, 0),
(21, 45676, 4, 4, 2, 2, 3, 0, 54814, 4, 3, 2, 4, 3, 0, 64664, 4, 3, 2, 2, 4, 0),
(22, 54121, 5, 5, 2, 3, 4, 0, 64949, 4, 4, 2, 5, 4, 12, 77175, 4, 5, 2, 3, 5, 12),
(23, 63622, 5, 3, 2, 3, 4, 0, 76350, 4, 2, 2, 5, 4, 0, 91250, 4, 2, 2, 3, 5, 0),
(24, 74310, 5, 5, 2, 3, 4, 0, 89176, 4, 4, 2, 5, 4, 0, 107083, 4, 5, 2, 3, 5, 0),
(25, 86334, 4, 4, 2, 2, 3, 3, 103605, 3, 3, 2, 4, 3, 17, 124895, 3, 3, 2, 2, 4, 14),
(26, 99861, 6, 3, 2, 4, 5, 0, 119837, 5, 2, 2, 6, 5, 0, 144933, 5, 3, 2, 4, 6, 0),
(27, 115078, 6, 2, 2, 4, 5, 0, 138098, 5, 1, 2, 6, 5, 0, 167475, 5, 1, 2, 4, 6, 0),
(28, 132197, 4, 2, 2, 2, 3, 0, 158641, 4, 1, 2, 4, 3, 0, 192835, 4, 2, 2, 2, 4, 0),
(29, 151456, 6, 3, 2, 4, 5, 0, 181751, 5, 2, 2, 6, 5, 3, 221365, 5, 2, 2, 4, 6, 3),
(30, 173121, 10, 4, 3, 4, 4, 0, 207749, 10, 3, 3, 6, 4, 0, 253461, 10, 4, 3, 4, 5, 0),
(31, 197494, 5, 5, 3, 3, 4, 8, 236996, 4, 3, 3, 5, 4, 0, 289568, 4, 3, 3, 3, 5, 0),
(32, 224913, 6, 4, 3, 4, 5, 0, 269898, 5, 3, 3, 6, 5, 0, 330188, 5, 4, 3, 4, 6, 0),
(33, 255758, 5, 4, 3, 3, 4, 0, 306912, 5, 3, 3, 5, 4, 0, 375885, 5, 3, 3, 3, 5, 0),
(34, 290458, 6, 4, 3, 4, 5, 0, 348552, 5, 3, 3, 6, 5, 8, 427294, 5, 4, 3, 4, 6, 8),
(35, 329495, 5, 3, 3, 3, 4, 0, 395397, 4, 2, 3, 5, 4, 0, 485126, 4, 2, 3, 3, 5, 0),
(36, 373412, 4, 3, 3, 2, 3, 18, 448097, 5, 2, 3, 4, 3, 0, 550188, 5, 3, 3, 2, 4, 0),
(37, 422818, 5, 4, 3, 3, 4, 0, 507384, 5, 3, 3, 5, 4, 0, 623383, 5, 3, 3, 3, 5, 0),
(38, 478399, 6, 5, 3, 4, 5, 0, 574081, 5, 4, 3, 6, 5, 15, 705726, 5, 5, 3, 4, 6, 18),
(39, 540927, 6, 4, 3, 4, 5, 0, 649115, 5, 3, 3, 6, 5, 0, 798362, 5, 3, 3, 4, 6, 0),
(40, 611271, 15, 3, 3, 5, 5, 13, 733528, 15, 2, 3, 7, 5, 0, 902577, 15, 3, 3, 5, 6, 0),
(41, 690408, 7, 3, 3, 5, 2, 0, 828492, 6, 2, 3, 7, 2, 0, 1019818, 6, 2, 3, 5, 3, 0),
(42, 779437, 7, 4, 3, 5, 6, 0, 935326, 6, 3, 3, 7, 6, 0, 1151714, 6, 4, 3, 5, 7, 0),
(43, 879592, 8, 5, 3, 6, 7, 0, 1055514, 7, 4, 3, 8, 7, 0, 1300096, 7, 4, 3, 6, 8, 0),
(44, 992268, 6, 3, 3, 4, 5, 0, 1190725, 5, 2, 3, 6, 5, 0, 1448478, 5, 3, 3, 4, 6, 0),
(45, 1119028, 5, 8, 3, 3, 4, 4, 1325936, 5, 8, 3, 5, 4, 18, 1596860, 5, 8, 3, 3, 5, 4),
(46, 1245788, 6, 5, 3, 4, 5, 0, 1461147, 5, 4, 3, 6, 5, 0, 1745242, 5, 5, 3, 4, 6, 0),
(47, 1372548, 7, 4, 3, 5, 6, 0, 1596358, 6, 3, 3, 7, 6, 0, 1893624, 6, 3, 3, 5, 7, 0),
(48, 1499308, 6, 4, 3, 4, 5, 0, 1731569, 5, 3, 3, 6, 5, 0, 2042006, 5, 4, 3, 4, 6, 0),
(49, 1626068, 5, 3, 3, 3, 4, 0, 1866780, 4, 2, 3, 5, 4, 0, 2190388, 4, 2, 3, 3, 5, 0),
(50, 1752828, 15, 3, 3, 5, 5, 0, 2001991, 15, 2, 3, 7, 5, 0, 2338770, 15, 3, 3, 5, 6, 0),
(51, 1879588, 6, 2, 3, 4, 5, 9, 2137202, 5, 1, 3, 6, 5, 13, 2487152, 5, 1, 3, 4, 6, 13),
(52, 2006348, 7, 2, 3, 5, 6, 0, 2272413, 6, 1, 3, 7, 6, 0, 2635534, 6, 2, 3, 5, 7, 0),
(53, 2133108, 8, 2, 3, 6, 7, 0, 2407624, 7, 1, 3, 8, 7, 0, 2783916, 7, 1, 3, 6, 8, 0),
(54, 2259868, 8, 4, 3, 6, 7, 0, 2542835, 7, 3, 3, 8, 7, 0, 2932298, 7, 4, 3, 6, 8, 0),
(55, 2386628, 7, 4, 3, 5, 6, 0, 2678046, 6, 3, 3, 7, 6, 0, 3080680, 6, 3, 3, 5, 7, 0),
(56, 2513388, 7, 4, 3, 5, 6, 0, 2813257, 6, 3, 3, 7, 6, 0, 3229062, 6, 4, 3, 5, 7, 9),
(57, 2640148, 6, 5, 3, 4, 5, 0, 2948468, 6, 4, 3, 6, 5, 0, 3377444, 6, 4, 3, 4, 6, 0),
(58, 2766908, 5, 5, 3, 3, 4, 0, 3083679, 5, 4, 3, 5, 4, 19, 3525826, 5, 5, 3, 3, 5, 0),
(59, 2893668, 8, 3, 3, 6, 7, 0, 3218890, 7, 2, 3, 8, 7, 0, 3674208, 7, 2, 3, 6, 8, 0),
(60, 3020428, 15, 4, 4, 6, 6, 19, 3354101, 15, 3, 4, 8, 6, 0, 3822590, 15, 4, 4, 6, 7, 15),
(61, 3147188, 8, 5, 4, 6, 7, 0, 3489312, 7, 4, 4, 8, 7, 0, 3970972, 7, 4, 4, 6, 8, 0),
(62, 3273948, 8, 4, 4, 6, 7, 0, 3624523, 7, 3, 4, 8, 7, 0, 4119354, 7, 4, 4, 6, 8, 0),
(63, 3400708, 9, 5, 4, 7, 8, 0, 3759734, 8, 4, 4, 9, 8, 0, 4267736, 8, 4, 4, 7, 9, 0),
(64, 3527468, 5, 5, 4, 3, 4, 0, 3894945, 5, 4, 4, 5, 4, 0, 4416118, 5, 5, 4, 3, 5, 0),
(65, 3654228, 6, 4, 4, 4, 5, 0, 4030156, 6, 3, 4, 6, 5, 0, 4564500, 6, 3, 4, 4, 6, 0),
(66, 3780988, 8, 4, 4, 6, 7, 0, 4165367, 8, 3, 4, 8, 7, 0, 4712882, 8, 4, 4, 6, 8, 0),
(67, 3907748, 7, 3, 4, 5, 6, 0, 4300578, 7, 2, 4, 7, 6, 0, 4861264, 7, 2, 4, 5, 7, 0),
(68, 4034508, 9, 3, 4, 7, 8, 0, 4435789, 8, 2, 4, 9, 8, 0, 5009646, 8, 3, 4, 7, 9, 0),
(69, 4161268, 5, 4, 4, 3, 4, 0, 4571000, 5, 3, 4, 5, 4, 0, 5158028, 5, 3, 4, 3, 5, 0),
(70, 4288028, 20, 4, 4, 6, 6, 5, 4706211, 20, 3, 4, 8, 6, 16, 5306410, 20, 4, 4, 6, 7, 0),
(71, 4414788, 5, 5, 4, 3, 4, 0, 4841422, 5, 4, 4, 5, 4, 0, 5454792, 5, 4, 4, 3, 5, 0),
(72, 4541548, 6, 2, 4, 4, 5, 0, 4976633, 5, 1, 4, 6, 5, 0, 5603174, 5, 2, 4, 4, 6, 0),
(73, 4668308, 8, 4, 4, 6, 7, 0, 5111844, 8, 3, 4, 8, 7, 0, 5751556, 8, 3, 4, 6, 8, 0),
(74, 4795068, 7, 5, 4, 5, 6, 0, 5247055, 6, 4, 4, 7, 6, 0, 5899938, 6, 5, 4, 5, 7, 0),
(75, 4921828, 5, 3, 4, 3, 4, 0, 5382266, 5, 2, 4, 5, 4, 0, 6048320, 5, 2, 4, 3, 5, 0),
(76, 5048588, 6, 3, 4, 4, 5, 0, 5517477, 6, 2, 4, 6, 5, 0, 6196702, 6, 3, 4, 4, 6, 0),
(77, 5175348, 6, 4, 4, 4, 5, 0, 5652688, 7, 3, 4, 6, 5, 0, 6345084, 7, 3, 4, 4, 6, 0),
(78, 5302108, 7, 4, 4, 5, 6, 0, 5787899, 7, 3, 4, 7, 6, 0, 6493466, 7, 4, 4, 5, 7, 0),
(79, 5428868, 8, 4, 4, 6, 7, 10, 5923110, 7, 3, 4, 8, 7, 0, 6641848, 7, 3, 4, 6, 8, 0),
(80, 5555628, 20, 5, 4, 6, 7, 0, 6058321, 20, 4, 4, 8, 7, 0, 6790230, 20, 5, 4, 6, 8, 0),
(81, 5682388, 7, 3, 4, 5, 6, 0, 6193532, 7, 2, 4, 7, 6, 0, 6938612, 7, 2, 4, 5, 7, 0),
(82, 5809148, 6, 4, 4, 4, 5, 0, 6328743, 5, 3, 4, 6, 5, 0, 7086994, 5, 4, 4, 4, 6, 0),
(83, 5935908, 6, 2, 4, 4, 5, 0, 6463954, 6, 1, 4, 6, 5, 0, 7235376, 6, 1, 4, 4, 6, 0),
(84, 6062668, 5, 4, 4, 3, 4, 0, 6599165, 5, 3, 4, 5, 4, 0, 7383758, 5, 4, 4, 3, 5, 0),
(85, 6189428, 7, 4, 4, 5, 6, 0, 6734376, 6, 3, 4, 7, 6, 0, 7532140, 6, 3, 4, 5, 7, 0),
(86, 6316188, 8, 5, 4, 6, 7, 0, 6869587, 8, 4, 4, 8, 7, 0, 7680522, 8, 5, 4, 6, 8, 0),
(87, 6442948, 8, 4, 4, 6, 7, 0, 7004798, 7, 3, 4, 8, 7, 0, 7828904, 7, 3, 4, 6, 8, 0),
(88, 6569708, 9, 5, 4, 7, 8, 0, 7140009, 8, 4, 4, 9, 8, 0, 7977286, 8, 5, 4, 7, 9, 0),
(89, 6696468, 5, 2, 4, 3, 4, 0, 7275220, 5, 1, 4, 5, 4, 0, 8125668, 5, 1, 4, 3, 5, 0),
(90, 6823228, 20, 2, 5, 7, 8, 0, 7410431, 20, 1, 5, 9, 8, 0, 8274050, 20, 2, 5, 7, 9, 0),
(91, 6949988, 5, 3, 5, 3, 4, 0, 7545642, 5, 2, 5, 5, 4, 0, 8422432, 5, 2, 5, 3, 5, 0),
(92, 7076748, 6, 3, 5, 4, 5, 0, 7680853, 4, 2, 5, 6, 5, 0, 8570814, 4, 3, 5, 4, 6, 0),
(93, 7203508, 8, 4, 5, 6, 7, 0, 7816064, 6, 2, 5, 8, 7, 0, 8719196, 6, 2, 5, 6, 8, 0),
(94, 7330268, 4, 4, 5, 3, 3, 0, 7951275, 4, 3, 5, 5, 3, 0, 8867578, 4, 4, 5, 3, 4, 0),
(95, 7457028, 3, 3, 5, 5, 2, 0, 8086486, 4, 2, 5, 7, 2, 0, 9015960, 4, 2, 5, 5, 3, 0),
(96, 7583788, 5, 3, 5, 4, 3, 0, 8221697, 5, 2, 5, 7, 3, 0, 9164342, 5, 3, 5, 4, 4, 0),
(97, 7710548, 5, 4, 5, 4, 5, 0, 8356908, 5, 3, 5, 7, 5, 0, 9312724, 5, 3, 5, 4, 6, 0),
(98, 7837308, 4, 5, 5, 4, 3, 0, 8492119, 4, 3, 5, 7, 3, 0, 9461106, 4, 4, 5, 4, 4, 0),
(99, 7964068, 50, 5, 5, 6, 5, 0, 8627330, 50, 3, 5, 9, 5, 0, 9609488, 50, 4, 5, 6, 6, 0),
(100, 16777215, 0, 0, 0, 0, 0, 0, 16777215, 0, 0, 0, 0, 0, 0, 16777215, 0, 0, 0, 0, 0, 0);
SQL);
$page .= self::table_status_msg($query === true, 'Levels', 'populate');
$query = db()->exec(<<<SQL
CREATE TABLE monsters (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` TEXT NOT NULL DEFAULT '',
`maxhp` INTEGER NOT NULL DEFAULT 0,
`maxdam` INTEGER NOT NULL DEFAULT 0,
`armor` INTEGER NOT NULL DEFAULT 0,
`level` INTEGER NOT NULL DEFAULT 0,
`maxexp` INTEGER NOT NULL DEFAULT 0,
`maxgold` INTEGER NOT NULL DEFAULT 0,
`immune` INTEGER NOT NULL DEFAULT 0
);
SQL);
$page .= self::table_status_msg($query === true, 'Monsters', 'create');
$query = db()->exec(<<<SQL
INSERT INTO monsters VALUES
(1, 'Blue Slime', 4, 3, 1, 1, 1, 1, 0),
(2, 'Red Slime', 6, 5, 1, 1, 2, 1, 0),
(3, 'Critter', 6, 5, 2, 1, 4, 2, 0),
(4, 'Creature', 10, 8, 2, 2, 4, 2, 0),
(5, 'Shadow', 10, 9, 3, 2, 6, 2, 1),
(6, 'Drake', 11, 10, 3, 2, 8, 3, 0),
(7, 'Shade', 12, 10, 3, 3, 10, 3, 1),
(8, 'Drakelor', 14, 12, 4, 3, 10, 3, 0),
(9, 'Silver Slime', 15, 100, 200, 30, 15, 1000, 2),
(10, 'Scamp', 16, 13, 5, 4, 15, 5, 0),
(11, 'Raven', 16, 13, 5, 4, 18, 6, 0),
(12, 'Scorpion', 18, 14, 6, 5, 20, 7, 0),
(13, 'Illusion', 20, 15, 6, 5, 20, 7, 1),
(14, 'Nightshade', 22, 16, 6, 6, 24, 8, 0),
(15, 'Drakemal', 22, 18, 7, 6, 24, 8, 0),
(16, 'Shadow Raven', 24, 18, 7, 6, 26, 9, 1),
(17, 'Ghost', 24, 20, 8, 6, 28, 9, 0),
(18, 'Frost Raven', 26, 20, 8, 7, 30, 10, 0),
(19, 'Rogue Scorpion', 28, 22, 9, 7, 32, 11, 0),
(20, 'Ghoul', 29, 24, 9, 7, 34, 11, 0),
(21, 'Magician', 30, 24, 10, 8, 36, 12, 0),
(22, 'Rogue', 30, 25, 12, 8, 40, 13, 0),
(23, 'Drakefin', 32, 26, 12, 8, 40, 13, 0),
(24, 'Shimmer', 32, 26, 14, 8, 45, 15, 1),
(25, 'Fire Raven', 34, 28, 14, 9, 45, 15, 0),
(26, 'Dybbuk', 34, 28, 14, 9, 50, 17, 0),
(27, 'Knave', 36, 30, 15, 9, 52, 17, 0),
(28, 'Goblin', 36, 30, 15, 10, 54, 18, 0),
(29, 'Skeleton', 38, 30, 18, 10, 58, 19, 0),
(30, 'Dark Slime', 38, 32, 18, 10, 62, 21, 0),
(31, 'Silver Scorpion', 30, 160, 350, 40, 63, 2000, 2),
(32, 'Mirage', 40, 32, 20, 11, 64, 21, 1),
(33, 'Sorceror', 41, 33, 22, 11, 68, 23, 0),
(34, 'Imp', 42, 34, 22, 12, 70, 23, 0),
(35, 'Nymph', 43, 35, 22, 12, 70, 23, 0),
(36, 'Scoundrel', 43, 35, 22, 12, 75, 25, 0),
(37, 'Megaskeleton', 44, 36, 24, 13, 78, 26, 0),
(38, 'Grey Wolf', 44, 36, 24, 13, 82, 27, 0),
(39, 'Phantom', 46, 38, 24, 14, 85, 28, 1),
(40, 'Specter', 46, 38, 24, 14, 90, 30, 0),
(41, 'Dark Scorpion', 48, 40, 26, 15, 95, 32, 1),
(42, 'Warlock', 48, 40, 26, 15, 100, 33, 1),
(43, 'Orc', 49, 42, 28, 15, 104, 35, 0),
(44, 'Sylph', 49, 42, 28, 15, 106, 35, 0),
(45, 'Wraith', 50, 45, 30, 16, 108, 36, 0),
(46, 'Hellion', 50, 45, 30, 16, 110, 37, 0),
(47, 'Bandit', 52, 45, 30, 16, 114, 38, 0),
(48, 'Ultraskeleton', 52, 46, 32, 16, 116, 39, 0),
(49, 'Dark Wolf', 54, 47, 36, 17, 120, 40, 1),
(50, 'Troll', 56, 48, 36, 17, 120, 40, 0),
(51, 'Werewolf', 56, 48, 38, 17, 124, 41, 0),
(52, 'Hellcat', 58, 50, 38, 18, 128, 43, 0),
(53, 'Spirit', 58, 50, 38, 18, 132, 44, 0),
(54, 'Nisse', 60, 52, 40, 19, 132, 44, 0),
(55, 'Dawk', 60, 54, 40, 19, 136, 45, 0),
(56, 'Figment', 64, 55, 42, 19, 140, 47, 1),
(57, 'Hellhound', 66, 56, 44, 20, 140, 47, 0),
(58, 'Wizard', 66, 56, 44, 20, 144, 48, 0),
(59, 'Uruk', 68, 58, 44, 20, 146, 49, 0),
(60, 'Siren', 68, 400, 800, 50, 10000, 50, 2),
(61, 'Megawraith', 70, 60, 46, 21, 155, 52, 0),
(62, 'Dawkin', 70, 60, 46, 21, 155, 52, 0),
(63, 'Grey Bear', 70, 62, 48, 21, 160, 53, 0),
(64, 'Haunt', 72, 62, 48, 22, 160, 53, 0),
(65, 'Hellbeast', 74, 64, 50, 22, 165, 55, 0),
(66, 'Fear', 76, 66, 52, 23, 165, 55, 0),
(67, 'Beast', 76, 66, 52, 23, 170, 57, 0),
(68, 'Ogre', 78, 68, 54, 23, 170, 57, 0),
(69, 'Dark Bear', 80, 70, 56, 24, 175, 58, 1),
(70, 'Fire', 80, 72, 56, 24, 175, 58, 0),
(71, 'Polgergeist', 84, 74, 58, 25, 180, 60, 0),
(72, 'Fright', 86, 76, 58, 25, 180, 60, 0),
(73, 'Lycan', 88, 78, 60, 25, 185, 62, 0),
(74, 'Terra Elemental', 88, 80, 62, 25, 185, 62, 1),
(75, 'Necromancer', 90, 80, 62, 26, 190, 63, 0),
(76, 'Ultrawraith', 90, 82, 64, 26, 190, 63, 0),
(77, 'Dawkor', 92, 82, 64, 26, 195, 65, 0),
(78, 'Werebear', 92, 84, 65, 26, 195, 65, 0),
(79, 'Brute', 94, 84, 65, 27, 200, 67, 0),
(80, 'Large Beast', 96, 88, 66, 27, 200, 67, 0),
(81, 'Horror', 96, 88, 68, 27, 210, 70, 0),
(82, 'Flame', 100, 90, 70, 28, 210, 70, 0),
(83, 'Lycanthor', 100, 90, 70, 28, 210, 70, 0),
(84, 'Wyrm', 100, 92, 72, 28, 220, 73, 0),
(85, 'Aero Elemental', 104, 94, 74, 29, 220, 73, 1),
(86, 'Dawkare', 106, 96, 76, 29, 220, 73, 0),
(87, 'Large Brute', 108, 98, 78, 29, 230, 77, 0),
(88, 'Frost Wyrm', 110, 100, 80, 30, 230, 77, 0),
(89, 'Knight', 110, 102, 80, 30, 240, 80, 0),
(90, 'Lycanthra', 112, 104, 82, 30, 240, 80, 0),
(91, 'Terror', 115, 108, 84, 31, 250, 83, 0),
(92, 'Blaze', 118, 108, 84, 31, 250, 83, 0),
(93, 'Aqua Elemental', 120, 110, 90, 31, 260, 87, 1),
(94, 'Fire Wyrm', 120, 110, 90, 32, 260, 87, 0),
(95, 'Lesser Wyvern', 122, 110, 92, 32, 270, 90, 0),
(96, 'Doomer', 124, 112, 92, 32, 270, 90, 0),
(97, 'Armor Knight', 130, 115, 95, 33, 280, 93, 0),
(98, 'Wyvern', 134, 120, 95, 33, 290, 97, 0),
(99, 'Nightmare', 138, 125, 100, 33, 300, 100, 0),
(100, 'Fira Elemental', 140, 125, 100, 34, 310, 103, 1),
(101, 'Megadoomer', 140, 128, 105, 34, 320, 107, 0),
(102, 'Greater Wyvern', 145, 130, 105, 34, 335, 112, 0),
(103, 'Advocate', 148, 132, 108, 35, 350, 117, 0),
(104, 'Strong Knight', 150, 135, 110, 35, 365, 122, 0),
(105, 'Liche', 150, 135, 110, 35, 380, 127, 0),
(106, 'Ultradoomer', 155, 140, 115, 36, 395, 132, 0),
(107, 'Fanatic', 160, 140, 115, 36, 410, 137, 0),
(108, 'Green Dragon', 160, 140, 115, 36, 425, 142, 0),
(109, 'Fiend', 160, 145, 120, 37, 445, 148, 0),
(110, 'Greatest Wyvern', 162, 150, 120, 37, 465, 155, 0),
(111, 'Lesser Devil', 164, 150, 120, 37, 485, 162, 0),
(112, 'Liche Master', 168, 155, 125, 38, 505, 168, 0),
(113, 'Zealot', 168, 155, 125, 38, 530, 177, 0),
(114, 'Serafiend', 170, 155, 125, 38, 555, 185, 0),
(115, 'Pale Knight', 175, 160, 130, 39, 580, 193, 0),
(116, 'Blue Dragon', 180, 160, 130, 39, 605, 202, 0),
(117, 'Obsessive', 180, 160, 135, 40, 630, 210, 0),
(118, 'Devil', 184, 164, 135, 40, 666, 222, 0),
(119, 'Liche Prince', 190, 168, 138, 40, 660, 220, 0),
(120, 'Cherufiend', 195, 170, 140, 41, 690, 230, 0),
(121, 'Red Dragon', 200, 180, 145, 41, 720, 240, 0),
(122, 'Greater Devil', 200, 180, 145, 41, 750, 250, 0),
(123, 'Renegade', 205, 185, 150, 42, 780, 260, 0),
(124, 'Archfiend', 210, 190, 150, 42, 810, 270, 0),
(125, 'Liche Lord', 210, 190, 155, 42, 850, 283, 0),
(126, 'Greatest Devil', 215, 195, 160, 43, 890, 297, 0),
(127, 'Dark Knight', 220, 200, 160, 43, 930, 310, 0),
(128, 'Giant', 220, 200, 165, 43, 970, 323, 0),
(129, 'Shadow Dragon', 225, 200, 170, 44, 1010, 337, 0),
(130, 'Liche King', 225, 205, 170, 44, 1050, 350, 0),
(131, 'Incubus', 230, 205, 175, 44, 1100, 367, 1),
(132, 'Traitor', 230, 205, 175, 45, 1150, 383, 0),
(133, 'Demon', 240, 210, 180, 45, 1200, 400, 0),
(134, 'Dark Dragon', 245, 215, 180, 45, 1250, 417, 1),
(135, 'Insurgent', 250, 220, 190, 46, 1300, 433, 0),
(136, 'Leviathan', 255, 225, 190, 46, 1350, 450, 0),
(137, 'Grey Daemon', 260, 230, 190, 46, 1400, 467, 0),
(138, 'Succubus', 265, 240, 200, 47, 1460, 487, 1),
(139, 'Demon Prince', 270, 240, 200, 47, 1520, 507, 0),
(140, 'Black Dragon', 275, 250, 205, 47, 1580, 527, 1),
(141, 'Nihilist', 280, 250, 205, 47, 1640, 547, 0),
(142, 'Behemoth', 285, 260, 210, 48, 1700, 567, 0),
(143, 'Demagogue', 290, 260, 210, 48, 1760, 587, 0),
(144, 'Demon Lord', 300, 270, 220, 48, 1820, 607, 0),
(145, 'Red Daemon', 310, 280, 230, 48, 1880, 627, 0),
(146, 'Colossus', 320, 300, 240, 49, 1940, 647, 0),
(147, 'Demon King', 330, 300, 250, 49, 2000, 667, 0),
(148, 'Dark Daemon', 340, 320, 260, 49, 2200, 733, 1),
(149, 'Titan', 360, 340, 270, 50, 2400, 800, 0),
(150, 'Black Daemon', 400, 400, 280, 50, 3000, 1000, 1),
(151, 'Lucifuge', 600, 600, 400, 50, 10000, 10000, 2);
SQL);
$page .= self::table_status_msg($query === true, 'Monsters', 'populate');
$query = db()->exec(<<<SQL
CREATE TABLE news (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`author` TEXT NOT NULL DEFAULT 'Guild Master',
`postdate` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`content` TEXT NOT NULL
);
SQL);
$page .= self::table_status_msg($query === true, 'News', 'create');
$query = db()->exec("INSERT INTO news (content) VALUES ('This is the first news post. Please use the admin control panel to add another one and make this one go away.');");
$page .= self::table_status_msg($query === true, 'News', 'populate');
$query = db()->exec(<<<SQL
CREATE TABLE spells (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` TEXT NOT NULL,
`mp` INTEGER NOT NULL DEFAULT 0,
`attribute` INTEGER NOT NULL DEFAULT 0,
`type` INTEGER NOT NULL DEFAULT 0
);
SQL);
$page .= self::table_status_msg($query === true, 'Spells', 'create');
$query = db()->exec(<<<SQL
INSERT INTO spells VALUES
(1, 'Heal', 5, 10, 1),
(2, 'Revive', 10, 25, 1),
(3, 'Life', 25, 50, 1),
(4, 'Breath', 50, 100, 1),
(5, 'Gaia', 75, 150, 1),
(6, 'Hurt', 5, 15, 2),
(7, 'Pain', 12, 35, 2),
(8, 'Maim', 25, 70, 2),
(9, 'Rend', 40, 100, 2),
(10, 'Chaos', 50, 130, 2),
(11, 'Sleep', 10, 5, 3),
(12, 'Dream', 30, 9, 3),
(13, 'Nightmare', 60, 13, 3),
(14, 'Craze', 10, 10, 4),
(15, 'Rage', 20, 25, 4),
(16, 'Fury', 30, 50, 4),
(17, 'Ward', 10, 10, 5),
(18, 'Fend', 20, 25, 5),
(19, 'Barrier', 30, 50, 5);
SQL);
$page .= self::table_status_msg($query === true, 'Spells', 'populate');
$query = db()->exec(<<<SQL
CREATE TABLE towns (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` TEXT NOT NULL,
`latitude` INTEGER NOT NULL DEFAULT 0,
`longitude` INTEGER NOT NULL DEFAULT 0,
`innprice` INTEGER NOT NULL DEFAULT 0,
`mapprice` INTEGER NOT NULL DEFAULT 0,
`travelpoints` INTEGER NOT NULL DEFAULT 0,
`itemslist` TEXT NOT NULL
);
SQL);
$page .= self::table_status_msg($query === true, 'Towns', 'create');
$query = db()->exec(<<<SQL
INSERT INTO towns VALUES
(1, 'Midworld', 0, 0, 5, 0, 0, '1,2,3,17,18,19,28,29'),
(2, 'Roma', 30, 30, 10, 25, 5, '2,3,4,18,19,29'),
(3, 'Bris', 70, -70, 25, 50, 15, '2,3,4,5,18,19,20,29.30'),
(4, 'Kalle', -100, 100, 40, 100, 30, '5,6,8,10,12,21,22,23,29,30'),
(5, 'Narcissa', -130, -130, 60, 500, 50, '4,7,9,11,13,21,22,23,29,30,31'),
(6, 'Hambry', 170, 170, 90, 1000, 80, '10,11,12,13,14,23,24,30,31'),
(7, 'Gilead', 200, -200, 100, 3000, 110, '12,13,14,15,24,25,26,32'),
(8, 'Endworld', -250, -250, 125, 9000, 160, '16,27,33');
SQL);
$page .= self::table_status_msg($query === true, 'Towns', 'populate');
$query = db()->exec(<<<SQL
CREATE TABLE users (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`username` TEXT NOT NULL,
`password` TEXT NOT NULL,
`email` TEXT NOT NULL,
`verify` TEXT NOT NULL default '',
`regdate` datetime NOT NULL default CURRENT_TIMESTAMP,
`onlinetime` datetime NOT NULL default CURRENT_TIMESTAMP,
`authlevel` INTEGER NOT NULL default 0,
`latitude` INTEGER NOT NULL default 0,
`longitude` INTEGER NOT NULL default 0,
`charclass` INTEGER NOT NULL default 0,
'class_id' INTEGER NOT NULL DEFAULT 1,
`currentaction` TEXT NOT NULL default 'In Town',
`currentfight` INTEGER NOT NULL default 0,
`currentmonster` INTEGER NOT NULL default 0,
`currentmonsterhp` INTEGER NOT NULL default 0,
`currentmonstersleep` INTEGER NOT NULL default 0,
`currentmonsterimmune` INTEGER NOT NULL default 0,
`currentuberdamage` INTEGER NOT NULL default 0,
`currentuberdefense` INTEGER NOT NULL default 0,
`currenthp` INTEGER NOT NULL default 15,
`currentmp` INTEGER NOT NULL default 0,
`currenttp` INTEGER NOT NULL default 10,
`maxhp` INTEGER NOT NULL default 15,
`maxmp` INTEGER NOT NULL default 0,
`maxtp` INTEGER NOT NULL default 10,
`level` INTEGER NOT NULL default 1,
`gold` INTEGER NOT NULL default 100,
`experience` INTEGER NOT NULL default 0,
`goldbonus` INTEGER NOT NULL default 0,
`expbonus` INTEGER NOT NULL default 0,
`strength` INTEGER NOT NULL default 5,
`dexterity` INTEGER NOT NULL default 5,
`attackpower` INTEGER NOT NULL default 5,
`defensepower` INTEGER NOT NULL default 5,
`weaponid` INTEGER NOT NULL default 0,
`armorid` INTEGER NOT NULL default 0,
`shieldid` INTEGER NOT NULL default 0,
`slot1id` INTEGER NOT NULL default 0,
`slot2id` INTEGER NOT NULL default 0,
`slot3id` INTEGER NOT NULL default 0,
`weaponname` TEXT NOT NULL default 'None',
`armorname` TEXT NOT NULL default 'None',
`shieldname` TEXT NOT NULL default 'None',
`slot1name` TEXT NOT NULL default 'None',
`slot2name` TEXT NOT NULL default 'None',
`slot3name` TEXT NOT NULL default 'None',
`dropcode` INTEGER NOT NULL default 0,
`spells` TEXT NOT NULL default '0',
`towns` TEXT NOT NULL default '0',
`game_skin` INTEGER NOT NULL DEFAULT 0
);
SQL);
$page .= self::table_status_msg($query === true, 'Users', 'create');
$time = round((microtime(true) - START), 4);
return $page."<br>Database setup complete in $time seconds.<br><br><a href=\"/install/third\">Click here to continue with installation.</a></body></html>";
}
/**
* Gather user info for admin account.
*/
public static function third(): string
{
return <<<HTML
<html>
<head>
<title>Dragon Knight Installation</title>
</head>
<body>
<b>Dragon Knight Installation: Page Three</b><br><br>
Now you must create an administrator account so you can use the control panel. Fill out the form below to create your account. You will be able to customize the class names through the control panel once your admin account is created.<br><br>
<form action="/install/fourth" method="post">
<table width="50%">
<tr><td width="20%" style="vertical-align:top;">Username:</td><td><input type="text" name="username" /><br><br><br></td></tr>
<tr><td style="vertical-align:top;">Password:</td><td><input type="password" name="password" /></td></tr>
<tr><td style="vertical-align:top;">Verify Password:</td><td><input type="password" name="confirm_password" /><br><br><br></td></tr>
<tr><td style="vertical-align:top;">Email Address:</td><td><input type="text" name="email" /></td></tr>
<tr><td style="vertical-align:top;">Verify Email:</td><td><input type="text" name="confirm_email" /><br><br><br></td></tr>
<tr><td style="vertical-align:top;">Character Class:</td><td><select name="charclass"><option value="1">Mage</option><option value="2">Warrior</option><option value="3">Paladin</option></select></td></tr>
<tr><td colspan="2"><input type="submit" name="submit" value="Submit" /> <input type="reset" name="reset" value="Reset" /></td></tr>
</table>
</form>
</body>
</html>
HTML;
}
/**
* Final page: insert new user row, congratulate the person on a job well done.
*/
public static function fourth(?array $post = null): string
{
$post ??= $_POST;
$form = validate($post, [
'username' => ['length:3-18', 'alpha-spaces'],
'email' => ['email'],
'confirm_email' => ['confirm'],
'password' => ['length:6-255'],
'confirm_password' => ['confirm'],
]);
if (! $form['valid']) {
exit(ul_from_validate_errors($form['errors']));
}
$form = $form['data'];
if (db()->query(
"INSERT INTO users (username, password, email, verify, charclass, authlevel) VALUES (?, ?, ?, 'g2g', ?, 1)",
[$form['username'], password_hash($form['password'], PASSWORD_ARGON2ID), $form['email'], $form['charclass'] ?? null]
) === false) {
exit('Failed to create user.');
}
file_put_contents(getcwd().'/.installed', date('Y-m-d H:i:s'));
return <<<HTML
<html>
<head>
<title>Dragon Knight Installation</title>
</head>
<body>
<b>Dragon Knight Installation: Page Four</b><br><br>
Your admin account was created successfully. Installation is complete.<br><br>
Be sure to delete install.php from your Dragon Knight directory for security purposes.<br><br>
You are now ready to <a href="/">play the game</a>. Note that you must log in through the public section before being allowed into the control panel. Once logged in, an "Admin" link will appear in the public static functions box of the left sidebar panel.<br><br/>
Thank you for using Dragon Knight!<br><br>-----<br><br>
<b>Optional:</b> Dragon Knight is a free product, and does not require registration of any sort. However, there is an
optional "call home" public static function in the installer, which notifies the author of your game installation. The ONLY information
transmitted with this public static function is the URL to your game. This is included mainly to satisfy the author's curiosity about
how many copies of the game are being installed and used. If you choose to submit your URL to the author, please
<a href="/install/fifth">click here</a>.
</body>
</html>
HTML;
}
/**
* Call Home public static function.
*/
public static function fifth(): string
{
if (mail('sky@sharkk.net', 'Dragon Knight Call Home', $_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']) !== true) {
exit('Dragon Knight was unable to send your URL. Please go back and try again, or just continue on to <a href=\"/\">the game</a>.');
}
return <<<HTML
<html>
<head>
<title>Dragon Knight Installation</title>
</head>
<body>
<b>Dragon Knight Installation: Page Five</b><br><br>
Thank you for submitting your URL!<br><br>
You are now ready to <a href="/">play the game</a>. Note that you must log in through the public section before being allowed into the control panel. Once logged in, an "Admin" link will appear in the public static functions box of the left sidebar panel.
</body>
</html>
HTML;
}
public static function table_status_msg(bool $condition, string $table_name, string $verb): string
{
$verb = match ($verb) {
'create' => ['created', 'creating'],
'populate' => ['populated', 'populating']
};
if ($condition === false) {
return "Error {$verb[1]} $table_name table. (".db()->lastErrorMsg().')<br>';
}
return "$table_name table {$verb[0]}.<br>";
}
}

View File

@ -0,0 +1,450 @@
<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight\Actions;
use DragonKnight\Router;
use function DragonKnight\db;
use function DragonKnight\env;
use function DragonKnight\get_town_by_xy;
use function DragonKnight\get_item;
use function DragonKnight\get_town_by_id;
use function DragonKnight\is_post;
use function DragonKnight\page_title;
use function DragonKnight\pretty_date;
use function DragonKnight\redirect;
use function DragonKnight\render;
use function DragonKnight\user;
class Towns
{
public static function register_routes(Router $r): Router
{
$r->form('/inn', fn() => \DragonKnight\Actions\Towns::inn());
$r->get('/shop', fn() => \DragonKnight\Actions\Towns::shop());
$r->form('/buy/:id', fn($id) => \DragonKnight\Actions\Towns::buy($id));
// $r->get('/sell', 'Towns\sell');
$r->get('/maps', fn() => \DragonKnight\Actions\Towns::maps());
$r->form('/maps/:id', fn($id) => \DragonKnight\Actions\Towns::buy_map($id));
$r->get('/gotown/:id', fn($id) => \DragonKnight\Actions\Towns::travelto($id));
return $r;
}
/**
* Spit out the main town page.
*/
public static function town(): string|false
{
$town = get_town_by_xy(user()->longitude, user()->latitude);
if ($town === false) {
exit('There is an error with your user account, or with the town data. Please try again.');
}
$page = ['news' => '', 'whos_online' => ''];
// News box. Grab latest news entry and display it. Something a little more graceful coming soon maybe.
if (env('show_news')) {
$news = db()->query('SELECT * FROM news ORDER BY id DESC LIMIT 1;')->fetchArray(SQLITE3_ASSOC);
$news_date = pretty_date($news['postdate']);
$news_content = nl2br($news['content']);
$page['news'] = <<<HTML
<div class="title">Latest News</div>
<span class="light">$news_date</span><br>
$news_content
HTML;
}
// Who's Online. Currently just members. Guests maybe later.
if (env('show_online')) {
$onlinequery = db()->query(<<<SQL
SELECT id, username
FROM users
WHERE onlinetime >= datetime('now', '-600 seconds')
ORDER BY username;
SQL);
$online_count = 0;
$online_rows = [];
while ($onlinerow = $onlinequery->fetchArray(SQLITE3_ASSOC)) {
$online_count++;
$online_rows[] = "<a href=\"javascript:opencharpopup({$onlinerow['id']})\">".$onlinerow['username'].'</a>';
}
$online_rows = implode(', ', $online_rows);
$page['whos_online'] = <<<HTML
<div class="title">Who's Online</div>
There are <b>$online_count</b> user(s) online within the last 10 minutes: $online_rows
HTML;
}
page_title($town['name']);
return render('towns', ['town' => $town, 'news' => $page['news'], 'whos_online' => $page['whos_online']]);
}
/**
* Staying at the inn resets all expendable stats to their max values.
* GET/POST /inn.
*/
public static function inn(): string
{
$town = get_town_by_xy(user()->longitude, user()->latitude);
if ($town === false) {
exit('Cheat attempt detected.<br><br>Get a life, loser.');
}
$page = '';
if (user()->gold < $town['innprice']) {
$page = <<<HTML
You do not have enough gold to stay at this Inn tonight. <br><br>
You may return to <a hx-get="/" hx-target="#middle">town</a>, or use the direction buttons on the left to start exploring.
HTML;
} elseif (is_post() && $_POST['rest']) {
user()->gold -= $town['innprice'];
user()->restore_points()->save();
$page = <<<HTML
You wake up feeling refreshed and ready for action. <br><br>
You may return to <a hx-get="/" hx-target="#middle">town</a>, or use the direction buttons on the left to start exploring.
HTML;
} elseif (is_post() && ! $_POST['rest']) {
redirect('/');
} else {
$page = <<<HTML
Resting at the inn will refill your current HP, MP, and TP to their maximum levels.<br><br>
A night's sleep at this Inn will cost you <b>{$town['innprice']} gold</b>. Is that ok?<br><br>
<form hx-post="/inn" hx-target="#middle">
<button name="rest" value="1">Yes</button>
<button name="rest" value="0">No</button>
</form>
HTML;
}
page_title($town['name'].' Inn');
return $page;
}
/**
* Displays a list of available items for purchase from the town the user is currently in. If the user is not in a town,
* redirects to home.
* GET /shop.
*/
public static function shop(): string
{
$town = get_town_by_xy(user()->longitude, user()->latitude);
if ($town === false) {
exit('Cheat attempt detected.<br><br>Get a life, loser.');
}
$page = <<<HTML
Buying weapons will increase your Attack Power. Buying armor and shields will increase your Defense Power.<br><br>
Click an item name to purchase it.<br><br>
The following items are available at this town:<br><br>
<table>
HTML;
$items = db()->query('SELECT * FROM items WHERE id IN ('.$town['itemslist'].');');
while ($item = $items->fetchArray(SQLITE3_ASSOC)) {
$attrib = ($item['type'] == 1) ? 'Attack Power:' : 'Defense Power:';
$page .= '<tr><td width="4%">';
$page .= match ($item['type']) {
1 => '<img src="/img/icon_weapon.gif" alt="weapon">',
2 => '<img src="/img/icon_armor.gif" alt="armor">',
3 => '<img src="/img/icon_shield.gif" alt="shield">'
};
$page .= '</td>';
if (user()->weaponid === $item['id'] || user()->armorid === $item['id'] || user()->shieldid === $item['id']) {
$page .= <<<HTML
<td width="32%"><span class="light">{$item['name']}</span></td>
<td width="32%"><span class="light">$attrib {$item['attribute']}</span></td>
<td width="32%"><span class="light">Already purchased</span></td>
HTML;
} else {
$specialdot = $item['special'] !== 'X' ? '<span class="highlight">&#42;</span>' : '';
$page .= <<<HTML
<td width="32%"><b><a hx-get="/buy/{$item['id']}" hx-target="#middle">{$item['name']}</a>$specialdot</b></td>
<td width="32%">$attrib <b>{$item['attribute']}</b></td>
<td width="32%">Price: <b>{$item['buycost']} gold</b></td>
HTML;
}
$page .= '</tr>';
}
$page .= <<<HTML
</table><br>
If you've changed your mind, you may also return back to <a hx-get="/" hx-target="#middle">town</a>.
HTML;
page_title($town['name'].' Shop');
return $page;
}
/**
* Confirm user's intent to purchase item.
*/
public static function buy(int $id): string
{
$town = get_town_by_xy(user()->longitude, user()->latitude);
if ($town === false) {
redirect('/');
}
if (! in_array($id, explode(',', $town['itemslist']))) {
redirect('/shop');
}
$item = get_item($id);
$can_afford = user()->gold >= $item['buycost'];
$page = '';
if (! $can_afford) {
$page = <<<HTML
You do not have enough gold to buy <b>{$item['name']}</b>.<br><br>
You may return to <a hx-get="/" hx-target="#middle">town</a>, <a hx-get="/shop" hx-target="#middle">shop</a>,
or use the direction buttons on the left to start exploring.
HTML;
} elseif (is_post() && ! $_POST['buy']) {
redirect('/shop');
} elseif (is_post() && $_POST['buy']) {
$type_mapping = [
1 => ['id' => 'weaponid', 'name' => 'weaponname', 'power' => 'attackpower'],
2 => ['id' => 'armorid', 'name' => 'armorname', 'power' => 'defensepower'],
3 => ['id' => 'shieldid', 'name' => 'shieldname', 'power' => 'defensepower'],
];
if (! isset($type_mapping[$item['type']])) { // should never happen
return 'Error! Invalid item type...<br>'.var_dump($item);
}
// Retrieve current equipped item or create a default
$current_equip_id = user()->{$type_mapping[$item['type']]['id']};
if ($current_equip_id != 0) {
$item2 = get_item($current_equip_id);
} else {
$item2 = ['attribute' => 0, 'buycost' => 0, 'special' => 'X'];
}
// Process special item effects
$specialFields = [];
$specialValues = [];
$powerAdjustments = 0;
foreach ([$item, $item2] as $index => $process_item) {
if ($process_item['special'] != 'X') {
$special = explode(',', $process_item['special']);
$toChange = $special[0];
$changeAmount = $index === 0 ? $special[1] : -$special[1];
user()->$toChange += $changeAmount;
$specialFields[] = "$toChange = ?";
$specialValues[] = user()->$toChange;
// Adjust attack or defense power
if ($toChange == 'strength' || $toChange == 'dexterity') {
$powerType = $toChange == 'strength' ? 'attackpower' : 'defensepower';
$powerAdjustments += $changeAmount;
}
}
}
// Determine power and type-specific updates
$currentType = $type_mapping[$item['type']];
$powerField = $currentType['power'];
user()->$powerField += $item['attribute'] - $item2['attribute'];
// Calculate new gold with trade-in value
user()->gold += ceil($item2['buycost'] / 2) - $item['buycost'];
// Ensure current HP/MP/TP don't exceed max values
user()->currenthp = min(user()->currenthp, user()->maxhp);
user()->currentmp = min(user()->currentmp, user()->maxmp);
user()->currenttp = min(user()->currenttp, user()->maxtp);
// Update item info in user
user()->{$type_mapping[$item['type']]['id']} = $item['id'];
user()->{$type_mapping[$item['type']]['name']} = $item['name'];
user()->save();
$page = <<<HTML
Thank you for purchasing <b>{$item['name']}</b>.<br><br>
You may return to <a hx-get="/" hx-target="#middle">town</a>, <a hx-get="/shop" hx-target="#middle">shop</a>, or use the direction buttons on the
left to start exploring.
HTML;
} else {
$type_to_row_mapping = [1 => 'weaponid', 2 => 'armorid', 3 => 'shieldid'];
$current_equipped_id = user()->{$type_to_row_mapping[$item['type']]} ?? 0;
if ($current_equipped_id != 0) {
$item2 = get_item($current_equipped_id);
$sell_price = ceil($item2['buycost'] / 2);
$page = <<<HTML
If you are buying the {$item['name']}, then I will buy your {$item2['name']} for $sell_price gold. Is that ok?<br><br>
<form hx-post="/buy/$id" hx-target="#middle">
<button name="buy" value="1">Yes</button>
<button name="buy" value="0">No</button>
</form>
HTML;
} else {
$page = <<<HTML
You are buying {$item['name']} for {$item['buycost']} gold, is that ok?<br><br>
<form hx-post="/buy/$id" hx-target="#middle">
<button name="buy" value="1">Yes</button>
<button name="buy" value="0">No</button>
</form>
HTML;
}
}
page_title('Buying '.$item['name']);
return $page;
}
/**
* List maps the user can buy.
*/
public static function maps(): string
{
$page = <<<HTML
Buying maps will put the town in your Travel To box, and it won't cost you as many TP to get there.<br><br>
Click a town name to purchase its map.<br><br>
<table>
HTML;
$mapped = explode(',', user()->towns);
$towns = db()->query('SELECT * FROM towns ORDER BY id;');
while ($town = $towns->fetchArray(SQLITE3_ASSOC)) {
$latitude = ($town['latitude'] >= 0) ? $town['latitude'].'N,' : ($town['latitude'] * -1).'S,';
$longitude = ($town['longitude'] >= 0) ? $town['longitude'].'E' : ($town['longitude'] * -1).'W';
if (in_array($town['id'], $mapped)) {
$page .= <<<HTML
<tr>
<td width="25%"><span class="light">{$town['name']}</span></td>
<td width="25%"><span class="light">Already mapped.</span></td>
<td width="35%"><span class="light">Location: $latitude $longitude</span></td>
<td width="15%"><span class="light">TP: {$town['travelpoints']}</span></td>
</tr>
HTML;
} else {
$page .= <<<HTML
<tr>
<td width="25%"><a href="/maps/{$town['id']}">{$town['name']}</a></td>
<td width="25%">Price: {$town['mapprice']} gold</td>
<td width="50%" colspan="2">Buy map to reveal details.</td>
</tr>
HTML;
}
}
$page .= <<<HTML
</table><br>
If you've changed your mind, you may also return back to <a hx-get="/" hx-target="#middle">town</a>.
HTML;
page_title('Maps');
return $page;
}
public static function buy_map(int $id): string
{
$town = get_town_by_id($id);
if ($town === false) {
redirect('/maps');
}
$page = '';
if (user()->gold < $town['mapprice']) {
$page = <<<HTML
You do not have enough gold to buy this map.<br><br>
You may return to <a hx-get="/" hx-target="#middle">town</a>, <a hx-get="/maps" hx-target="#middle">store</a>, or use the direction buttons on the left to start exploring.
HTML;
} elseif (is_post() && $_POST['buy']) {
user()->towns .= ",$id";
user()->gold -= $town['mapprice'];
user()->save();
$page = <<<HTML
Thank you for purchasing this map.<br><br>
You may return to <a hx-get="/" hx-target="#middle">town</a>, <a hx-get="/maps" hx-target="#middle">map shop</a>, or use the direction buttons on the left to start exploring.
HTML;
} elseif (is_post() && ! $_POST['buy']) {
redirect('/maps');
} else {
$page = <<<HTML
You are buying the <b>{$town['name']}</b> map for {$town['mapprice']} gold. Is that ok?<br><br>
<form action="/maps/$id" method="post">
<button name="buy" value="1">Yes</button>
<button name="buy" value="0">No</button>
</form>
HTML;
}
page_title('Buying '.$town['name'].' Map');
return $page;
}
/**
* Send a user to a town from the Travel To menu.
*/
public static function travelto(int $id, bool $use_points = true): string
{
if (user()->currentaction == 'Fighting') {
redirect('/fight');
}
$town = get_town_by_id($id);
$cost = $use_points ? $town['travelpoints'] : 0;
$mapped = explode(',', user()->towns);
$travelled = false;
$page = '';
if ($use_points && ! in_array($id, $mapped)) {
// trying to teleport to this town when it is not mapped
redirect('/');
} elseif (user()->currenttp < $cost) {
$page = 'You do not have enough TP to travel here. Please <a href="/" hx-get="/" hx-target="#middle">go back</a> and try again when you get more TP.';
} elseif ((user()->latitude == $town['latitude']) && (user()->longitude == $town['longitude'])) {
if (! in_array($id, $mapped)) {
// add town to user's mapped if they travelled here
user()->towns .= ",$id";
$travelled = true;
$page = <<<HTML
You have discovered <b>{$town['name']}</b>! It has been added to your mapped towns.<br><br>
You may now <a href="/" hx-get="/" hx-target="#middle">enter this town</a>.
HTML;
} else {
$page = 'You are already in this town. <a href="/" hx-get="/" hx-target="#middle">Click here</a> to return.';
}
} else {
user()->latitude = $town['latitude'];
user()->longitude = $town['longitude'];
user()->currenttp -= $cost;
$travelled = true;
$page = 'You have travelled to <b>'.$town['name'].'</b>. You may now <a href="/" hx-get="/" hx-target="#middle">enter this town</a>.';
}
if ($travelled) {
user()->currentaction = 'In Town';
user()->save();
}
page_title('Travelling to '.$town['name']);
return $page;
}
}

View File

@ -0,0 +1,272 @@
<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight\Actions;
use DragonKnight\Mail;
use DragonKnight\Router;
use function DragonKnight\db;
use function DragonKnight\env;
use function DragonKnight\is_post;
use function DragonKnight\page_title;
use function DragonKnight\redirect;
use function DragonKnight\render;
use function DragonKnight\token;
use function DragonKnight\ul_from_validate_errors;
use function DragonKnight\user;
use function DragonKnight\validate;
class Users
{
public static function register_routes(Router $r): Router
{
$r->form('/login', fn() => \DragonKnight\Actions\Users::login());
$r->get('/logout', fn() => \DragonKnight\Actions\Users::logout());
$r->form('/register', fn() => \DragonKnight\Actions\Users::register());
$r->form('/lostpassword', fn() => \DragonKnight\Actions\Users::lostpassword());
$r->post('/changepassword', fn() => \DragonKnight\Actions\Users::changepassword());
$r->form('/verify', fn() => \DragonKnight\Actions\Users::verify());
$r->form('/settings', fn() => \DragonKnight\Actions\Users::settings());
return $r;
}
/**
* Displays the login page, and processes login requests.
*/
public static function login(): string|false
{
global $auth;
if (is_post()) {
$form = validate($_POST, [
'username' => ['length:3-18', 'alpha-spaces'],
'password' => ['length:6-255'],
]);
if (! $form['valid']) {
exit(ul_from_validate_errors($form['errors']));
}
$good = $auth->login($form['data']['username'], $form['data']['password']);
if (! $good) {
exit('Invalid username or password. Please go back and try again.');
}
redirect('/');
}
page_title('Login');
return render('login');
}
/**
* Delete the current cookie and redirect to home.
*/
public static function logout(): void
{
global $auth;
$auth->logout();
redirect('/login');
}
/**
* Register a new account.
*/
public static function register(): string|false
{
$page = false;
if (isset($_POST['submit'])) {
$form = validate($_POST, [
'username' => ['length:3-18', 'alpha-spaces', 'unique:users,username'],
'email' => ['email', 'unique:users,email'],
'confirm_email' => ['confirm'],
'password' => ['length:6-255'],
'confirm_password' => ['confirm'],
'charclass' => ['in:1,2,3'],
]);
if (! $form['valid']) {
$err = ul_from_validate_errors($form['errors']);
$page = "The following error(s) occurred when your account was being made:<br><span style=\"color:red;\">$err</span><br>Please go back and try again.";
} else {
$form = $form['data'];
$password = password_hash($form['password'], PASSWORD_ARGON2ID);
$token = (env('verify_email') ?? false) ? token(8) : 'g2g';
db()->query('INSERT INTO users (verify, username, password, email, charclass) VALUES (?, ?, ?, ?, ?)', [
$token, $form['username'], $password, $form['email'], $form['charclass'],
]);
if ((env('verify_email') ?? false)) {
if (self::sendregmail($form['email'], $token)) {
$page = 'Your account was created successfully.<br><br>You should receive an Account Verification email shortly. You will need the verification code contained in that email before you are allowed to log in. Once you have received the email, please visit the <a href="users.php?do=verify">Verification Page</a> to enter your code and start playing.';
} else {
$page = 'Your account was created successfully.<br><br>However, there was a problem sending your verification email. Please check with the game administrator to help resolve this problem.';
}
} else {
$page = 'Your account was created succesfully.<br><br>You may now continue to the <a href="/login">Login Page</a> and continue playing '.env('game_name').'!';
}
}
} else {
if ((env('verify_email') ?? false)) {
$verify_text = '<br><span class="small">A verification code will be sent to the address above, and you will not be able to log in without first entering the code. Please be sure to enter your correct email address.</span>';
} else {
$verify_text = '';
}
$page = render('register', ['verify_text' => $verify_text]);
}
page_title('Register');
return $page;
}
public static function verify(): string|false
{
if (isset($_POST['submit'])) {
$u = trim($_POST['username'] ?? '');
$e = trim($_POST['email'] ?? '');
$t = trim($_POST['token'] ?? '');
$query = db()->query('SELECT id FROM users WHERE username=? AND email=? AND verify=? LIMIT 1;', [$u, $e, $t]);
if ($query === false) {
exit('Verification failed. Go back, double-check your details, and try again.');
}
db()->query("UPDATE users SET verify='g2g' WHERE username=?;", [$u]);
return 'Your account was verified successfully.<br><br>You may now continue to the <a href="/login">Login Page</a> and start playing the game.<br><br>Thanks for playing!';
}
return render('verify');
}
public static function lostpassword(): string|false
{
if (isset($_POST['submit'])) {
$e = trim($_POST['email'] ?? '');
if (! db()->exists('users', 'email', $e)) {
exit('No account with that email address.');
}
$newpass = token(16);
$hashed = password_hash($newpass, PASSWORD_ARGON2ID);
db()->query('UPDATE users SET password=? WHERE email=?;', [$hashed, $e]);
if (self::sendpassemail($e, $newpass)) {
return 'Your new password was emailed to the address you provided.<br><br>Once you receive it, you may <a href="/login">Log In</a> and continue playing.<br><br>Thank you.';
}
return 'There was an error sending your new password.<br><br>Please check with the game administrator for more information.<br><br>We apologize for the inconvience.';
}
return render('lostpassword');
}
public static function changepassword(): string|false
{
if (! isset($_POST['submit'])) {
return false;
}
$u = trim($_POST['username'] ?? '');
$p = $_POST['password'] ?? '';
$np = $_POST['new_password'] ?? '';
$np2 = $_POST['new_password2'] ?? '';
$user = db()->query('SELECT password FROM users WHERE username=? LIMIT 1;', [$u]);
$user = $user->fetchArray(SQLITE3_ASSOC);
if ($user === false) {
exit('No account with that username.');
}
if (! password_verify($p, $user['password'])) {
exit('The old password you provided was incorrect.');
}
if (empty($np) || strlen($np) < 6) {
$errors[] = 'New password is required and must be at least 6 characters long.';
}
if ($np2 !== $np) {
$errors[] = 'Verify New Password must match.';
}
$realnewpass = password_hash($np, PASSWORD_ARGON2ID);
db()->query('UPDATE users SET password=? WHERE username=?;', [$realnewpass, $u]);
global $auth;
$auth->logout();
return 'Your password was changed successfully.<br><br>You have been logged out of the game to avoid errors.<br><br>Please <a href="/login">log back in</a> to continue playing.';
}
public static function settings(): string|false
{
if (! is_post()) {
return render('settings');
}
$form = validate($_POST, [
'game_skin' => ['in:0,1'],
]);
if (! $form['valid']) {
exit(ul_from_validate_errors($form['errors']));
}
$form = $form['data'];
user()->game_skin = $form['game_skin'];
user()->save();
$alert = '<div class="alert">Settings updated</div>';
return $alert.render('settings');
}
public static function sendpassemail($emailaddress, $password): bool
{
$email = <<<HTML
You or someone using your email address submitted a Lost Password application on the {env('game_name')} server, located at {env('game_url')}.
We have issued you a new password so you can log back into the game.
Your new password is: $password
Thanks for playing.
HTML;
return Mail::send_email($emailaddress, env('game_name').' Lost Password', $email);
}
public static function sendregmail($emailaddress, $vercode): bool
{
$verurl = env('game_url').'/verify';
$email = <<<HTML
You or someone using your email address recently signed up for an account on the {env('game_name')} server, located at {env('game_url')}.
This email is sent to verify your registration email. In order to begin using your account, you must verify your email address.
Please visit the Verification Page ($verurl) and enter the code below to activate your account.
Verification code: $vercode
If you were not the person who signed up for the game, please disregard this message. You will not be emailed again.
HTML;
return Mail::send_email($emailaddress, env('game_name').' Account Verification', $email);
}
}

View File

@ -1,10 +1,18 @@
<?php
declare(strict_types=1);
/*
This is an experimental new class for handling user auth. The idea is to rely as much as possible on PHP's native
session handling. When authenticated, the class will store use data in GLOBALS state.
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight;
class Auth
{
/**
@ -22,7 +30,7 @@ class Auth
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Strict'
'samesite' => 'Strict',
]);
session_start();
@ -59,7 +67,9 @@ class Auth
public function login(string $username, string $password): bool
{
$user = get_user($username);
if ($user === false) return false;
if ($user === false) {
return false;
}
if (password_verify($password, $user['password'])) {
$_SESSION['authenticated'] = true;
@ -94,7 +104,7 @@ class Auth
{
$_SESSION = [];
if (ini_get("session.use_cookies")) {
if (ini_get('session.use_cookies')) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
}

View File

@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight;
env_load(__DIR__.'/../../.env');
$uri = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
$GLOBALS['cache'] = [];
$GLOBALS['state'] = [];
/**
* These are table names whose data we want to be able to edit in the admin panel in bulk.
*/
define('ADMIN_BULK_DATA_STRUCTS', [
'users', 'items', 'drops', 'towns', 'monsters', 'levels', 'spells',
]);
if (! file_exists((__DIR__.'/../../.installed')) && $uri[0] !== 'install') { // need to install the game
redirect('/install');
return;
}
if (file_exists((__DIR__.'/../../.installed')) && $uri[0] === 'install') { // game is installed, go play!
redirect('/');
return;
}
if (! file_exists((__DIR__.'/../../.installed')) || $uri[0] === 'install') {
return;
}
// boostrap the game
if (! env('game_open')) {
echo render('The game is currently closed for maintanence. Please check back later.');
exit;
}
$auth = new Auth();
// Login (or verify) if not logged in.
if (user() === false) {
if (! in_array($uri[0], ['login', 'register', 'verify', 'lostpassword', 'help'])) {
redirect('/login');
}
return;
}
if ($auth->good()) {
// Block user if he/she has been banned.
if (user()->authlevel === 2) {
exit('Your account has been banned.');
}
// Force verify if the user isn't verified yet.
if ((env('verify_email') ?? false) && user()->verify !== 'g2g' && ! in_array($uri[0], ['verify', 'logout'])) {
redirect('/verify');
}
// Ensure the user can't use the admin panel.
if (user()->authlevel !== 1 && $uri[0] === 'admin') {
redirect('/');
}
// Update default page layout based on root endpoint
page_layout('layouts/primary');
if ($uri[0] === 'admin') {
page_layout('layouts/admin');
}
if ($uri[0] === 'help') {
page_layout('layouts/help');
}
user()->update_online_time();
return;
}
$auth->logout();
redirect('/login');

View File

@ -1,5 +1,21 @@
<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight;
use SQLite3;
use SQLite3Result;
/**
* An extension to the SQLite3 class to add our own logging and binding semantics!
*/
@ -30,8 +46,10 @@ class Database extends SQLite3
$p = strpos($query, '?') !== false;
try {
$stmt = $this->prepare($query);
foreach ($params ?? [] as $k => $v) $stmt->bindValue($p ? $k + 1 : $k, $v, $this->getSQLiteType($v));
} catch (Exception $e) {
foreach ($params ?? [] as $k => $v) {
$stmt->bindValue($p ? $k + 1 : $k, $v, $this->getSQLiteType($v));
}
} catch (\Exception $e) {
exit("Failed to prepare query ($query): ".$this->lastErrorMsg());
}
@ -52,6 +70,7 @@ class Database extends SQLite3
$start = microtime(true);
$r = parent::exec($query);
$this->log($query, microtime(true) - $start);
return $r;
}
@ -68,6 +87,7 @@ class Database extends SQLite3
}
$result = $this->query($query, [':v' => $value]);
return $result->fetchArray(SQLITE3_NUM) !== false;
}

View File

@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight;
define('VERSION', '1.2.5');
define('BUILD', 'Reawaken');
define('START', microtime(true));
class DragonKnight
{
public const VERSION = '1.2.5';
public const BUILD = 'Reawaken';
}

132
src/DragonKnight/Mail.php Normal file
View File

@ -0,0 +1,132 @@
<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight;
class Mail
{
/**
* Send an email or log email details.
*
* @param string $to Recipient email address
* @param string $subject Email subject
* @param string $message Email body
* @param array $options Optional configuration options
* @return bool Success status of email sending or logging
*/
public static function send_email(string $to, string $subject, string $message, array $options = []): bool
{
// Default configuration
$config = array_merge([
'from' => env('admin_email', 'noreply@'.$_SERVER['SERVER_NAME']),
'log_path' => getcwd().'/logs/email.log',
'method' => 'smtp', // 'smtp' or 'log'
'smtp_host' => env('smtp_host', 'localhost'),
'smtp_port' => env('smtp_port', 25),
'smtp_username' => env('smtp_username', null),
'smtp_password' => env('smtp_password', null),
'smtp_encryption' => env('smtp_encryption', null),
], $options);
// Always send to log during debug
if (env('debug', false)) {
$config['method'] = 'log';
}
// Validate input
if (empty($to) || empty($subject) || empty($message)) {
error_log('Email sending failed: Missing required parameters');
return false;
}
// Prepare email headers
$headers = [
'From: '.$config['from'],
'X-Mailer: PHP/'.phpversion(),
];
// Choose sending method
switch ($config['method']) {
case 'log':
// Log email details to file
$logMessage = sprintf(
"[%s] To: %s, Subject: %s, Message:\n\n %s\n\n\n\n",
date('Y-m-d H:i:s'),
$to,
$subject,
$message
);
// Attempt to log to file
if (file_put_contents($config['log_path'], $logMessage, FILE_APPEND) === false) {
error_log('Failed to write to log file: '.$config['log_path']);
return false;
}
return true;
case 'smtp':
default:
// Attempt to send via SMTP
try {
// Prepare SMTP connection
$smtpConfig = [
'host' => $config['smtp_host'],
'port' => $config['smtp_port'],
'username' => $config['smtp_username'],
'password' => $config['smtp_password'],
'encryption' => $config['smtp_encryption'],
];
// Send email using PHP's mail public static function (basic SMTP)
$result = mail(
$to,
$subject,
$message,
implode("\r\n", $headers)
);
if (! $result) {
error_log('SMTP email sending failed');
return false;
}
return true;
} catch (\Exception $e) {
error_log('Email sending error: '.$e->getMessage());
return false;
}
}
}
// Example usage:
// Send via SMTP
// send_email('recipient@example.com', 'Test Subject', 'Email body text');
// Send via log
// send_email('recipient@example.com', 'Test Subject', 'Email body text', ['method' => 'log']);
// Customize SMTP settings
// send_email('recipient@example.com', 'Test Subject', 'Email body text', [
// 'method' => 'smtp',
// 'smtp_host' => 'smtp.yourserver.com',
// 'smtp_port' => 587,
// 'smtp_username' => 'your_username',
// 'smtp_password' => 'your_password',
// 'smtp_encryption' => 'tls'
// ]);
}

120
src/DragonKnight/Math.php Normal file
View File

@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight;
class Math
{
/*
Internal math public static functions, such as to calculate EXP, HP, stats, etc.
*/
/**
* Calculates the ***total*** EXP required at a particular level in order to level up.
*/
public static function calculate_exp(int $level, int $growth_rate): int
{
if ($level < 1) {
throw new \InvalidArgumentException('Level must be 1 or greater');
}
// Growth rates:
// 0 = Erratic
// 1 = Fast
// 2 = Medium Fast
// 3 = Medium Slow
// 4 = Slow
// 5 = Fluctuating
if ($growth_rate < 0 || $growth_rate > 5) {
throw new \InvalidArgumentException('Growth rate must be between 0 and 5');
}
return match ($growth_rate) {
0 => Math::calculate_erratic_exp($level),
1 => (4 * pow($level, 3)) / 5,
2 => pow($level, 3),
3 => ((6 * pow($level, 3)) / 5) - (15 * pow($level, 2)) + (100 * $level) - 140,
4 => (5 * pow($level, 3)) / 4,
5 => Math::calculate_fluctuating_exp($level),
};
}
/**
* Calculate the ***total*** EXP for a given level in the Erratic formula.
*/
public static function calculate_erratic_exp(int $level): int
{
if ($level <= 50) {
return (pow($level, 3) * (100 - $level)) / 50;
} elseif ($level <= 68) {
return (pow($level, 3) * (150 - $level)) / 100;
} elseif ($level <= 98) {
return (pow($level, 3) * ((1911 - (10 * $level)) / 3)) / 500;
}
return (pow($level, 3) * (160 - $level)) / 100;
}
/**
* Calculate the ***total*** EXP for a given level in the Fluctuating formula.
*/
public static function calculate_fluctuating_exp(int $level): int
{
if ($level <= 15) {
return pow($level, 3) * ((((($level + 1) / 3) + 24) / 50));
} elseif ($level <= 36) {
return pow($level, 3) * (($level + 14) / 50);
}
return pow($level, 3) * ((($level / 2) + 32) / 50);
}
/**
* Calculate a points total from a base. Modes: 1 (weak), 2 (normal), 3 (strong).
*/
public static function calculate_points(int $base_points, int $level, int $mode = 2): int
{
if ($level < 1) {
throw new \InvalidArgumentException('Level must be 1 or greater');
}
$growth_multiplier = match ($mode) {
1 => 0.15,
2 => 0.3,
3 => 0.6,
default => throw new \InvalidArgumentException('Invalid mode. Use 1 (weak), 2 (normal), or 3 (strong)')
};
return (int) floor((2 * $base_points * $level * $growth_multiplier) / 100) + $level + 10;
}
/**
* Calculate a stat total from a base. Modes: 1 (weak), 2 (normal), 3 (strong).
*/
public static function calculate_stat(int $base_stat, int $level, int $mode = 2): int
{
if ($level < 1) {
throw new \InvalidArgumentException('Level must be 1 or greater');
}
$growth_multiplier = match ($mode) {
1 => 0.15,
2 => 0.3,
3 => 0.6,
default => throw new \InvalidArgumentException('Invalid mode. Use 1 (weak), 2 (normal), or 3 (strong)')
};
return (int) floor((2 * $base_stat * $level * $growth_multiplier) / 100) + 5;
}
}

View File

@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight\Models;
use function DragonKnight\db;
class Model
{
protected string $table_name = '';
protected array $original_data = [];
protected array $changes = [];
public function __construct(array $data)
{
$this->original_data = $data;
$this->changes = [];
}
public function __get(string $key): mixed
{
return array_key_exists($key, $this->changes) ? $this->changes[$key] : $this->original_data[$key] ?? false;
}
public function __set(string $key, mixed $value): void
{
if (array_key_exists($key, $this->original_data)) {
if ($value !== $this->original_data[$key]) {
$this->changes[$key] = $value;
}
} else {
throw new \InvalidArgumentException("Attempted to write to $key, which doesn't exist in the data for this model.");
}
}
public function save(): bool
{
if (empty($this->changes)) {
return true;
}
$placeholders = [];
$values = [];
foreach ($this->changes as $key => $value) {
$placeholders[] = "$key=?";
$values[] = $value;
}
$values[] = $this->id;
$query = 'UPDATE '.$this->table_name.' SET '.implode(', ', $placeholders).' WHERE id = ?;';
$result = db()->query($query, $values);
return $result === false ? false : true;
}
}

View File

@ -0,0 +1,117 @@
<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight\Models;
use function DragonKnight\db;
use function DragonKnight\get_spells_from_list;
class User extends Model
{
protected string $table_name = 'users';
/**
* Find a user by their ID, username or email. Returns false on any failure.
*/
public static function find(int|string $id): User|false
{
$query = db()->query(
'SELECT * FROM users WHERE id=? OR username=? COLLATE NOCASE OR email=? COLLATE NOCASE LIMIT 1;',
[$id, $id, $id]
);
if ($query === false) {
return false;
}
$data = $query->fetchArray(SQLITE3_ASSOC);
if ($data === false) {
return false;
}
return new User($data);
}
/**
* Return a list of spells from this user's spell list.
*/
public function spells(): array|false
{
return get_spells_from_list($this->spells);
}
/**
* Restore all HP, MP, and TP values to their max.
*/
public function restore_points(): User
{
$this->currenthp = $this->maxhp;
$this->currentmp = $this->maxmp;
$this->currenttp = $this->maxtp;
return $this;
}
/**
* Sends a manual update to online time for this user.
*/
public function update_online_time(): void
{
if ($this->onlinetime && strtotime($this->onlinetime) > strtotime('-9 minutes')) {
return;
}
db()->query('UPDATE users SET onlinetime=CURRENT_TIMESTAMP WHERE id=?;', [$this->id]);
}
/**
* Heal HP by a given amount. Caps to max HP. Returns number of points restored.
*/
public function restore_hp(int $amount): int
{
$initial_hp = $this->currenthp;
$this->currenthp += $amount;
if ($this->currenthp > $this->maxhp) {
$this->currenthp = $this->maxhp;
}
return $this->currenthp - $initial_hp;
}
/**
* Save works just as it does on the Model class. In our case, though, user state changing may necessitate
* OOB swaps for parts of the UI that have user data displayed. Left and right nav, for example. In these cases,
* we set a flag in GLOBALS state to signify this.
*/
public function save(): bool
{
if (empty($this->changes)) {
return true;
}
$placeholders = [];
$values = [];
foreach ($this->changes as $key => $value) {
$placeholders[] = "$key=?";
$values[] = $value;
}
$values[] = $this->id;
$query = 'UPDATE '.$this->table_name.' SET '.implode(', ', $placeholders).' WHERE id = ?;';
$result = db()->query($query, $values);
if ($result === false) {
return false;
}
$GLOBALS['state']['user-state-changed'] = true;
return true;
}
}

View File

@ -0,0 +1,91 @@
<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight;
/**
* This file contains public static functions to render various UI elements.
* The goal is to begin shifting elements in the game to HTMX/AJAX for more fluid gameplay.
*/
class Render
{
/**
* Prepare content for final render. If the request is HTMX-based, will return just the content passed to it. Otherwise
* it will render() onto $layout with some additional bits.
*/
public static function content(string $content, string $layout = 'layouts/primary'): string
{
if (is_htmx()) {
return $content;
}
return render($layout, ['content' => $content]);
}
public static function debug_db_info(): string
{
$total_time = round(microtime(true) - START, 4);
$htmx = is_htmx() ? ' (htmx)' : '';
return '<div id="debug-db-info" hx-swap-oob="true">'.$total_time.' Seconds, '.db()->count.' Queries'.$htmx.'</div>';
}
public static function right_nav(): string
{
if (user() === false) {
return '';
}
// Flashy numbers if they're low
$hp = (user()->currenthp <= (user()->maxhp / 5)) ? '<blink><span class="highlight"><b>*'.user()->currenthp.'*</b></span></blink>' : user()->currenthp;
$mp = (user()->currentmp <= (user()->maxmp / 5)) ? '<blink><span class="highlight"><b>*'.user()->currentmp.'*</b></span></blink>' : user()->currentmp;
$template = render('right_nav', ['hp' => $hp, 'mp' => $mp]);
if (is_htmx()) {
$template = '<section id="right" hx-swap-oob="true">'.$template.'</section>';
}
return $template;
}
public static function left_nav(): string
{
if (user() === false) {
return '';
}
$template = render('left_nav');
if (is_htmx()) {
$template = '<section id="left" hx-swap-oob="true">'.$template.'</section>';
}
return $template;
}
public static function babblebox(): string
{
return render('babblebox', ['messages' => babblebox_messages()]);
}
public static function debug_query_log(): string
{
$html = '<pre id="debug-query-log" hx-swap-oob="true">';
foreach (db()->log as $record) {
$query_string = str_replace(["\r\n", "\n", "\r"], ' ', $record[0]);
$error_string = ! empty($record[2]) ? '// '.$record[2] : '';
$html .= '<div>['.round($record[1], 2)."s] {$query_string}{$error_string}</div>";
}
return $html.'</pre>';
}
}

214
src/DragonKnight/Router.php Normal file
View File

@ -0,0 +1,214 @@
<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight;
/**
* A radix-trie based URI router. Seperates URIs into chunks, then turns those chunks into an efficiently parsed
* trie. Supports URI variables!
*/
class Router
{
/**
* List of valid HTTP verbs.
*/
private const VALID_METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
/**
* The tree of currently registered routes.
*/
private array $routes = [];
/**
* Store the last inserted node so we can register middleware and attributes to it.
*/
private array $last_inserted_node;
/**
* Add a route to the route tree. The route must be a URI path, and contain dynamic segments
* using a colon prefix. (:id, :slug, etc).
*
* Example:
* `$r->add($routes, 'GET', '/posts/:id', function($id) { echo "Viewing post $id"; });`
*/
public function add(string $method, string $route, callable $handler): self
{
$this->validateMethod($method);
$this->validateRoute($route);
$segments = $route === '/' ? [''] : explode('/', trim($route, '/'));
$node = &$this->routes;
foreach ($segments as $segment) {
$segment = str_starts_with($segment, ':') ? ':x' : $segment;
if ($segment === '') {
continue;
}
$node = &$node[$segment];
}
$node[$method] = [
'handler' => $handler,
'middleware' => [],
];
$this->last_inserted_node = &$node[$method];
return $this;
}
/**
* Perform a lookup in the route tree for a given method and URI. Returns an array with a result code,
* a handler if found, and any dynamic parameters. Codes are 200 for success, 404 for not found, and
* 405 for method not allowed.
*
* @return array ['code', 'handler', 'params']
*/
public function lookup(string $method, string $uri): array|int
{
$node = $this->routes;
$params = [];
if ($uri === '/') {
return $node[$method] ?? 405;
}
foreach (explode('/', trim($uri, '/')) as $segment) {
if (isset($node[$segment])) {
$node = $node[$segment];
continue;
}
if (isset($node[':x'])) {
$params[] = $segment;
$node = $node[':x'];
continue;
}
return 404;
}
$node[$method]['params'] = $params;
return $node[$method] ?? 405;
}
/**
* Add a middleware function to the last inserted node's stack.
*/
public function middleware(callable $middleware): self
{
$this->last_inserted_node['middleware'][] = $middleware;
return $this;
}
/**
* Shorthand to register a GET route.
*/
public function get(array|string $route, callable $handler): self
{
return is_array($route)
? array_reduce($route, fn($r, $route) => $r->add('GET', $route, $handler), $this)
: $this->add('GET', $route, $handler);
}
/**
* Shorthand to register a POST route.
*/
public function post(string $route, callable $handler): self
{
return $this->add('POST', $route, $handler);
}
/**
* Shorthand to register a PUT route.
*/
public function put(string $route, callable $handler): self
{
return $this->add('PUT', $route, $handler);
}
/**
* Shorthand to register a DELETE route.
*/
public function delete(string $route, callable $handler): self
{
return $this->add('DELETE', $route, $handler);
}
/**
* Shorthand to register a PATCH route.
*/
public function patch(string $route, callable $handler): self
{
return $this->add('PATCH', $route, $handler);
}
/**
* Register multiple verbs to the same route.
*/
public function many(array $methods, string $route, callable $handler): self
{
foreach ($methods as $method) {
$this->add($method, $route, $handler);
}
return $this;
}
/**
* Register all verbs to the same route.
*/
public function any(string $route, callable $handler): self
{
foreach (self::VALID_METHODS as $method) {
$this->add($method, $route, $handler);
}
return $this;
}
/**
* Some pages function entirely as forms; thus we can shorthand a GET/POST route.
*/
public function form(string $route, callable $handler): self
{
return $this->many(['GET', 'POST'], $route, $handler);
}
/**
* Validate the given method against valid HTTP verbs.
*/
private function validateMethod(string $method): void
{
if (! in_array($method, self::VALID_METHODS)) {
throw new \InvalidArgumentException("Invalid HTTP method: $method");
}
}
/**
* Validate that a new route follows expected formatting.
*/
private function validateRoute(string $route): void
{
if ($route === '') {
throw new \InvalidArgumentException('Route cannot be empty');
}
// Ensure route starts with a slash
if (! str_starts_with($route, '/')) {
throw new \InvalidArgumentException("Route must start with a '/'");
}
}
}

View File

@ -0,0 +1,733 @@
<?php
declare(strict_types=1);
/*
* This file is a part of the Dragon-Knight project.
*
* Copyright (c) 2024-present Sharkk
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace DragonKnight;
use DragonKnight\Actions\Explore;
use DragonKnight\Actions\Towns;
use DragonKnight\Models\User;
function index(): string
{
$page = false;
if (! $user = user()) {
error_log('User not found in index() function.');
return $page ?: '';
}
if ($user->currentaction === 'In Town') {
$page = Towns::town();
} elseif ($user->currentaction === 'Exploring') {
$page = Explore::explore();
} elseif ($user->currentaction === 'Fighting') {
redirect('/fight');
}
return $page ?: '';
}
/**
* Show the user their position on the current world map. Only works with a game size of 250 and the default towns 😅.
*/
function show_map(): void
{
$pos = sprintf(
'<div style="position: absolute; width: 5px; height: 5px; border-radius: 1000px; border: solid 1px black; background-color: red; left: %dpx; top: %dpx;"></div>',
round(258 + user()->longitude * (500 / 500) - 3),
round(258 - user()->latitude * (500 / 500) - 3)
);
echo render('layouts/minimal', [
'content' => '<img src="/img/map.gif" alt="Map">'.$pos,
'title' => 'Map',
]);
}
/**
* Show a character's info. Defaults to the currently logged in user.
*/
function show_character_info(int $id = 0): string
{
$user = $id !== 0 ? User::find($id) : user();
if ($user === false) {
throw new \RuntimeException('Failed to show info for user ID '.$id);
}
$level = db()->query("SELECT `{$user->charclass}_exp` FROM levels WHERE id=? LIMIT 1;", [$user->level + 1])->fetchArray(SQLITE3_ASSOC);
$spells = $user->spells();
$magic_list = 'None';
if (! empty($spells)) {
$magic_list = '';
foreach ($spells as $spell) {
$magic_list .= $spell['name'].'<br>';
}
}
$showchar = render('show_char', [
'char' => $user,
'level' => $level,
'magic_list' => $magic_list,
]);
return render('layouts/minimal', ['content' => $showchar, 'title' => $user->username.' Information']);
}
/**
* Handle a POST request to send a new babblebox message.
*/
function babblebox(): ?string
{
if (is_post()) {
$content = trim($_POST['babble']);
if (! empty($content)) {
db()->query(
'INSERT INTO babble (posttime, author, babble) VALUES (CURRENT_TIMESTAMP, ?, ?);',
[user()->username, $content]
);
}
return babblebox_messages();
}
return null;
}
/**
* The handler that is polled by HTMX for new babblebox messages.
*/
function babblebox_messages(): string
{
if (user() === false) {
return '';
}
$query = db()->query('SELECT * FROM babble ORDER BY id ASC LIMIT 40;');
$has_chats = false;
$messages = '';
while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
$has_chats = true;
$messages .= '<div class="message">[<b>'.$row['author'].'</b>] '.make_safe($row['babble']).'</div>';
}
if (! $has_chats) {
$messages = 'There are no messages. :(';
}
return $messages;
}
/**
* Open or get SQLite database connection.
*/
function db(): Database
{
if (! is_dir($path = __DIR__.'/../../db')) {
error_log('Database folder not found at '.$path.'. Please run the installer first.');
throw new \RuntimeException("Database folder not found at $path. Please run the installer first.");
}
return $GLOBALS['database'] ??= new Database($path.'/database.db');
}
/**
* Redirect to a different URL, exit.
*/
function redirect(string $location): void
{
if (is_htmx()) {
$target = isset($_SERVER['HTTP_HX_TARGET']) ? '#'.$_SERVER['HTTP_HX_TARGET'] : '#middle';
$json = json_encode(['path' => $location, 'target' => $target]);
header("HX-Location: $json");
} else {
header("Location: $location");
}
exit;
}
/**
* Render a view with the given data. Can be used redundantly within the template.
*/
function render(string $path_to_base_view, array $data = []): string|false
{
ob_start();
extract($data);
require __DIR__."/../../templates/$path_to_base_view.php";
return ob_get_clean();
}
/**
* Replace tags with given content.
*/
function parse(string $template, array $array): string
{
return strtr($template, array_combine(
array_map(fn ($key) => "{{{$key}}}", array_keys($array)),
array_values($array)
));
}
/**
* Change the SQLite3 datetime format (YYYY-MM-DD HH:MM:SS) into something friendlier.
*/
function pretty_date(string $uglydate): string
{
return date('l, F j, Y', mktime(
0,
0,
0,
(int) substr($uglydate, 5, 2), // Month
(int) substr($uglydate, 8, 2), // Day
(int) substr($uglydate, 0, 4) // Year
));
}
/**
* Use htmlentities with UTF-8 encoding to ensure we're only outputting healthy, safe and effective HTML.
*/
function make_safe(string $content): string
{
return htmlentities($content, ENT_QUOTES, 'UTF-8');
}
/**
* Finalize admin page and output to browser.
*/
function display_admin($content, $title)
{
echo render('layouts/admin', [
'title' => $title,
'content' => $content,
]);
exit;
}
/**
* Determine what game skin to use. If a user is logged in then it uses their setting, otherwise defaults to 0 (retro).
*/
function game_skin(): int
{
return user() !== false
? user()->game_skin
: 0;
}
/**
* Get a town's data by it's coordinates.
*/
function get_town_by_xy(int $x, int $y): array|false
{
$cache_tag = "town-$x-$y";
if (! isset($GLOBALS['cache'][$cache_tag])) {
$query = db()->query('SELECT * FROM towns WHERE longitude = ? AND latitude = ? LIMIT 1;', [$x, $y]);
if ($query === false) {
return false;
}
$GLOBALS['cache'][$cache_tag] = $query->fetchArray(SQLITE3_ASSOC);
}
return $GLOBALS['cache'][$cache_tag];
}
/**
* Get a town's data by it's ID.
*/
function get_town_by_id(int $id): array|false
{
$query = db()->query('SELECT * FROM towns WHERE id = ? LIMIT 1;', [$id]);
if ($query === false) {
return false;
}
return $query->fetchArray(SQLITE3_ASSOC);
}
/**
* Get a user's data by their ID, username or email.
*/
function get_user(int|string $id, string $data = '*'): array|false
{
$query = db()->query(
"SELECT $data FROM users WHERE id=? OR username=? COLLATE NOCASE OR email=? COLLATE NOCASE LIMIT 1;",
[$id, $id, $id]
);
if ($query === false) {
return false;
}
return $query->fetchArray(SQLITE3_ASSOC);
}
/**
* Get an item by it's ID.
*/
function get_item(int $id): array|false
{
$query = db()->query('SELECT * FROM items WHERE id=? LIMIT 1;', [$id]);
if ($query === false) {
return false;
}
return $query->fetchArray(SQLITE3_ASSOC);
}
/**
* Get a drop by it's ID.
*/
function get_drop(int $id): array|false
{
$query = db()->query('SELECT * FROM drops WHERE id=? LIMIT 1;', [$id]);
if ($query === false) {
return false;
}
return $query->fetchArray(SQLITE3_ASSOC);
}
/**
* Get a spell by it's ID.
*/
function get_spell(int $id): array|false
{
$query = db()->query('SELECT * FROM spells WHERE id=? LIMIT 1;', [$id]);
if ($query === false) {
return false;
}
return $query->fetchArray(SQLITE3_ASSOC);
}
/**
* Get a monster by it's ID.
*/
function get_monster(int $id): array|false
{
$query = db()->query('SELECT * FROM monsters WHERE id=? LIMIT 1;', [$id]);
if ($query === false) {
return false;
}
return $query->fetchArray(SQLITE3_ASSOC);
}
/**
* Translate a Specials keyword to it's string.
*/
function special_to_string(string $special): string
{
return match ($special) {
'maxhp' => 'Max HP',
'maxmp' => 'Max MP',
'maxtp' => 'Max TP',
'goldbonus' => 'Gold Bonus (%)',
'expbonus' => 'Experience Bonus (%)',
'strength' => 'Strength',
'dexterity' => 'Dexterity',
'attackpower' => 'Attack Power',
'defensepower' => 'Defense Power',
default => $special
};
}
/**
* Generate a pretty dope token.
*/
function token($length = 32): string
{
return bin2hex(random_bytes($length));
}
/**
* Validate any given array of data against rules. Returns [valid, data, error]. Data contains the trimmed
* values from the input array. Note: all fields with rules are assumed to be required, unless the optional
* rule is used.
*
* Example: ['required', 'no-trim', 'length:5-20', 'alphanum-spaces']
*/
function validate(array $input_data, array $rules): array
{
$data = [];
$errors = [];
foreach ($rules as $field => $field_rules) {
$value = $input_data[$field] ?? null;
$field_name = ucfirst(str_replace('_', ' ', $field));
$is_required = true;
$default_value = null;
if (in_array('optional', $field_rules)) {
$is_required = false;
}
foreach ($field_rules as $rule) {
if (strpos($rule, 'default:') === 0) {
$default_value = substr($rule, 8);
break;
}
}
if (($value === null || $value === '') && $default_value !== null) {
$value = $default_value;
}
if (($value === null || $value === '') && ! $is_required) {
continue;
}
if ($is_required && ($value === null || $value === '')) {
$errors[$field][] = "{$field_name} is required.";
continue;
}
if (! in_array('no-trim', $field_rules)) {
$value = trim($value);
}
$data[$field] = $value;
foreach ($field_rules as $rule) {
// Parse rule and arguments
if (strpos($rule, ':') !== false) {
list($rule_name, $rule_args) = explode(':', $rule, 2);
} else {
$rule_name = $rule;
$rule_args = null;
}
if ($rule_name === 'optional') {
continue;
}
switch ($rule_name) {
case 'bool':
if (! isset($input_data[$field]) || empty($value)) {
$value = false;
} else {
$value = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if ($value === null) {
$errors[$field][] = "{$field_name} must be a valid boolean value.";
}
}
break;
case 'length':
list($min, $max) = explode('-', $rule_args);
$len = strlen((string) $value);
if ($len < $min || $len > $max) {
$errors[$field][] = "{$field_name} must be between {$min} and {$max} characters.";
}
break;
case 'alphanum':
if (! preg_match('/^[a-zA-Z0-9]+$/', $value)) {
$errors[$field][] = "{$field_name} must contain only letters and numbers.";
}
break;
case 'alpha':
if (! preg_match('/^[a-zA-Z]+$/', $value)) {
$errors[$field][] = "{$field_name} must contain only letters and numbers.";
}
break;
case 'alphanum-spaces':
if (! preg_match('/^[a-zA-Z0-9\s_]+$/', $value)) {
$errors[$field][] = "{$field_name} must contain only letters, numbers, spaces, and underscores.";
}
break;
case 'alpha-spaces':
if (! preg_match('/^[a-zA-Z\s_]+$/', $value)) {
$errors[$field][] = "{$field_name} must contain only letters, numbers, spaces, and underscores.";
}
break;
case 'email':
if (! filter_var($value, FILTER_VALIDATE_EMAIL)) {
$errors[$field][] = "{$field_name} must be a valid email address.";
}
break;
case 'int':
if (filter_var($value, FILTER_VALIDATE_INT) === false) {
$errors[$field][] = "{$field_name} must be an integer.";
}
break;
case 'min':
if ($value < $rule_args) {
$errors[$field][] = "{$field_name} must be at least {$rule_args}.";
}
break;
case 'max':
if ($value > $rule_args) {
$errors[$field][] = "{$field_name} must be no more than {$rule_args}.";
}
break;
case 'regex':
if (! preg_match($rule_args, $value)) {
$errors[$field][] = "{$field_name} does not match the required pattern.";
}
break;
case 'in':
$options = explode(',', $rule_args);
if (! in_array($value, $options)) {
$errors[$field][] = "{$field_name} must be one of: ".implode(', ', $options);
}
break;
case 'confirm':
$field_to_confirm = substr($field, 8);
$confirm_value = $data[$field_to_confirm] ?? '';
$confirm_field_name = ucfirst(str_replace('_', ' ', $field_to_confirm));
if ($value !== $confirm_value) {
$errors[$field][] = "{$field_name} must match {$confirm_field_name}.";
}
break;
case 'unique':
list($table, $column) = explode(',', $rule_args, 2);
if (db()->exists($table, $column, $value)) {
$errors[$field][] = "{$field_name} must be unique.";
}
break;
}
}
}
foreach ($input_data as $field => $value) {
if (! isset($data[$field])) {
$data[$field] = trim($value);
}
}
return [
'valid' => empty($errors),
'data' => $data,
'errors' => $errors,
];
}
/**
* Generates a ul list from `validate()`'s errors.
*/
function ul_from_validate_errors(array $errors): string
{
$string = '<ul>';
foreach ($errors as $field => $errors) {
$string .= '<li>';
foreach ($errors as $error) {
$string .= $error;
}
$string .= '</li>';
}
return $string.'</ul>';
}
/**
* Load the environment variables from the .env file.
*/
function env_load(string $filePath): void
{
if (! file_exists($filePath)) {
throw new \Exception('The .env file does not exist. (el)');
}
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
$line = trim($line);
// Skip lines that are empty after trimming or are comments
if ($line === '' || str_starts_with($line, '#')) {
continue;
}
// Skip lines without an '=' character
if (strpos($line, '=') === false) {
continue;
}
[$name, $value] = explode('=', $line, 2);
$name = trim($name);
$value = trim($value, " \t\n\r\0\x0B\"'"); // Trim whitespace and quotes
if (! array_key_exists($name, $_SERVER) && ! array_key_exists($name, $_ENV)) {
putenv("$name=$value");
$_ENV[$name] = $value;
$_SERVER[$name] = $value;
}
}
}
/**
* Retrieve an environment variable.
*/
function env(string $key, mixed $default = null)
{
$v = $_ENV[$key] ?? $_SERVER[$key] ?? (getenv($key) ?: $default);
return match (true) {
$v === 'true' => true,
$v === 'false' => false,
is_numeric($v) => (int) $v,
is_float($v) => (float) $v,
default => $v
};
}
/**
* Get the data on spells from a given list of IDs.
*/
function get_spells_from_list(array|string $spell_ids): array|false
{
if (is_string($spell_ids)) {
$spell_ids = explode(',', $spell_ids);
}
$placeholders = implode(',', array_fill(0, count($spell_ids), '?'));
$query = db()->query("SELECT id, name, type FROM spells WHERE id IN($placeholders)", $spell_ids);
if ($query === false) {
return false;
}
$rows = [];
while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
$rows[] = $row;
}
return ! empty($rows)
? $rows
: false;
}
function generate_stat_bar(int $current, int $max): string
{
$percent = $max > 0 ? round(max(0, $current) / $max * 100, 4) : 0;
if ($percent < 0) {
$percent = 0;
}
if ($percent > 100) {
$percent = 100;
}
$color = $percent >= 66 ? 'green' : ($percent >= 33 ? 'yellow' : 'red');
return <<<HTML
<div class="stat-bar" style="width: 15px; height: 100px; border: solid 1px black;">
<div style="height: $percent%; background-image: url(/img/bars_$color.gif);"></div>
</div>
HTML;
}
function create_stat_table(): string
{
return '<div class="stat-table">'.
'<div class="stat-row">'.
'<div class="stat-col">'.generate_stat_bar((int) user()->currenthp, (int) user()->maxhp).'<div>HP</div></div>'.
'<div class="stat-col">'.generate_stat_bar((int) user()->currentmp, (int) user()->maxmp).'<div>MP</div></div>'.
'<div class="stat-col">'.generate_stat_bar((int) user()->currenttp, (int) user()->maxtp).'<div>TP</div></div>'.
'</div>'.
'</div>';
}
/**
* Returns the user in the GLOBALS state, if there is one. If not, populates it if there is a SESSION user_id.
*/
function user(): User|false
{
$GLOBALS['state']['user'] ??= (isset($_SESSION['user_id']) ? User::find($_SESSION['user_id']) : false);
return $GLOBALS['state']['user'];
}
/**
* Determine whether a request is from HTMX. If HTMX is trying to restore history, we will say no in order to render
* full pages.
*/
function is_htmx(): bool
{
if (isset($_SERVER['HTTP_HX_HISTORY_RESTORE_REQUEST']) && $_SERVER['HTTP_HX_HISTORY_RESTORE_REQUEST'] === 'true') {
return false;
}
return isset($_SERVER['HTTP_HX_REQUEST']) && $_SERVER['HTTP_HX_REQUEST'] === 'true';
}
/**
* Return whether the request is POST.
*/
function is_post(): bool
{
return $_SERVER['REQUEST_METHOD'] === 'POST';
}
/**
* Get the current page title per updates. Optionally set a new title.
*/
function page_title(?string $new_title = null): ?string
{
if ($new_title) {
return $GLOBALS['state']['new-page-title'] = $new_title;
}
return $GLOBALS['state']['new-page-title'] ?? env('game_name');
}
/**
* Render the response for the browser based on the request context. The main point is to seperate the handling
* of HTMX responses from normal responses.
*/
function render_response(array $uri, string $content): string
{
if ($uri[0] === 'babblebox') {
return $content;
}
if (is_htmx()) {
header('HX-Push-Url: '.$_SERVER['REQUEST_URI']);
$content .= '<title>'.page_title().'</title>';
$content .= Render::debug_db_info();
if (env('debug', false)) {
$content .= Render::debug_query_log();
}
if ($GLOBALS['state']['user-state-changed'] ?? false) {
$content .= Render::right_nav();
$content .= Render::left_nav();
}
}
return Render::content($content, page_layout());
}
/**
* Get/set page layout through GLOBALS state.
*/
function page_layout(string $layout = ''): string
{
if ($layout === '') {
return $GLOBALS['state']['page-layout'] ?? 'layouts/primary';
}
return $GLOBALS['state']['page-layout'] = $layout;
}

View File

@ -1,566 +0,0 @@
<?php
// admin.php :: primary administration script.
namespace Admin;
use Router;
use SQLite3Result;
function register_routes(Router $r): Router
{
if (user() !== false && user()->authlevel === 1) {
$r->get('/admin', 'Admin\donothing');
$r->form('/admin/main', 'Admin\primary');
$r->get('/admin/items', 'Admin\items');
$r->form('/admin/items/:id', 'Admin\edit_item');
$r->get('/admin/drops', 'Admin\drops');
$r->form('/admin/drops/:id', 'Admin\edit_drop');
$r->get('/admin/towns', 'Admin\towns');
$r->form('/admin/towns/:id', 'Admin\edit_town');
$r->get('/admin/monsters', 'Admin\monsters');
$r->form('/admin/monsters/:id', 'Admin\edit_monster');
$r->get('/admin/levels', 'Admin\levels');
$r->post('/admin/levels', 'Admin\edit_level');
$r->get('/admin/spells', 'Admin\spells');
$r->form('/admin/spells/:id', 'Admin\edit_spell');
$r->get('/admin/users', 'Admin\users');
$r->form('/admin/users/:id', 'Admin\edit_user');
$r->form('/admin/news', 'Admin\add_news');
}
return $r;
}
/**
* Home page for the admin panel.
*/
function donothing(): string
{
page_title('Admin');
return <<<HTML
Welcome to the administration section. Use the links on the left bar to control and edit various
elements of the game.
<br><br>
Please note that the control panel has been created mostly as a shortcut for certain individual settings. It is
meant for use primarily with editing one thing at a time. If you need to completely replace an entire table
(say, to replace all stock monsters with your own new ones), it is suggested that you use a more in-depth
database tool such as <a href="https://sqlitebrowser.org/" target="_new">SQLite Browser</a>.
<br><br>
Also, you should be aware that certain portions of the DK code are dependent on the formatting of certain
database results (for example, the special attributes on item drops). While I have attempted to point these out
throughout the admin script, you should definitely pay attention and be careful when editing some fields,
because mistakes in the database content may result in script errors or your game breaking completely.
HTML;
}
/**
* Main settings that get written to .env
*/
function primary(): string
{
if (is_post()) {
$form = validate($_POST, [
'gamename' => ['alphanum-spaces'],
'gamesize' => ['int', 'min:5'],
'class1name' => ['alpha-spaces'],
'class2name' => ['alpha-spaces'],
'class3name' => ['alpha-spaces'],
'gameopen' => ['bool'],
'verifyemail' => ['bool'],
'shownews' => ['bool'],
'showonline' => ['bool'],
'showbabble' => ['bool']
]);
if ($form['valid']) {
$form = $form['data'];
if (($form['gamesize'] % 5) != 0) exit('Map size must be divisible by five.');
// @todo
// write changes to .env
$page = 'Main settings updated.';
} else {
$error_list = ul_from_validate_errors($form['errors']);
$page = <<<HTML
<b>Errors:</b><br>
<div style="color: red;">{$error_list}</div><br>
Please go back and try again.
HTML;
}
} else {
$page = render('admin/main_settings');
}
page_title('Admin: Main Settings');
return $page;
}
/**
* Show the full list of items that can be edited.
*/
function items(): string
{
$items = db()->query('SELECT * FROM items ORDER BY id;');
$page = "<h2>Edit Items</h2>Click an item's name or ID to edit it.<br><br>\n";
$page .= build_bulk_table($items, 'name', '/admin/items');
page_title('Admin: Items');
return $page;
}
/**
* Shows the form for editing an item via GET, processes edits via POST
*/
function edit_item(int $id): string
{
$item = get_item($id);
if (is_post()) {
$page = handle_edit_form($id, 'items', validate($_POST, [
'name' => [],
'type' => ['int', 'in:1,2,3'],
'buycost' => ['int', 'min:0'],
'attribute' => ['int', 'min:0'],
'special' => ['default:X']
]));
} else {
$page = render('admin/edit_item', ['item' => $item]);
}
page_title('Admin: Editing '.$item['name']);
return $page;
}
/**
* Show the full list of drops that can be edited
*/
function drops()
{
$drops = db()->query('SELECT * FROM drops ORDER BY id;');
$page = "<h2>Edit Drops</h2>Click an item's name to edit it.<br><br>\n";
$page .= build_bulk_table($drops, 'name', '/admin/drops');
page_title('Admin: Drops');
return $page;
}
/**
* Show the form to edit drops via GET, process those edits via POST
*/
function edit_drop(int $id): string
{
$drop = get_drop($id);
if (is_post()) {
$page = handle_edit_form($id, 'drops', validate($_POST, [
'name' => [],
'mlevel' => ['int', 'min:1'],
'attribute1' => [],
'attribute2' => ['default:X'],
]));
} else {
$page = render('admin/edit_drop', ['drop' => $drop]);
}
page_title('Admin: Editing '.$drop['name']);
return $page;
}
/**
* Generate the list of towns that can be edited.
*/
function towns(): string
{
$towns = db()->query('SELECT * FROM towns ORDER BY id;');
$page = "<h2>Edit Towns</h2>Click an town's name or ID to edit it.<br><br>\n";
$page .= build_bulk_table($towns, 'name', '/admin/towns');
page_title('Admin: Towns');
return $page;
}
/**
* Save any changes to the town made.
*/
function edit_town(int $id): string
{
$town = get_town_by_id($id);
if (is_post()) {
$page = handle_edit_form($id, 'towns', validate($_POST, [
'name' => [],
'latitude' => ['int', 'min:0', 'max:'.env('game_size')],
'longitude' => ['int', 'min:0', 'max:'.env('game_size')],
'innprice' => ['int', 'min:0'],
'mapprice' => ['int', 'min:0'],
'travelpoints' => ['int', 'min:0'],
'itemslist' => ['optional']
]));
} else {
$page = render('admin/edit_town', ['town' => $town]);
}
page_title('Admin: Editing '.$town['name']);
return $page;
}
/**
* List the monsters available to edit.
*/
function monsters()
{
$max_level = db()->query('SELECT level FROM monsters ORDER BY level DESC LIMIT 1;')->fetchArray(SQLITE3_ASSOC)['level'];
$monsters = db()->query('SELECT * FROM monsters ORDER BY id;');
$page = "<h2>Edit Monsters</h2>";
if ((env('game_size') / 5) !== $max_level) {
$page .= "<span class=\"highlight\">Note:</span> Your highest monster level does not match with your entered map size. Highest monster level should be ".(env('game_size') / 5).", yours is $max_level. Please fix this before opening the game to the public.<br>";
} else {
$page .= "Monster level and map size match. No further actions are required for map compatibility.<br>";
}
$page .= "Click an monster's name or ID to edit it.<br><br>\n";
$page .= build_bulk_table($monsters, 'name', '/admin/monsters');
page_title('Admin: Monsters');
return $page;
}
/**
* Handle the actual editing of the monster.
*/
function edit_monster(int $id): string
{
$monster = get_monster($id);
if (is_post()) {
$page = handle_edit_form($id, 'monsters', validate($_POST, [
'name' => [],
'maxhp' => ['int', 'min:1'],
'maxdam' => ['int', 'min:0'],
'armor' => ['int', 'min:0'],
'level' => ['int', 'min:1'],
'maxexp' => ['int', 'min:0'],
'maxgold' => ['int', 'min:0'],
'immune' => ['in:0,1,2']
]));
} else {
$page = render('admin/edit_monster', ['monster' => $monster]);
}
page_title('Admin: Editing '.$monster['name']);
return $page;
}
/**
* List all spells available to edit.
*/
function spells(): string
{
$page = "<h2>Edit Spells</h2>Click an spell's name to edit it.<br><br>\n";
$spells = db()->query('SELECT * FROM spells ORDER BY id;');
$page .= build_bulk_table($spells, 'name', '/admin/spells');
page_title('Admin: Spells');
return $page;
}
/**
* Handle the editing of an individual spell.
*/
function edit_spell(int $id): string
{
$spell = get_spell($id);
if (is_post()) {
$page = handle_edit_form($id, 'spells', validate($_POST, [
'name' => [],
'mp' => ['int', 'min:0'],
'attribute' => ['int', 'min:0'],
'type' => ['in:1,2,3,4,5']
]));
} else {
$page = render('admin/edit_spell', ['spell' => $spell]);
}
page_title('Admin: Editing '.$spell['name']);
return $page;
}
/**
* List all editable levels.
*/
function levels(): string
{
$max_level = db()->query('SELECT id FROM levels ORDER BY id DESC LIMIT 1;')->fetchArray(SQLITE3_ASSOC)['id'];
$page = <<<HTML
<h2>Edit Levels</h2>
Select a level number from the dropdown box to edit it.<br><br>
<form action="/admin/levels" method="post" hx-post="/admin/levels" hx-target="#main">
<select name="level">
HTML;
for ($i = 2; $i < $max_level; $i++) $page .= "<option value=\"$i\">$i</option>\n";
$page .= <<<HTML
</select>
<button type="submit">Edit</button>
</form>
HTML;
page_title('Admin: Levels');
return $page;
}
/**
* Handle the editing of a level.
*/
function edit_level()
{
if (!isset($_POST['level'])) return 'No level to edit.';
$id = $_POST['level'];
$level = db()->query('SELECT * FROM levels WHERE id=? LIMIT 1;', [$id])->fetchArray(SQLITE3_ASSOC);
if (is_post() && isset($_POST['save'])) {
unset($_POST['save']);
unset($_POST['level']);
$page = handle_edit_form($id, 'levels', validate($_POST, [
'1_exp' => ['int', 'min:0'],
'1_hp' => ['int', 'min:0'],
'1_mp' => ['int', 'min:0'],
'1_tp' => ['int', 'min:0'],
'1_strength' => ['int', 'min:0'],
'1_dexterity' => ['int', 'min:0'],
'1_spells' => ['int', 'min:0'],
'2_exp' => ['int', 'min:0'],
'2_hp' => ['int', 'min:0'],
'2_mp' => ['int', 'min:0'],
'2_tp' => ['int', 'min:0'],
'2_strength' => ['int', 'min:0'],
'2_dexterity' => ['int', 'min:0'],
'2_spells' => ['int', 'min:0'],
'3_exp' => ['int', 'min:0'],
'3_hp' => ['int', 'min:0'],
'3_mp' => ['int', 'min:0'],
'3_tp' => ['int', 'min:0'],
'3_strength' => ['int', 'min:0'],
'3_dexterity' => ['int', 'min:0'],
'3_spells' => ['int', 'min:0']
]), 'Level <b>'.$id.'</b> updated.');
} else {
$page = render('admin/edit_level', ['level' => $level]);
}
page_title('Admin: Editing Level '.$id);
return $page;
}
function users()
{
$users = db()->query('SELECT * FROM users ORDER BY id;');
$page = "<h2>Edit Users</h2>Click a username or ID to edit the account.<br><br><div class=\"table-wrapper\">";
$page .= build_bulk_table($users, 'username', '/admin/users');
page_title('Admin: Users');
return $page . '</div>';
}
/**
* Handle editing a user.
*/
function edit_user(int $id): string
{
$user = db()->query('SELECT * FROM users WHERE id = ? LIMIT 1;', [$id])->fetchArray(SQLITE3_ASSOC);
if (is_post()) {
$form = validate($_POST, [
'username' => ['length:3-18', 'alpha-spaces', 'unique:users,username'],
'verify' => [],
'authlevel' => ['int'],
'email' => ['email', 'unique:users,email'],
'charclass' => ['in:1,2,3'],
'latitude' => ['int', 'min:0', 'max:'.env('game_size')],
'longitude' => ['int', 'min:0', 'max:'.env('game_size')],
'currentaction' => [],
'currentfight' => ['int'],
'currentmonster' => ['int'],
'currentmonsterhp' => ['int'],
'currentmonstersleep' => ['int'],
'currentmonsterimmune' => ['int'],
'currentuberdamage' => ['int'],
'currentuberdefense' => ['int'],
'currenthp' => ['int', 'min:0'],
'currentmp' => ['int', 'min:0'],
'currenttp' => ['int', 'min:0'],
'maxhp' => ['int', 'min:1'],
'maxmp' => ['int', 'min:1'],
'maxtp' => ['int', 'min:1'],
'level' => ['int', 'min:1'],
'gold' => ['int', 'min:0'],
'experience' => ['int', 'min:0'],
'goldbonus' => ['int'],
'expbonus' => ['int'],
'strength' => ['int'],
'dexterity' => ['int'],
'attackpower' => ['int'],
'defensepower' => ['int'],
'weaponid' => ['int'],
'armorid' => ['int'],
'shieldid' => ['int'],
'slot1id' => ['int'],
'slot2id' => ['int'],
'slot3id' => ['int'],
'weaponname' => ['default:None'],
'armorname' => ['default:None'],
'shieldname' => ['default:None'],
'slot1name' => ['default:None'],
'slot2name' => ['default:None'],
'slot3name' => ['default:None'],
'dropcode' => ['int', 'min:0', 'default:0'],
'spells' => ['optional'],
'towns' => ['optional']
]);
if ($form['valid']) {
save_data_row('users', $form['data'], $id);
$page = 'User <b>'.$user['username'].'</b> updated.';
} else {
$error_list = ul_from_validate_errors($form['errors']);
$page = <<<HTML
<b>Errors:</b><br>
<div style="color: red;">{$error_list}</div><br>
Please go back and try again.
HTML;
}
} else {
$page = render('admin/edit_user', ['user' => $user]);
}
page_title('Admin: Editing '.$user['username']);
return $page;
}
/**
* Handling adding news posts.
*/
function add_news()
{
if (is_post()) {
$c = trim($_POST['content'] ?? '');
$errors = [];
if (empty($c)) $errors[] = "Content is required.";
if (count($errors) === 0) {
db()->query('INSERT INTO news (author, content) VALUES (?, ?);', [user()->username, $c]);
$page = 'News post added.';
} else {
$error_list = implode('<br>', $errors);
$page = "<b>Errors:</b><br><div style=\"color:red;\">$error_list</div><br>Please go back and try again.";
}
} else {
$page = <<<HTML
<h2>Add a News Post</h2>
<form action="/admin/news" method="post" hx-post="/admin/news" hx-target="#main">
Type your post below and then click Submit to add it.<br>
<textarea name="content" rows="5" cols="50"></textarea><br>
<button type="submit">Submit</button>
<button type="reset">Clear</button>
</form>
HTML;
}
page_title('Admin: Add News');
return $page;
}
/**
* Build an HTML table containing all columns and rows of a given data structure. Takes a SQLiteResult3 of a SELECT
* query.
*/
function build_bulk_table(SQLite3Result $query_data, string $edit_column, string $edit_link): string
{
$data = [];
$data_count = 0;
while ($row = $query_data->fetchArray(SQLITE3_ASSOC)) $data[$data_count++] = $row;
if ($data_count === 0) return 'No data.';
$columns = array_diff(array_keys($data[0]), ['password']);
$html_parts = [
'<table><colgroup>',
str_repeat('<col>', count($columns)),
'</colgroup><thead><tr>'
];
foreach ($columns as $column) {
$html_parts[] = '<th>' .
make_safe($column === 'id' ? 'ID' : ucfirst($column)) .
'</th>';
}
$html_parts[] = '</tr></thead><tbody>';
$is_edit_column = array_flip(['id', $edit_column]);
foreach ($data as $row) {
$html_parts[] = '<tr>';
foreach ($columns as $column) {
$name = make_safe($row[$column]);
$html_parts[] = isset($is_edit_column[$column])
? "<td><a href=\"{$edit_link}/{$row['id']}\" hx-get=\"{$edit_link}/{$row['id']}\" hx-target=\"#main\">{$name}</a></td>"
: "<td>{$name}</td>";
}
$html_parts[] = '</tr>';
}
$html_parts[] = '</tbody></table>';
return implode('', $html_parts);
}
/**
* Save a row of data to it's table from the data supplied.
*/
function save_data_row(string $table, array $data, int $id): SQLite3Result|false
{
$data = array_filter($data, fn($value) => $value !== null && $value !== '');
if (empty($data)) return false;
$fields = implode(',', array_map(fn($key) => "`$key`=?", array_keys($data)));
$values = array_values($data);
$values[] = $id;
return db()->query("UPDATE $table SET $fields WHERE id=?", $values);
}
/**
* Handle the result of a generic edit form.
*/
function handle_edit_form(int $id, string $table, array $form, string $updated_message = ''): string
{
if ($form['valid']) {
save_data_row($table, $form['data'], $id);
$page = $updated_message ?: '<b>'.$form['data']['name'].'</b> updated.';
} else {
$error_list = ul_from_validate_errors($form['errors']);
$page = <<<HTML
<b>Errors:</b><br>
<div style="color: red;">{$error_list}</div><br>
Please go back and try again.
HTML;
}
return $page;
}

View File

@ -1,69 +0,0 @@
<?php
// explore.php :: Handles all map exploring, chances to fight, etc.
namespace Explore;
/**
* Just spit out a blank exploring page. Exploring without a GET string is normally when they first log in, or when
* they've just finished fighting.
*/
function explore()
{
page_title('Exploring');
return <<<HTML
<div class="title"><img src="/img/title_exploring.gif" alt="Exploring"></div>
You are exploring the map, and nothing has happened. Continue exploring using the direction buttons or the Travel To menus.
HTML;
}
function move() {
// Early exit if fighting
if (user()->currentaction == 'Fighting') redirect('/fight');
// Validate direction
$form = validate($_POST, ['direction' => ['in:north,west,east,south']]);
if (!$form['valid']) return ul_from_validate_errors($form['errors']);
// Current game state
$game_size = env('game_size');
$latitude = user()->latitude;
$longitude = user()->longitude;
$direction = $form['data']['direction'];
// Calculate new coordinates with boundary checks
switch ($direction) {
case 'north':
$latitude = min($latitude + 1, $game_size);
break;
case 'south':
$latitude = max($latitude - 1, -$game_size);
break;
case 'east':
$longitude = min($longitude + 1, $game_size);
break;
case 'west':
$longitude = max($longitude - 1, -$game_size);
break;
}
// Check for town
$town = get_town_by_xy($longitude, $latitude);
if ($town !== false) {
return \Towns\travelto($town['id'], false);
}
// Determine action (1 in 5 chance of fighting)
if (rand(1, 5) === 1) {
user()->currentaction = 'Fighting';
user()->currentfight = 1;
} else {
user()->currentaction = 'Exploring';
}
user()->latitude = $latitude;
user()->longitude = $longitude;
user()->save();
return index();
}

View File

@ -1,451 +0,0 @@
<?php
// fight.php :: Handles all fighting action.
namespace Fights;
use Router;
function register_routes(Router $r): Router
{
$r->form('/fight', 'Fights\fight');
$r->get('/victory', 'Fights\victory');
$r->form('/drop', 'Fights\drop');
$r->get('/dead', 'Fights\dead');
return $r;
}
/**
* One big long function that determines the outcome of the fight.
*/
function fight()
{
if (user()->currentaction !== 'Fighting') exit('Cheat attempt detected.<br><br>Get a life, loser.');
$page = ["magiclist" => "", "yourturn" => "", "monsterturn" => "", "monsterhp" => "", "command" => ""];
$playerisdead = 0;
// Generate spell list
$user_spells = user()->spells();
if (!empty($user_spells)) {
$page['magiclist'] = '<select name="userspell">';
foreach ($user_spells as $spell) {
$page['magiclist'] .= "<option value=\"{$spell['id']}\">{$spell['name']}</option>\n";
}
$page['magiclist'] .= '</select> <input type="submit" name="spell" value="Spell"><br><br>';
}
// Determine initial combat parameters
$chancetoswingfirst = rand(1, 10) + (int)ceil(sqrt(user()->dexterity));
if (user()->currentfight === 1) {
$maxlevel = (int)floor(max(abs(user()->latitude) + 5, abs(user()->longitude) + 5) / 5);
$minlevel = max(1, $maxlevel - 2);
$monster = db()->query('SELECT * FROM monsters WHERE level >= ? AND level <= ? ORDER BY RANDOM() LIMIT 1;', [
$minlevel, $maxlevel
])->fetchArray(SQLITE3_ASSOC);
user()->currentmonster = $monster["id"];
user()->currentmonsterhp = rand((int)(($monster["maxhp"]/5)*4), $monster["maxhp"]);
user()->currentmonstersleep = 0;
user()->currentmonsterimmune = $monster["immune"];
$chancetoswingfirst = ($chancetoswingfirst > (rand(1,7) + (int)ceil(sqrt($monster["maxdam"])))) ? 1 : 0;
}
// Get monster statistics
$monster = get_monster(user()->currentmonster);
$page['monstername'] = $monster['name'];
// Run action
if (isset($_POST["run"])) {
$chancetorun = rand(4,10) + (int)ceil(sqrt(user()->dexterity));
if ($chancetorun <= (rand(1,5) + (int)ceil(sqrt($monster["maxdam"])))) {
$page["yourturn"] = "You tried to run away, but were blocked in front!<br><br>";
$page["monsterhp"] = "Monster's HP: " . user()->currentmonsterhp . "<br><br>";
// Monster turn logic (similar to original function)
$page["monsterturn"] = handleMonsterTurn($userrow, $monster);
user()->currentaction = 'Exploring';
user()->save();
redirect('/');
}
}
// Fight action
if (isset($_POST["fight"])) {
// Player's attack
$min = (int)(user()->attackpower * 0.75);
$max = (int)(user()->attackpower / 3);
$tohit = (int)ceil(mt_rand(min($min, $max), max($min, $max)));
$toexcellent = rand(1,150);
if ($toexcellent <= sqrt(user()->strength)) {
$tohit *= 2;
$page["yourturn"] .= "Excellent hit!<br>";
}
$min = (int)($monster["armor"] * 0.75);
$max = (int)$monster["armor"];
$toblock = (int)ceil(rand(min($min, $max), max($min, $max)) / 3);
$tododge = rand(1, 100);
$monsterdamage = max(1, $tohit - $toblock);
if ($tododge <= sqrt($monster["armor"])) {
$monsterdamage = 0;
$page["yourturn"] .= "The monster is dodging. No damage has been scored.<br>";
}
if (user()->currentuberdamage != 0) {
$monsterdamage += (int)ceil($monsterdamage * (user()->currentuberdamage / 100));
}
user()->currentmonsterhp -= $monsterdamage;
$page["yourturn"] .= "You attack the monster for $monsterdamage damage.<br><br>";
$page["monsterhp"] = "Monster's HP: " . user()->currentmonsterhp . "<br><br>";
// Check for monster defeat
if (user()->currentmonsterhp <= 0) {
user()->currentmonsterhp = 0;
user()->save();
redirect('/victory');
}
// Monster's turn
$page["monsterturn"] = handleMonsterTurn($userrow, $monster);
}
// Spell action
if (isset($_POST["spell"])) {
$pickedspell = $_POST["userspell"];
if ($pickedspell == 0) return 'You must select a spell first. Please go back and try again.';
$newspellrow = get_spell($pickedspell);
$spell = in_array($pickedspell, explode(',', user()->spells));
if (!$spell) return 'You have not yet learned this spell. Please go back and try again.';
if (user()->currentmp < $newspellrow["mp"]) {
return 'You do not have enough Magic Points to cast this spell. Please go back and try again.';
}
// Spell type handling (similar to original function)
$page["yourturn"] = handleSpellCast($userrow, $newspellrow);
$page["monsterhp"] = "Monster's HP: " . user()->currentmonsterhp . "<br><br>";
// Check for monster defeat
if (user()->currentmonsterhp <= 0) {
user()->currentmonsterhp = 0;
user()->save();
redirect('/victory');
}
// Monster's turn
$page["monsterturn"] = handleMonsterTurn($userrow, $monster);
}
// Monster's turn if player lost first swing
if (!isset($_POST["run"]) && !isset($_POST["fight"]) && !isset($_POST["spell"]) && $chancetoswingfirst == 0) {
$page["yourturn"] = "The monster attacks before you are ready!<br><br>";
$page["monsterhp"] = "Monster's HP: " . user()->currentmonsterhp . "<br><br>";
$page["monsterturn"] = handleMonsterTurn($userrow, $monster);
}
// Prepare command or death message
if ($playerisdead != 1) {
$page["command"] = <<<HTML
Command?<br><br>
<form action="/fight" method="post" hx-post="/fight" hx-target="#middle">
<input type="submit" name="fight" value="Fight"><br><br>
{$page['magiclist']}
<input type="submit" name="run" value="Run"><br><br>
</form>
HTML;
user()->currentfight += 1;
} else {
$page["command"] = <<<HTML
<b>You have died.</b><br><br>
As a consequence, you've lost half of your gold. However, you have been given back a portion of your hit points to continue your journey.<br><br>
You may now continue back to <a href="/" hx-get="/" hx-target="#middle">town</a>, and we hope you fair better next time.
HTML;
}
user()->save();
// Finalize page and display it
$page = render('fight', ['page' => $page]);
return $page;
}
function victory()
{
if (user()->currentmonsterhp != 0) redirect('/fight');
if (user()->currentfight == 0) redirect('/');
$monsterrow = get_monster(user()->currentmonster);
$min = (int)(($monsterrow["maxexp"] / 6) * 5);
$max = (int)$monsterrow["maxexp"];
$exp = mt_rand(min($min, $max), max($min, $max));
if ($exp < 1) { $exp = 1; }
if (user()->expbonus != 0) { $exp += ceil((user()->expbonus/100)*$exp); }
$min = (int)(($monsterrow["maxgold"] / 6) * 5);
$max = (int)$monsterrow["maxgold"];
$gold = mt_rand(min($min, $max), max($min, $max));
if ($gold < 1) { $gold = 1; }
if (user()->goldbonus != 0) { $gold += ceil((user()->goldbonus/100)*$exp); }
if (user()->experience + $exp < 16777215) { $newexp = user()->experience += $exp; $warnexp = ""; } else { $newexp = user()->experience; $exp = 0; $warnexp = "You have maxed out your experience points."; }
if (user()->gold + $gold < 16777215) { $newgold = user()->gold += $gold; $warngold = ""; } else { $newgold = user()->gold; $gold = 0; $warngold = "You have maxed out your gold."; }
$levelrow = db()->query('SELECT * FROM levels WHERE id=? LIMIT 1;', [user()->level + 1])->fetchArray(SQLITE3_ASSOC);
if (user()->level < 100) {
if ($newexp >= $levelrow[user()->charclass."_exp"]) {
user()->maxhp += $levelrow[user()->charclass."_hp"];
user()->maxmp += $levelrow[user()->charclass."_mp"];
user()->maxtp += $levelrow[user()->charclass."_tp"];
user()->strength += $levelrow[user()->charclass."_strength"];
user()->dexterity += $levelrow[user()->charclass."_dexterity"];
user()->attackpower += $levelrow[user()->charclass."_strength"];
user()->defensepower += $levelrow[user()->charclass."_dexterity"];
user()->level += 1;
$newlevel = $levelrow["id"];
if ($levelrow[user()->charclass."_spells"] != 0) {
user()->spells .= ",".$levelrow[user()->charclass."_spells"];
$spelltext = "You have learned a new spell.<br>";
} else { $spelltext = ""; $newspell=""; }
$page = "Congratulations. You have defeated the ".$monsterrow["name"].".<br>You gain $exp experience. $warnexp <br>You gain $gold gold. $warngold <br><br><b>You have gained a level!</b><br><br>You gain ".$levelrow[user()->charclass."_hp"]." hit points.<br>You gain ".$levelrow[user()->charclass."_mp"]." magic points.<br>You gain ".$levelrow[user()->charclass."_tp"]." travel points.<br>You gain ".$levelrow[user()->charclass."_strength"]." strength.<br>You gain ".$levelrow[user()->charclass."_dexterity"]." dexterity.<br>$spelltext<br>You can now continue <a href=\"/\" hx-get=\"/\" hx-target=\"#middle\">exploring</a>.";
$title = "Courage and Wit have served thee well!";
$dropcode = "";
} else {
$page = "Congratulations. You have defeated the ".$monsterrow["name"].".<br>You gain $exp experience. $warnexp <br>You gain $gold gold. $warngold <br><br>";
if (rand(1, 30) === 1) {
$droprow = db()->query('SELECT * FROM drops WHERE mlevel <= ? ORDER BY RANDOM() LIMIT 1;', [$monsterrow['level']])->fetchArray(SQLITE3_ASSOC);
$dropcode = "dropcode='".$droprow["id"]."',";
$page .= "This monster has dropped an item. <a href=\"/drop\" hx-get=\"/drop\" hx-target=\"#middle\">Click here</a> to reveal and equip the item, or you may also move on and continue <a href=\"/\" hx-get=\"/\" hx-target=\"#middle\">exploring</a>.";
} else {
$dropcode = "";
$page .= 'You can now continue <a href="/" hx-get="/" hx-target="#middle">exploring</a>.';
}
$title = "Victory!";
}
}
user()->currentaction = 'Exploring';
user()->currentfight = 0;
user()->currentuberdamage = 0;
user()->currentuberdefense = 0;
user()->currentmonstersleep = 0;
user()->currentmonsterimmune = 0;
user()->save();
page_title($title);
return $page;
}
function drop()
{
if (user()->dropcode == 0) redirect('/');
$droprow = get_drop(user()->dropcode);
if (isset($_POST["submit"])) {
$slot = $_POST["slot"];
if ($slot === 0) return 'Please go back and select an inventory slot to continue.';
$slotstr = 'slot'.$slot.'id';
if (user()->$slotstr != 0) {
$slotrow = get_drop(user()->$slotstr);
$old1 = explode(",",$slotrow["attribute1"]);
if ($slotrow["attribute2"] != "X") { $old2 = explode(",",$slotrow["attribute2"]); } else { $old2 = array(0=>"maxhp",1=>0); }
$new1 = explode(",",$droprow["attribute1"]);
if ($droprow["attribute2"] != "X") { $new2 = explode(",",$droprow["attribute2"]); } else { $new2 = array(0=>"maxhp",1=>0); }
user()->$old1[0] -= $old1[1];
user()->$old2[0] -= $old2[1];
if ($old1[0] == "strength") { user()->attackpower -= $old1[1]; }
if ($old1[0] == "dexterity") { user()->defensepower -= $old1[1]; }
if ($old2[0] == "strength") { user()->attackpower -= $old2[1]; }
if ($old2[0] == "dexterity") { user()->defensepower -= $old2[1]; }
user()->$new1[0] += $new1[1];
user()->$new2[0] += $new2[1];
if ($new1[0] == "strength") { user()->attackpower += $new1[1]; }
if ($new1[0] == "dexterity") { user()->defensepower += $new1[1]; }
if ($new2[0] == "strength") { user()->attackpower += $new2[1]; }
if ($new2[0] == "dexterity") { user()->defensepower += $new2[1]; }
if (user()->currenthp > user()->maxhp) { user()->currenthp = user()->maxhp; }
if (user()->currentmp > user()->maxmp) { user()->currentmp = user()->maxmp; }
if (user()->currenttp > user()->maxtp) { user()->currenttp = user()->maxtp; }
$slot_s = 'slot'.$_POST["slot"];
$slot_name = "{$slot_s}name";
$slot_id = "{$slot_s}id";
user()->$slot_name = $droprow['name'];
user()->$slot_id = $droprow['id'];
} else {
$new1 = explode(",",$droprow["attribute1"]);
if ($droprow["attribute2"] != "X") { $new2 = explode(",",$droprow["attribute2"]); } else { $new2 = array(0=>"maxhp",1=>0); }
user()->$new1[0] += $new1[1];
user()->$new2[0] += $new2[1];
if ($new1[0] == "strength") { user()->attackpower += $new1[1]; }
if ($new1[0] == "dexterity") { user()->defensepower += $new1[1]; }
if ($new2[0] == "strength") { user()->attackpower += $new2[1]; }
if ($new2[0] == "dexterity") { user()->defensepower += $new2[1]; }
$slot_s = 'slot'.$_POST["slot"];
$slot_name = "{$slot_s}name";
$slot_id = "{$slot_s}id";
user()->$slot_name = $droprow['name'];
user()->$slot_id = $droprow['id'];
}
user()->save();
return 'The item has been equipped. You can now continue <a href="/" hx-get="/" hx-target="#middle">exploring</a>.';
}
$attributearray = array("maxhp"=>"Max HP",
"maxmp"=>"Max MP",
"maxtp"=>"Max TP",
"defensepower"=>"Defense Power",
"attackpower"=>"Attack Power",
"strength"=>"Strength",
"dexterity"=>"Dexterity",
"expbonus"=>"Experience Bonus",
"goldbonus"=>"Gold Bonus");
$page = "The monster dropped the following item: <b>".$droprow["name"]."</b><br><br>";
$page .= "This item has the following attribute(s):<br>";
$attribute1 = explode(",",$droprow["attribute1"]);
$page .= $attributearray[$attribute1[0]];
if ($attribute1[1] > 0) { $page .= " +" . $attribute1[1] . "<br>"; } else { $page .= $attribute1[1] . "<br>"; }
if ($droprow["attribute2"] != "X") {
$attribute2 = explode(",",$droprow["attribute2"]);
$page .= $attributearray[$attribute2[0]];
if ($attribute2[1] > 0) { $page .= " +" . $attribute2[1] . "<br>"; } else { $page .= $attribute2[1] . "<br>"; }
}
$page .= "<br>Select an inventory slot from the list below to equip this item. If the inventory slot is already full, the old item will be discarded.";
$page .= "<form action=\"/drop\" method=\"post\"><select name=\"slot\"><option value=\"0\">Choose One</option><option value=\"1\">Slot 1: ".user()->slot1name."</option><option value=\"2\">Slot 2: ".user()->slot2name."</option><option value=\"3\">Slot 3: ".user()->slot3name."</option></select> <input type=\"submit\" name=\"submit\" value=\"Submit\" /></form>";
$page .= "You may also choose to just continue <a href=\"/\" hx-get=\"/\" hx-target=\"#middle\">exploring</a> and give up this item.";
return $page;
}
function dead()
{
return <<<HTML
<b>You have died.</b><br><br>
As a consequence, you've lost half of your gold. However, you have been given back a portion of your hit points
to continue your journey.<br><br>
You may now continue back to <a href="/" hx-get="/" hx-target="#middle">town</a>, and we hope you fair better next time.
HTML;
}
function handleMonsterTurn(&$userrow, $monsterrow)
{
$pagearray = "";
if (user()->currentmonstersleep != 0) {
$chancetowake = rand(1,15);
if ($chancetowake > user()->currentmonstersleep) {
user()->currentmonstersleep = 0;
$pagearray .= "The monster has woken up.<br>";
} else {
$pagearray .= "The monster is still asleep.<br>";
}
}
if (user()->currentmonstersleep == 0) {
$tohit = (int)ceil(mt_rand((int)($monsterrow["maxdam"] * 0.5), (int)$monsterrow["maxdam"]));
$toblock = (int)ceil(mt_rand((int)(user()->defensepower * 0.75), (int)user()->defensepower) / 4);
$tododge = rand(1, 150);
if ($tododge <= sqrt(user()->dexterity)) {
$tohit = 0;
$pagearray .= "You dodge the monster's attack. No damage has been scored.<br>";
$persondamage = 0;
} else {
$persondamage = max(1, $tohit - $toblock);
if (user()->currentuberdefense != 0) {
$persondamage -= (int)ceil($persondamage * (user()->currentuberdefense/100));
}
$persondamage = max(1, $persondamage);
}
$pagearray .= "The monster attacks you for $persondamage damage.<br><br>";
user()->currenthp -= $persondamage;
if (user()->currenthp <= 0) {
$newgold = (int)ceil(user()->gold/2);
$newhp = (int)ceil(user()->maxhp/4);
db()->query("UPDATE users SET currenthp=?, currentaction='In Town', currentmonster=0, currentmonsterhp=0, currentmonstersleep=0, currentmonsterimmune=0, currentfight=0, latitude=0, longitude=0, gold=? WHERE id=?;", [
$newhp, $newgold, $userrow['id']
]);
dead();
}
}
return $pagearray;
}
function handleSpellCast(&$userrow, $newspellrow)
{
$pagearray = "";
switch ($newspellrow["type"]) {
case 1: // Heal spell
$newhp = min(user()->currenthp + $newspellrow["attribute"], user()->maxhp);
user()->currenthp = $newhp;
user()->currentmp -= $newspellrow["mp"];
$pagearray = "You have cast the {$newspellrow["name"]} spell, and gained {$newspellrow["attribute"]} Hit Points.<br><br>";
break;
case 2: // Hurt spell
if (user()->currentmonsterimmune == 0) {
$monsterdamage = mt_rand((int)(($newspellrow["attribute"]/6)*5), $newspellrow["attribute"]);
user()->currentmonsterhp -= $monsterdamage;
$pagearray = "You have cast the {$newspellrow["name"]} spell for $monsterdamage damage.<br><br>";
} else {
$pagearray = "You have cast the {$newspellrow["name"]} spell, but the monster is immune to it.<br><br>";
}
user()->currentmp -= $newspellrow["mp"];
break;
case 3: // Sleep spell
if (user()->currentmonsterimmune != 2) {
user()->currentmonstersleep = $newspellrow["attribute"];
$pagearray = "You have cast the {$newspellrow["name"]} spell. The monster is asleep.<br><br>";
} else {
$pagearray = "You have cast the {$newspellrow["name"]} spell, but the monster is immune to it.<br><br>";
}
user()->currentmp -= $newspellrow["mp"];
break;
case 4: // +Damage spell
user()->currentuberdamage = $newspellrow["attribute"];
user()->currentmp -= $newspellrow["mp"];
$pagearray = "You have cast the {$newspellrow["name"]} spell, and will gain {$newspellrow["attribute"]}% damage until the end of this fight.<br><br>";
break;
case 5: // +Defense spell
user()->currentuberdefense = $newspellrow["attribute"];
user()->currentmp -= $newspellrow["mp"];
$pagearray = "You have cast the {$newspellrow["name"]} spell, and will gain {$newspellrow["attribute"]}% defense until the end of this fight.<br><br>";
break;
}
return $pagearray;
}

View File

@ -1,115 +0,0 @@
<?php
// forum.php :: Internal forums script for the game.
namespace Forum;
use Router;
function register_routes(Router $r): Router
{
$r->get('/forum/thread/:x/:x', 'Forum\showthread');
$r->form('/forum/new', 'Forum\newthread');
$r->post('/forum/reply', 'Forum\reply');
$r->get('/forum/list/:x', 'Forum\donothing');
$r->get('/forum', 'Forum\donothing');
return $r;
}
function donothing($start = 0)
{
$query = db()->query('SELECT * FROM forum WHERE parent=0 ORDER BY newpostdate DESC LIMIT 20 OFFSET ?;', [20 * $start]);
$page = <<<HTML
<table width="100%">
<tr>
<td style="padding: 1px; background-color: black;">
<table width="100%" style="margins: 0px;" cellspacing="1" cellpadding="3">
<tr>
<th colspan="3" style="background-color: #ddd;">
<center><a href="/forum/new" hx-get="/forum/new" hx-target="#middle">New Thread</a></center>
</th>
</tr>
<tr>
<th width="50%" style="background-color:#dddddd;">Thread</th>
<th width="10%" style="background-color:#dddddd;">Replies</th>
<th style="background-color:#dddddd;">Last Post</th>
</tr>
HTML;
$hasRows = false;
while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
$hasRows = true;
$page .= <<<HTML
<tr>
<td style="background-color: white;"><a href="/forum/thread/{$row['id']}/0" hx-get="/forum/thread/{$row['id']}/0" hx-target="#middle">{$row['title']}</a></td>
<td style="background-color: white;">{$row['replies']}</td>
<td style="background-color: white;">{$row['newpostdate']}</td>
</tr>
HTML;
}
if (!$hasRows) {
$page .= '<tr><td style="background-color:#ffffff;" colspan="3"><b>No threads in forum.</b></td></tr>';
}
$page .= '</table></td></tr></table>';
page_title('Forum');
return $page;
}
function showthread($id, $start)
{
$posts = db()->query('SELECT * FROM forum WHERE id=? OR parent=? ORDER BY id LIMIT 15 OFFSET ?;', [$id, $id, $start * 15]);
$title = db()->query('SELECT title FROM forum WHERE id=? LIMIT 1;', [$id])->fetchArray(SQLITE3_ASSOC);
$page = "<table width=\"100%\"><tr><td style=\"padding:1px; background-color:black;\"><table width=\"100%\" style=\"margins:0px;\" cellspacing=\"1\" cellpadding=\"3\"><tr><td colspan=\"2\" style=\"background-color:#dddddd;\"><b><a href=\"/forum\" hx-get=\"/forum\" hx-target=\"#middle\">Forum</a> :: ".$title['title']."</b></td></tr>\n";
while ($row = $posts->fetchArray(SQLITE3_ASSOC)) {
$page .= "<tr><td width=\"25%\" style=\"background-color:#ffffff; vertical-align:top;\"><span class=\"small\"><b>".$row["author"]."</b><br><br>".pretty_date($row["postdate"])."</td><td style=\"background-color:#ffffff; vertical-align:top;\">".nl2br($row["content"])."</td></tr>\n";
}
$page .= "</table></td></tr></table><br>";
$page .= "<table width=\"100%\"><tr><td><b>Reply To This Thread:</b><br><form action=\"/forum/reply\" method=\"post\" hx-post=\"/forum/reply\" hx-target=\"#middle\"><input type=\"hidden\" name=\"parent\" value=\"$id\" /><input type=\"hidden\" name=\"title\" value=\"Re: ".$title["title"]."\" /><textarea name=\"content\" rows=\"7\" cols=\"40\"></textarea><br><input type=\"submit\" name=\"submit\" value=\"Submit\" /> <input type=\"reset\" name=\"reset\" value=\"Reset\" /></form></td></tr></table>";
page_title('Forum: '.$title['title']);
return $page;
}
function reply()
{
$form = validate($_POST, [
'title' => [],
'content' => []
]);
if (!$form['valid']) exit(ul_from_validate_errors($form['errors']));
$form = $form['data'];
db()->query('INSERT INTO forum (author, title, content, parent) VALUES (?, ?, ?, ?);', [
user()->username, $form['title'], $form['content'], $form['parent']
]);
db()->query('UPDATE forum SET newpostdate=CURRENT_TIMESTAMP, replies=replies + 1 WHERE id=?;', [$form['parent']]);
return showthread($form['parent'], 0);
}
function newthread()
{
if (isset($_POST["submit"])) {
$form = validate($_POST, [
'title' => ['length:2-30'],
'content' => []
]);
if (!$form['valid']) exit(ul_from_validate_errors($form['errors']));
$form = $form['data'];
db()->query('INSERT INTO forum (author, title, content) VALUES (?, ?, ?);', [
user()->username, $form['title'], $form['content']
]);
redirect('/forum/thread/'.db()->lastInsertRowID().'/0');
}
page_title('Form: New Thread');
return "<table width=\"100%\"><tr><td><b>Make A New Post:</b><br><br/ ><form action=\"/forum/new\" method=\"post\" hx-post=\"/forum/new\" hx-target=\"#middle\">Title:<br><input type=\"text\" name=\"title\" size=\"50\" maxlength=\"50\" /><br><br>Message:<br><textarea name=\"content\" rows=\"7\" cols=\"40\"></textarea><br><br><input type=\"submit\" name=\"submit\" value=\"Submit\" /> <input type=\"reset\" name=\"reset\" value=\"Reset\" /></form></td></tr></table>";
}

View File

@ -1,34 +0,0 @@
<?php
// heal.php :: Handles stuff from the Quick Spells menu. (Healing spells only... other spells are handled in fight.php.)
function healspells(int $id): string
{
$user_spells = user()->spells();
$spell = get_spell($id);
$has_spell = false;
foreach ($user_spells as $us) if ($us['id'] === $id) $has_spell = true;
if ($has_spell !== true) {
$page = 'You have not yet learned this spell. Please go back and try again.';
} elseif ($spell['type'] !== 1) {
$page = 'This is not a healing spell. Please go back and try again.';
} elseif (user()->currentmp < $spell['mp']) {
$page = 'You do not have enough Magic Points to cast this spell. Please go back and try again.';
} elseif (user()->currentaction === 'Fighting') {
$page = 'You cannot use the Quick Spells list during a fight. Please go back and select the Healing Spell you wish to use from the Spells box on the main fighting screen to continue.';
} elseif (user()->currenthp == user()->maxhp) {
$page = 'Your HP is already full. You don\'t need to use a Healing spell now.';
} else {
$restored = user()->restore_hp($spell['attribute']);
user()->currentmp -= $spell['mp'];
user()->save();
$page = <<<HTML
You have cast the {$spell['name']} spell, and gained {$restored} HP. You can now continue <a href="/" hx-get="/" hx-target="#middle">exploring</a>.
HTML;
}
page_title('Casting '.$spell['name']);
return $page;
}

View File

@ -1,494 +0,0 @@
<?php
namespace Help;
use Router;
function register_routes(Router $r): Router
{
$r->get('/help', 'Help\main');
$r->get('/help/items', 'Help\items');
$r->get('/help/spells', 'Help\spells');
$r->get('/help/monsters', 'Help\monsters');
$r->get('/help/levels', 'Help\levels');
return $r;
}
function main()
{
$page = <<<HTML
<h3>Table of Contents</h3>
<ul>
<li><a href="#intro">Introduction</a></li>
<li><a href="#classes">Character Classes</a></li>
<li><a href="#intown">Playing The Game: In Town</a></li>
<li><a href="#exploring">Playing The Game: Exploring & Fighting</a></li>
<li><a href="#status">Playing The Game: Status Panels</a></li>
<li><a href="#items">Spoilers: Items & Drops</a></li>
<li><a href="#monsters">Spoilers: Monsters</a></li>
<li><a href="#spells">Spoilers: Spells</a></li>
<li><a href="#levels">Spoilers: Levels</a></li>
<li><a href="#credits">Credits</a></li>
</ul>
<hr>
<h3><a name="intro"></a>Introduction</h3>
Firstly, I'd like to say thank you for playing my game. The <i>Dragon Knight</i> game engine is the result of several months of
planning, coding and testing. The original idea was to create a web-based tribute to the NES game, <i>Dragon
Warrior</i>. In its current iteration, only the underlying fighting system really resembles that game, as almost
everything else in DK has been made bigger and better. But you should still recognize bits and pieces as stemming
from <i>Dragon Warrior</i> and other RPGs of old.<br><br>
This is the first game I've ever written, and it has definitely been a positive experience. It got difficult at
times, admittedly, but it was still a lot of fun to write, and even more fun to play. And I hope to use this
experience so that if I ever want to create another game it will be even better than this one.<br><br>
If you are a site administrator, and would like to install a copy of DK on your own server, you may visit the
<a href="http://dragon.se7enet.com/dev.php" target="_new">development site</a> for <i>Dragon Knight</i>. This page
includes the downloadable game souce code, as well as some other resources that developers and administrators may
find valuable.<br><br>
Once again, thanks for playing!<br><br>
<i>Jamin Seven</i><br>
<i>Dragon Knight creator</i><br>
<a href="http://www.se7enet.com" target="_new">My Homepage</a><br>
<a href="http://dragon.se7enet.com/dev.php" target="_new">Dragon Knight Homepage</a><br ><br>
[ <a href="#top">Top</a> ]
<br><br><hr>
<h3><a name="classes"></a>Character Classes</h3>
There are three character classes in the game. The main differences between the classes are what spells you get
access to, the speed with which you level up, and the amount of HP/MP/strength/dexterity you gain per level. Below
is a basic outline of each of the character classes. For more detailed information about the characters, please
view the Levels table at the bottom of this page. Also, note that the outline below refers to the stock class setup
for the game. If your administrator has used his/her own class setup, this information may not be accurate.<br><br>
<b>{env('class_1_name')}</b>
<ul>
<li>Fast level-ups</li>
<li>High hit points</li>
<li>High magic points</li>
<li>Low strength</li>
<li>Low dexterity</li>
<li>5 heal spells</li>
<li>5 hurt spells</li>
<li>3 sleep spells</li>
<li>3 +defense spells</li>
<li>0 +attack spells</li>
</ul>
<b>{env('class_2_name')}</b>
<ul>
<li>Medium level-ups</li>
<li>Medium hit points</li>
<li>Low magic points</li>
<li>High strength</li>
<li>Low dexterity</li>
<li>3 heal spells</li>
<li>3 hurt spells</li>
<li>2 sleep spells</li>
<li>3 +defense spells</li>
<li>3 +attack spells</li>
</ul>
<b>{env('class_3_name')}</b>
<ul>
<li>Slow level-ups</li>
<li>Medium hit points</li>
<li>Medium magic points</li>
<li>Low strength</li>
<li>High dexterity</li>
<li>4 heal spells</li>
<li>4 hurt spells</li>
<li>3 sleep spells</li>
<li>2 +defense spells</li>
<li>2 +attack spells</li>
</ul>
[ <a href="#top">Top</a> ]
<br><br><hr>
<h3><a name="intown"></a>Playing The Game: In Town</h3>
When you begin a new game, the first thing you see is the Town screen. Towns serve four primary functions: healing, buying items,
buying maps, and displaying game information.<br><br>
To heal yourself, click the "Rest at the Inn" link at the top of the town screen. Each town's Inn has a different price - some towns
are cheap, others are expensive. No matter what town you're in, the Inns always serve the same function: they restore your current
hit points, magic points, and travel points to their maximum amounts. Out in the field, you are free to use healing spells to restore
your hit points, but when you run low on magic points, the only way to restore them is at an Inn.<br><br>
Buying weapons and armor is accomplished through the appropriately-named "Buy Weapons/Armor" link. Not every item is available in
every town, so in order to get the most powerful items, you'll need to explore some of the outer towns. Once you've clicked the link,
you are presented with a list of items available in this town's store. To the left of each item is an icon that represents its type:
weapon, armor or shield. The amount of attack/defense power, as well as the item's price, are displayed to the right of the item name.
You'll notice that some items have a red asterisk (<span class="highlight">*</span>) next to their names. These are items that come
with special attributes that modify other parts of your character profile. See the Items & Drops table at the bottom of this page for
more information about special items.<br><br>
Maps are the third function in towns. Buying a map to a town places the town in your Travel To box in the left status panel. Once
you've purchased a town's map, you can click its name from your Travel To box and you will jump to that town. Travelling this way
costs travel points, though, and you'll only be able to visit towns if you have enough travel points.<br><br>
The final function in towns is displaying game information and statistics. This includes the latest news post made by the game
administrator, a list of players who have been online recently, and the Babble Box.<br><br>
[ <a href="#top">Top</a> ]
<br><br><hr>
<h3><a name="exploring"></a>Playing The Game: Exploring & Fighting</h3>
Once you're done in town, you are free to start exploring the world. Use the compass buttons on the left status panel to move around.
The game world is basically a big square, divided into four quadrants. Each quadrant is {{gamesize}} spaces
square. The first town is usually located at (0N,0E). Click the North button from the first town, and now you'll be at (1N,0E).
Likewise, if you now click the West button, you'll be at (1N,1W). Monster levels increase with every 5 spaces you move outward
from (0N,0E).<br><br>
While you're exploring, you will occasionally run into monsters. As in pretty much any other RPG game, you and the monster take turns
hitting each other in an attempt to reduce each other's hit points to zero. Once you run into a monster, the Exploring screen changes
to the Fighting screen.<br><br>
When a fight begins, you'll see the monster's name and hit points, and the game will ask you for your first command. You then get to
pick whether you want to fight, use a spell, or run away. Note, though, that sometimes the monster has the chance to hit you
first.<br><br>
The Fight button is pretty straightforward: you attack the monster, and the amount of damage dealt is based on your attack power and
the monster's armor. On top of that, there are two other things that can happen: an Excellent Hit, which doubles your total attack
damage; and a monster dodge, which results in you doing no damage to the monster.<br><br>
The Spell button allows you to pick an available spell and cast it. See the Spells list at the bottom of this page for more information
about spells.<br><br>
Finally, there is the Run button, which lets you run away from a fight if the monster is too powerful. Be warned, though: it is
possible for the monster to block you from running and attack you. So if your hit points are low, you may fare better by staying
around monsters that you know can't do much damage to you.<br><br>
Once you've had your turn, the monster also gets his turn. It is also possible for you to dodge the monster's attack and take no
damage.<br><br>
The end result of a fight is either you or the monster being knocked down to zero hit points. If you win, the monster dies and will
give you a certain amount of experience and gold. There is also a chance that the monster will drop an item, which you can put into
one of the three inventory slots to give you extra points in your character profile. If you lose and die, half of your gold is taken
away - however, you are given back a few hit points to help you make it back to town (for example, if you don't have enough gold to
pay for an Inn, and need to kill a couple low-level monsters to get the money).<br><br>
When the fight is over, you can continue exploring until you find another monster to beat into submission.<br><br>
[ <a href="#top">Top</a> ]
<br><br><hr>
<h3><a name="status"></a>Playing The Game: Status Panels</h3>
There are two status panels on the game screen: left and right.<br><br>
The left panel inclues your current location and play status (In Town, Exploring, Fighting), compass buttons for movement, and the
Travel To list for jumping between towns. At the bottom of the left panel is also a list of game functions.<br><br>
The right panel displays some character statistics, your inventory, and quick spells.<br><br>
The Character section shows the most important character statistics. It also displays the status bars for your current hit points,
magic points and travel points. These status bars are colored either green, yellow or red depending on your current amount of each
stat. There is also a link to pop up your list of extended statistics, which shows more detailed character information.<br><br>
The Fast Spells section lists any Heal spells you've learned. You may use these links any time you are in town or exploring to cast
the heal spell. These may not be used during fights, however - you have to use the Spells box on the fight screen for that.
[ <a href="#top">Top</a> ]
<br><br><hr>
<h3><a name="items"></a>Spoilers: Items & Drops</h3>
<a href="/help/items">Click here</a> for the Items & Drops spoiler page.<br><br>
[ <a href="#top">Top</a> ]
<br><br><hr>
<h3><a name="monsters"></a>Spoilers: Monsters</h3>
<a href="/help/monsters">Click here</a> for the Monsters spoiler page.<br><br>
[ <a href="#top">Top</a> ]
<br><br><hr>
<h3><a name="spells"></a>Spoilers: Spells</h3>
<a href="/help/spells">Click here</a> for the Spells spoiler page.<br><br>
[ <a href="#top">Top</a> ]
<br><br><hr>
<h3><a name="levels"></a>Spoilers: Levels</h3>
<a href="/help/levels">Click here</a> for the Levels spoiler page.<br><br>
[ <a href="#top">Top</a> ]
<br><br><hr>
<h3><a name="credits"></a>Credits</h3>
<ul>
<li><b>All program code and stock graphics for the game were created by Jamin Seven</b>.<br><br></li>
<li>Major props go to a few people on the PHP manual site, for help with various chunks of code. The specific people are listed in the source code.<br><br></li>
<li>Super monkey love goes to Enix and the developers of <i>Dragon Warrior</i>. If it weren't for you guys, my game never would have been made.<br><br></li>
<li>Mega props go to Dalez from GameFAQs for his DW3 experience chart, which was where I got my experience levels from.<br><br></li>
<li>
Mad crazy ninja love goes to the following people for help and support throughout the development process:<br><br>
<b>Ideas:</b> (whether they got used or not)
<ul>
<li>kushet</li>
<li>lghtning</li>
<li>Ebolamonkey3000</li>
<li>Crimson Scythe</li>
<li>SilDeath</li>
</ul>
<b>Beta Testing:</b> (forums name if applicable, character name otherwise)
<ul>
<li>Ebolamonkey3000</li>
<li>lisi</li>
<li>Junglist</li>
<li>Crimson Scythe</li>
<li>Sk8erpunk69</li>
<li>lghtning</li>
<li>kushet</li>
<li>SilDeath</li>
<li>lowrider4life</li>
<li>dubiin</li>
<li>Sam Wise The Great</li>
</ul>
</li>
</ul>
Apologies and lots of happy naked love to anyone I forgot. <br><br>
And of course, thanks to <b>you</b> for playing my game! <br><br>
<a href="/ninja">NINJA!</a> <br><br>
[ <a href="#top">Top</a> ]
<br><br><hr><br>
Please visit the following sites for more information:<br>
<a href="http://www.se7enet.com" target="_new">Se7enet</a> (Jamin's homepage)<br>
<a href="http://dragon.se7enet.com/dev.php" target="_new">Dragon Knight</a> (official DK homepage)<br>
<a href="http://se7enet.com/forums" target="_new">Forums</a> (official DK forums)<br><br>
All original coding and graphics for the <i>Dragon Knight</i> game engine are &copy; 2003-2005 by Jamin Seven.<br><br>
[ <a href="#top">Top</a> ]
HTML;
return display_help($page);
}
function items()
{
$page = <<<HTML
<table width="60%" style="border: solid 1px black" cellspacing="0" cellpadding="0">
<tr><td colspan="5" bgcolor="#ffffff"><center><b>Items</b></center></td></tr>
<tr><td><b>Type</b></td><td><b>Name</b></td><td><b>Cost</b></td><td><b>Attribute</b></td><td><b>Special</b></td></tr>
HTML;
$items = db()->query('SELECT * FROM items ORDER BY id;');
$item_types = [1 => ['weapon', 'Attack'], 2 => ['armor', 'Defense'], 3 => ['shield', 'Defense']];
while ($item = $items->fetchArray(SQLITE3_ASSOC)) {
$image = $item_types[$item['type']][0];
$power = $item_types[$item['type']][1];
if ($item['special'] !== 'X') {
$special = explode(',', $item['special']);
$attr = special_to_string($special[0]);
$stat = (($special[1] > 0) ? '+' : '') . $special[1];
$bigspecial = "$attr $stat";
} else {
$bigspecial = '<span class="light">None</span>';
}
$page .= "<tr><td width=\"5%\"><img src=\"/img/icon_$image.gif\" alt=\"$image\"></td><td width=\"30%\">".$item["name"]."</td><td width=\"20%\">".$item["buycost"]." Gold</td><td width=\"20%\">".$item["attribute"]." $power Power</td><td width=\"25%\">$bigspecial</td></tr>\n";
}
$page .= <<<HTML
</table>
<br><br>
<table width="60%" style="border: solid 1px black" cellspacing="0" cellpadding="0">
<tr><td colspan="4" bgcolor="#ffffff"><center><b>Drops</b></center></td></tr>
<tr><td><b>Name</b></td><td><b>Monster Level</b></td><td><b>Attribute 1</b></td><td><b>Attribute 2</b></td></tr>
HTML;
$drops = db()->query('SELECT * FROM drops ORDER BY id;');
while ($drop = $drops->fetchArray(SQLITE3_ASSOC)) {
if ($drop["attribute1"] !== "X") {
$special = explode(',', $drop['attribute1']);
$attr = special_to_string($special[0]);
$stat = (($special[1] > 0) ? '+' : '') . $special[1];
$bigspecial1 = "$attr $stat";
} else {
$bigspecial1 = '<span class="light">None</span>';
}
if ($drop["attribute2"] !== "X") {
$special = explode(',', $drop['attribute2']);
$attr = special_to_string($special[0]);
$stat = (($special[1] > 0) ? '+' : '') . $special[1];
$bigspecial2 = "$attr $stat";
} else {
$bigspecial2 = '<span class="light">None</span>';
}
$page .= "<tr><td width=\"25%\">".$drop["name"]."</td><td width=\"15%\">".$drop["mlevel"]."</td><td width=\"30%\">$bigspecial1</td><td width=\"30%\">$bigspecial2</td></tr>\n";
}
$page .= '</table>';
return display_help($page);
}
function spells()
{
$page = <<<HTML
<table width="50%" style="border: solid 1px black" cellspacing="0" cellpadding="0">
<tr><td colspan="8" bgcolor="#ffffff"><center><b>Spells</b></center></td></tr>
<tr><td><b>Name</b></td><td><b>Cost</b></td><td><b>Type</b></td><td><b>Attribute</b></td></tr>
HTML;
$spells = db()->query('SELECT * FROM spells ORDER BY id;');
$spell_types = ['None', 'Heal', 'Hurt', 'Sleep', '+Damage (%)', '+Defense (%)'];
while ($spell = $spells->fetchArray(SQLITE3_ASSOC)) {
$page .= <<<HTML
<tr><td width="25%">{$spell["name"]}</td>
<td width="25%">{$spell["mp"]}</td>
<td width="25%">{$spell_types[$spell['type']]}</td>
<td width="25%">{$spell["attribute"]}</td></tr>
HTML;
}
$page .= <<<HTML
</table>
<ul>
<li><b>Heal</b> spells always give you the maximum amount possible, until your current HP is full.</li>
<li><b>Hurt</b> spells deal X damage (not always the maximum) to the monster, regardless of the monster's armor.</li>
<li><b>Sleep</b> spells put the monster to sleep. The monster has an X in 15 chance of remaining asleep each turn.</li>
<li><b>+Damage</b> spells increase your total attack damage by X percent until the end of the fight.</li>
<li><b>+Defense</b> spells reduce the total damage you take from the monster by X percent until the end of each fight.</li>
</ul>
HTML;
return display_help($page);
}
function monsters()
{
$page = <<<HTML
<table width="75%" style="border: solid 1px black" cellspacing="0" cellpadding="0">
<tr><td colspan="8" bgcolor="#ffffff"><center><b>Monsters</b></center></td></tr>
<tr><td><b>Name</b></td><td><b>Max HP</b></td><td><b>Max Damage</b></td><td><b>Armor</b></td><td><b>Level</b></td><td><b>Max Exp.</b></td><td><b>Max Gold</b></td><td><b>Immunity</b></td></tr>
HTML;
$monsters = db()->query('SELECT * FROM monsters ORDER BY id;');
$immunities = ['<span class="light">None</span>', 'Hurt', 'Hurt & Sleep'];
while ($m = $monsters->fetchArray(SQLITE3_ASSOC)) {
$immune = $immunities[$m['immune']] ?? 'Unknown';
$page .= "<tr><td width=\"30%\">".$m["name"]."</td><td width=\"10%\">".$m["maxhp"]."</td><td width=\"10%\">".$m["maxdam"]."</td><td width=\"10%\">".$m["armor"]."</td><td width=\"10%\">".$m["level"]."</td><td width=\"10%\">".$m["maxexp"]."</td><td width=\"10%\">".$m["maxgold"]."</td><td width=\"20%\">$immune</td></tr>\n";
}
return display_help($page.'</table>');
}
function levels()
{
$rows = [];
$levels = db()->query('SELECT * FROM levels ORDER BY id;');
while ($level = $levels->fetchArray(SQLITE3_ASSOC)) {
$class_data = [1 => [], 2 => [], 3 => []];
foreach ($level as $column => $value) {
if ($column === 'id') continue;
$parts = explode('_', $column);
$class_number = (int) $parts[0];
$attribute = $parts[1];
if (in_array($class_number, [1, 2, 3])) {
$class_data[$class_number][$level['id']][$attribute] = $value;
}
}
$rows[$level['id']] = $class_data;
}
$spells = [];
$spells_query = db()->query('SELECT * FROM spells ORDER BY id;');
while ($spell = $spells_query->fetchArray(SQLITE3_ASSOC)) {
$spells[$spell['id']] = $spell;
}
$page = <<<HTML
<table width="50%" style="border: solid 1px black" cellspacing="0" cellpadding="0">
<tr><td colspan="8" bgcolor="#ffffff"><center><b>{{class1name}} Levels</b></center></td></tr>
<tr><td><b>Level</b><td><b>Exp.</b></td><td><b>HP</b></td><td><b>MP</b></td><td><b>TP</b></td><td><b>Strength</b></td><td><b>Dexterity</b></td><td><b>Spell</b></td></tr>
HTML;
foreach ($rows as $level => $class_data) {
$level_data = $class_data[1][$level];
$spell_name = '';
if (!empty($level_data['spells'])) $spell_name = $spells[$level_data['spells']]['name'];
$page .= '<tr>';
$page .= '<td>' . $level . '</td>';
$page .= '<td>' . ($level_data['exp'] ?? '') . '</td>';
$page .= '<td>' . ($level_data['hp'] ?? '') . '</td>';
$page .= '<td>' . ($level_data['mp'] ?? '') . '</td>';
$page .= '<td>' . ($level_data['tp'] ?? '') . '</td>';
$page .= '<td>' . ($level_data['strength'] ?? '') . '</td>';
$page .= '<td>' . ($level_data['dexterity'] ?? '') . '</td>';
$page .= '<td>' . (!empty($spell_name) ? $spell_name : '<span class="light">None</span>') . '</td>';
$page .= '</tr>';
}
$page .= <<<HTML
</table>
<br><br>
<table width="50%" style="border: solid 1px black" cellspacing="0" cellpadding="0">
<tr><td colspan="8" bgcolor="#ffffff"><center><b>{{class2name}} Levels</b></center></td></tr>
<tr><td><b>Level</b><td><b>Exp.</b></td><td><b>HP</b></td><td><b>MP</b></td><td><b>TP</b></td><td><b>Strength</b></td><td><b>Dexterity</b></td><td><b>Spell</b></td></tr>
HTML;
foreach ($rows as $level => $class_data) {
$level_data = $class_data[2][$level];
$spell_name = '';
if (!empty($level_data['spells'])) $spell_name = $spells[$level_data['spells']]['name'];
$page .= '<tr>';
$page .= '<td>' . $level . '</td>';
$page .= '<td>' . ($level_data['exp'] ?? '') . '</td>';
$page .= '<td>' . ($level_data['hp'] ?? '') . '</td>';
$page .= '<td>' . ($level_data['mp'] ?? '') . '</td>';
$page .= '<td>' . ($level_data['tp'] ?? '') . '</td>';
$page .= '<td>' . ($level_data['strength'] ?? '') . '</td>';
$page .= '<td>' . ($level_data['dexterity'] ?? '') . '</td>';
$page .= '<td>' . (!empty($spell_name) ? $spell_name : '<span class="light">None</span>') . '</td>';
$page .= '</tr>';
}
$page .= <<<HTML
</table>
<br><br>
<table width="50%" style="border: solid 1px black" cellspacing="0" cellpadding="0">
<tr><td colspan="8" bgcolor="#ffffff"><center><b>{{class3name}} Levels</b></center></td></tr>
<tr><td><b>Level</b><td><b>Exp.</b></td><td><b>HP</b></td><td><b>MP</b></td><td><b>TP</b></td><td><b>Strength</b></td><td><b>Dexterity</b></td><td><b>Spell</b></td></tr>
HTML;
foreach ($rows as $level => $class_data) {
$level_data = $class_data[3][$level];
$spell_name = '';
if (!empty($level_data['spells'])) $spell_name = $spells[$level_data['spells']]['name'];
$page .= '<tr>';
$page .= '<td>' . $level . '</td>';
$page .= '<td>' . ($level_data['exp'] ?? '') . '</td>';
$page .= '<td>' . ($level_data['hp'] ?? '') . '</td>';
$page .= '<td>' . ($level_data['mp'] ?? '') . '</td>';
$page .= '<td>' . ($level_data['tp'] ?? '') . '</td>';
$page .= '<td>' . ($level_data['strength'] ?? '') . '</td>';
$page .= '<td>' . ($level_data['dexterity'] ?? '') . '</td>';
$page .= '<td>' . (!empty($spell_name) ? $spell_name : '<span class="light">None</span>') . '</td>';
$page .= '</tr>';
}
$page .= <<<HTML
</table>
<br>
Experience points listed are total values up until that point. All other values are just the new amount that you gain for each level.
HTML;
return display_help($page);
}
function display_help(string $content)
{
return render('layouts/help', [
'content' => $content,
'version' => VERSION,
'build' => BUILD
]);
}

View File

@ -1,767 +0,0 @@
<?php
namespace Install;
use Router;
function register_routes(Router $r): Router
{
if (!file_exists('../.installed')) {
$r->get('/install', 'Install\first');
$r->get('/install/second', 'Install\second');
$r->get('/install/third', 'Install\third');
$r->post('/install/fourth', 'Install\fourth');
$r->get('/install/fifth', 'Install\fifth');
}
return $r;
}
/**
* First page - show warnings and gather info
*/
function first()
{
return <<<HTML
<html>
<head>
<title>Dragon Knight Installation</title>
</head>
<body>
<b>Dragon Knight Installation: Page One</b><br><br>
Installation for Dragon Knight is a simple two-step process: set up the database tables, then create the admin user. After that, you're done.<br><br>
<a href="/install/second"><button>Install</button></a>
</body>
</html>
HTML;
}
/**
* Set up database tables.
*/
function second()
{
if (file_exists('../database.db')) unlink('../database.db');
$page = "<html><head><title>Dragon Knight Installation</title></head><body><b>Dragon Knight Installation: Page Two</b><br><br>";
$query = db()->exec(<<<SQL
CREATE TABLE babble (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`posttime` TEXT NOT NULL DEFAULT '00:00:00',
`author` TEXT NOT NULL DEFAULT '',
`babble` TEXT NOT NULL DEFAULT ''
);
SQL);
$page .= table_status_msg($query === true, 'Babble', 'create');
$query = db()->exec(<<<SQL
CREATE TABLE drops (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` TEXT NOT NULL DEFAULT '',
`mlevel` INTEGER NOT NULL DEFAULT 0,
`type` INTEGER NOT NULL DEFAULT 0,
`attribute1` TEXT NOT NULL DEFAULT '',
`attribute2` TEXT NOT NULL DEFAULT ''
);
SQL);
$page .= table_status_msg($query === true, 'Drops', 'create');
$query = db()->exec(<<<SQL
INSERT INTO drops VALUES
(1, 'Life Pebble', 1, 1, 'maxhp,10', 'X'),
(2, 'Life Stone', 10, 1, 'maxhp,25', 'X'),
(3, 'Life Rock', 25, 1, 'maxhp,50', 'X'),
(4, 'Magic Pebble', 1, 1, 'maxmp,10', 'X'),
(5, 'Magic Stone', 10, 1, 'maxmp,25', 'X'),
(6, 'Magic Rock', 25, 1, 'maxmp,50', 'X'),
(7, 'Dragon''s Scale', 10, 1, 'defensepower,25', 'X'),
(8, 'Dragon''s Plate', 30, 1, 'defensepower,50', 'X'),
(9, 'Dragon''s Claw', 10, 1, 'attackpower,25', 'X'),
(10, 'Dragon''s Tooth', 30, 1, 'attackpower,50', 'X'),
(11, 'Dragon''s Tear', 35, 1, 'strength,50', 'X'),
(12, 'Dragon''s Wing', 35, 1, 'dexterity,50', 'X'),
(13, 'Demon''s Sin', 35, 1, 'maxhp,-50', 'strength,50'),
(14, 'Demon''s Fall', 35, 1, 'maxmp,-50', 'strength,50'),
(15, 'Demon''s Lie', 45, 1, 'maxhp,-100', 'strength,100'),
(16, 'Demon''s Hate', 45, 1, 'maxmp,-100', 'strength,100'),
(17, 'Angel''s Joy', 25, 1, 'maxhp,25', 'strength,25'),
(18, 'Angel''s Rise', 30, 1, 'maxhp,50', 'strength,50'),
(19, 'Angel''s Truth', 35, 1, 'maxhp,75', 'strength,75'),
(20, 'Angel''s Love', 40, 1, 'maxhp,100', 'strength,100'),
(21, 'Seraph''s Joy', 25, 1, 'maxmp,25', 'dexterity,25'),
(22, 'Seraph''s Rise', 30, 1, 'maxmp,50', 'dexterity,50'),
(23, 'Seraph''s Truth', 35, 1, 'maxmp,75', 'dexterity,75'),
(24, 'Seraph''s Love', 40, 1, 'maxmp,100', 'dexterity,100'),
(25, 'Ruby', 50, 1, 'maxhp,150', 'X'),
(26, 'Pearl', 50, 1, 'maxmp,150', 'X'),
(27, 'Emerald', 50, 1, 'strength,150', 'X'),
(28, 'Topaz', 50, 1, 'dexterity,150', 'X'),
(29, 'Obsidian', 50, 1, 'attackpower,150', 'X'),
(30, 'Diamond', 50, 1, 'defensepower,150', 'X'),
(31, 'Memory Drop', 5, 1, 'expbonus,10', 'X'),
(32, 'Fortune Drop', 5, 1, 'goldbonus,10', 'X');
SQL);
$page .= table_status_msg($query === true, 'Drops', 'populate');
$query = db()->exec(<<<SQL
CREATE TABLE forum (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`postdate` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`newpostdate` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`author` TEXT NOT NULL DEFAULT '',
`parent` INTEGER NOT NULL DEFAULT 0,
`replies` INTEGER NOT NULL DEFAULT 0,
`title` TEXT NOT NULL DEFAULT '',
`content` TEXT NOT NULL
);
SQL);
$page .= table_status_msg($query === true, 'Forum', 'create');
$query = db()->exec(<<<SQL
CREATE TABLE items (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`type` INTEGER NOT NULL DEFAULT 0,
`name` TEXT NOT NULL DEFAULT '',
`buycost` INTEGER NOT NULL DEFAULT 0,
`attribute` INTEGER NOT NULL DEFAULT 0,
`special` TEXT NOT NULL DEFAULT ''
);
SQL);
$page .= table_status_msg($query === true, 'Items', 'create');
$query = db()->exec(<<<SQL
INSERT INTO items VALUES
(1, 1, 'Stick', 10, 2, 'X'),
(2, 1, 'Branch', 30, 4, 'X'),
(3, 1, 'Club', 40, 5, 'X'),
(4, 1, 'Dagger', 90, 8, 'X'),
(5, 1, 'Hatchet', 150, 12, 'X'),
(6, 1, 'Axe', 200, 16, 'X'),
(7, 1, 'Brand', 300, 25, 'X'),
(8, 1, 'Poleaxe', 500, 35, 'X'),
(9, 1, 'Broadsword', 800, 45, 'X'),
(10, 1, 'Battle Axe', 1200, 50, 'X'),
(11, 1, 'Claymore', 2000, 60, 'X'),
(12, 1, 'Dark Axe', 3000, 100, 'expbonus,-5'),
(13, 1, 'Dark Sword', 4500, 125, 'expbonus,-10'),
(14, 1, 'Bright Sword', 6000, 100, 'expbonus,10'),
(15, 1, 'Magic Sword', 10000, 150, 'maxmp,50'),
(16, 1, 'Destiny Blade', 50000, 250, 'strength,50'),
(17, 2, 'Skivvies', 25, 2, 'goldbonus,10'),
(18, 2, 'Clothes', 50, 5, 'X'),
(19, 2, 'Leather Armor', 75, 10, 'X'),
(20, 2, 'Hard Leather Armor', 150, 25, 'X'),
(21, 2, 'Chain Mail', 300, 30, 'X'),
(22, 2, 'Bronze Plate', 900, 50, 'X'),
(23, 2, 'Iron Plate', 2000, 100, 'X'),
(24, 2, 'Magic Armor', 4000, 125, 'maxmp,50'),
(25, 2, 'Dark Armor', 5000, 150, 'expbonus,-10'),
(26, 2, 'Bright Armor', 10000, 175, 'expbonus,10'),
(27, 2, 'Destiny Raiment', 50000, 200, 'dexterity,50'),
(28, 3, 'Reed Shield', 50, 2, 'X'),
(29, 3, 'Buckler', 100, 4, 'X'),
(30, 3, 'Small Shield', 500, 10, 'X'),
(31, 3, 'Large Shield', 2500, 30, 'X'),
(32, 3, 'Silver Shield', 10000, 60, 'X'),
(33, 3, 'Destiny Aegis', 25000, 100, 'maxhp,50');
SQL);
$page .= table_status_msg($query === true, 'Drops', 'populate');
$query = db()->exec(<<<SQL
CREATE TABLE classes (
'id' INTEGER PRIMARY KEY AUTOINCREMENT,
'name' TEXT NOT NULL,
'lore' TEXT NOT NULL,
'exp_rate' INTEGER NOT NULL DEFAULT 3,
'base_hp' INTEGER NOT NULL DEFAULT 15,
'base_mp' INTEGER NOT NULL DEFAULT 10,
'base_str' INTEGER NOT NULL DEFAULT 1,
'base_dex' INTEGER NOT NULL DEFAULT 1,
'hp_rate' INTEGER NOT NULL DEFAULT 2,
'mp_rate' INTEGER NOT NULL DEFAULT 2,
'str_rate' INTEGER NOT NULL DEFAULT 2,
'dex_rate' INTEGER NOT NULL DEFAULT 2,
);
SQL);
$page .= table_status_msg($query === true, 'Classes', 'create');
$query = db()->exec(<<<SQL
INSERT INTO classes VALUES
(1, 'Adventurer', '', 3, 15, 10, 4, 4, 2, 2, 2, 2),
(2, 'Mage', '', 1, 10, 15, 1, 7, 1, 3, 1, 2),
(2, 'Warrior', '', 2, 20, 5, 7, 1, 3, 1, 3, 1),
(3, 'Paladin', '', 5, 15, 15, 5, 5, 2, 2, 2, 2);
SQL);
$page .= table_status_msg($query === true, 'Classes', 'populate');
$query = db()->exec(<<<SQL
CREATE TABLE levels (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`1_exp` INTEGER NOT NULL DEFAULT 0,
`1_hp` INTEGER NOT NULL DEFAULT 0,
`1_mp` INTEGER NOT NULL DEFAULT 0,
`1_tp` INTEGER NOT NULL DEFAULT 0,
`1_strength` INTEGER NOT NULL DEFAULT 0,
`1_dexterity` INTEGER NOT NULL DEFAULT 0,
`1_spells` INTEGER NOT NULL DEFAULT 0,
`2_exp` INTEGER NOT NULL DEFAULT 0,
`2_hp` INTEGER NOT NULL DEFAULT 0,
`2_mp` INTEGER NOT NULL DEFAULT 0,
`2_tp` INTEGER NOT NULL DEFAULT 0,
`2_strength` INTEGER NOT NULL DEFAULT 0,
`2_dexterity` INTEGER NOT NULL DEFAULT 0,
`2_spells` INTEGER NOT NULL DEFAULT 0,
`3_exp` INTEGER NOT NULL DEFAULT 0,
`3_hp` INTEGER NOT NULL DEFAULT 0,
`3_mp` INTEGER NOT NULL DEFAULT 0,
`3_tp` INTEGER NOT NULL DEFAULT 0,
`3_strength` INTEGER NOT NULL DEFAULT 0,
`3_dexterity` INTEGER NOT NULL DEFAULT 0,
`3_spells` INTEGER NOT NULL DEFAULT 0
);
SQL);
$page .= table_status_msg($query === true, 'Levels', 'create');
$query = db()->exec(<<<SQL
INSERT INTO levels VALUES
(1, 0, 15, 0, 5, 5, 5, 0, 0, 15, 0, 5, 5, 5, 0, 0, 15, 0, 5, 5, 5, 0),
(2, 15, 2, 5, 1, 0, 1, 1, 18, 2, 4, 1, 2, 1, 1, 20, 2, 5, 1, 0, 2, 1),
(3, 45, 3, 4, 2, 1, 2, 0, 54, 2, 3, 2, 3, 2, 0, 60, 2, 3, 2, 1, 3, 0),
(4, 105, 3, 3, 2, 1, 2, 6, 126, 2, 3, 2, 3, 2, 0, 140, 2, 4, 2, 1, 3, 0),
(5, 195, 2, 5, 2, 0, 1, 0, 234, 2, 4, 2, 2, 1, 6, 260, 2, 4, 2, 0, 2, 6),
(6, 330, 4, 5, 2, 2, 3, 0, 396, 3, 4, 2, 4, 3, 0, 440, 3, 5, 2, 2, 4, 0),
(7, 532, 3, 4, 2, 1, 2, 11, 639, 2, 3, 2, 3, 2, 0, 710, 2, 3, 2, 1, 3, 0),
(8, 835, 2, 4, 2, 0, 1, 0, 1003, 2, 3, 2, 2, 1, 11, 1115, 2, 4, 2, 0, 2, 11),
(9, 1290, 5, 3, 2, 3, 4, 2, 1549, 4, 2, 2, 5, 4, 0, 1722, 4, 2, 2, 3, 5, 0),
(10, 1973, 10, 3, 2, 4, 3, 0, 2369, 10, 2, 2, 6, 3, 0, 2633, 10, 3, 2, 4, 4, 0),
(11, 2997, 5, 2, 2, 3, 4, 0, 3598, 4, 1, 2, 5, 4, 2, 3999, 4, 1, 2, 3, 5, 2),
(12, 4533, 4, 2, 2, 2, 3, 7, 5441, 4, 1, 2, 4, 3, 0, 6047, 4, 2, 2, 2, 4, 0),
(13, 6453, 4, 3, 2, 2, 3, 0, 7745, 4, 2, 2, 4, 3, 0, 8607, 4, 2, 2, 2, 4, 0),
(14, 8853, 5, 4, 2, 3, 4, 17, 10625, 4, 3, 2, 5, 4, 7, 11807, 4, 4, 2, 3, 5, 7),
(15, 11853, 5, 5, 2, 3, 4, 0, 14225, 4, 4, 2, 5, 4, 0, 15808, 4, 4, 2, 3, 5, 0),
(16, 15603, 5, 3, 2, 3, 4, 0, 18725, 5, 2, 2, 5, 4, 0, 20807, 5, 3, 2, 3, 5, 0),
(17, 20290, 4, 2, 2, 2, 3, 12, 24350, 4, 1, 2, 4, 3, 0, 27057, 4, 1, 2, 2, 4, 0),
(18, 25563, 4, 2, 2, 2, 3, 0, 30678, 3, 1, 2, 4, 3, 14, 34869, 3, 2, 2, 2, 4, 17),
(19, 31495, 4, 5, 2, 2, 3, 0, 37797, 3, 4, 2, 4, 3, 0, 43657, 3, 4, 2, 2, 4, 0),
(20, 38169, 10, 6, 2, 3, 3, 0, 45805, 10, 5, 2, 5, 3, 0, 53543, 10, 6, 2, 3, 4, 0),
(21, 45676, 4, 4, 2, 2, 3, 0, 54814, 4, 3, 2, 4, 3, 0, 64664, 4, 3, 2, 2, 4, 0),
(22, 54121, 5, 5, 2, 3, 4, 0, 64949, 4, 4, 2, 5, 4, 12, 77175, 4, 5, 2, 3, 5, 12),
(23, 63622, 5, 3, 2, 3, 4, 0, 76350, 4, 2, 2, 5, 4, 0, 91250, 4, 2, 2, 3, 5, 0),
(24, 74310, 5, 5, 2, 3, 4, 0, 89176, 4, 4, 2, 5, 4, 0, 107083, 4, 5, 2, 3, 5, 0),
(25, 86334, 4, 4, 2, 2, 3, 3, 103605, 3, 3, 2, 4, 3, 17, 124895, 3, 3, 2, 2, 4, 14),
(26, 99861, 6, 3, 2, 4, 5, 0, 119837, 5, 2, 2, 6, 5, 0, 144933, 5, 3, 2, 4, 6, 0),
(27, 115078, 6, 2, 2, 4, 5, 0, 138098, 5, 1, 2, 6, 5, 0, 167475, 5, 1, 2, 4, 6, 0),
(28, 132197, 4, 2, 2, 2, 3, 0, 158641, 4, 1, 2, 4, 3, 0, 192835, 4, 2, 2, 2, 4, 0),
(29, 151456, 6, 3, 2, 4, 5, 0, 181751, 5, 2, 2, 6, 5, 3, 221365, 5, 2, 2, 4, 6, 3),
(30, 173121, 10, 4, 3, 4, 4, 0, 207749, 10, 3, 3, 6, 4, 0, 253461, 10, 4, 3, 4, 5, 0),
(31, 197494, 5, 5, 3, 3, 4, 8, 236996, 4, 3, 3, 5, 4, 0, 289568, 4, 3, 3, 3, 5, 0),
(32, 224913, 6, 4, 3, 4, 5, 0, 269898, 5, 3, 3, 6, 5, 0, 330188, 5, 4, 3, 4, 6, 0),
(33, 255758, 5, 4, 3, 3, 4, 0, 306912, 5, 3, 3, 5, 4, 0, 375885, 5, 3, 3, 3, 5, 0),
(34, 290458, 6, 4, 3, 4, 5, 0, 348552, 5, 3, 3, 6, 5, 8, 427294, 5, 4, 3, 4, 6, 8),
(35, 329495, 5, 3, 3, 3, 4, 0, 395397, 4, 2, 3, 5, 4, 0, 485126, 4, 2, 3, 3, 5, 0),
(36, 373412, 4, 3, 3, 2, 3, 18, 448097, 5, 2, 3, 4, 3, 0, 550188, 5, 3, 3, 2, 4, 0),
(37, 422818, 5, 4, 3, 3, 4, 0, 507384, 5, 3, 3, 5, 4, 0, 623383, 5, 3, 3, 3, 5, 0),
(38, 478399, 6, 5, 3, 4, 5, 0, 574081, 5, 4, 3, 6, 5, 15, 705726, 5, 5, 3, 4, 6, 18),
(39, 540927, 6, 4, 3, 4, 5, 0, 649115, 5, 3, 3, 6, 5, 0, 798362, 5, 3, 3, 4, 6, 0),
(40, 611271, 15, 3, 3, 5, 5, 13, 733528, 15, 2, 3, 7, 5, 0, 902577, 15, 3, 3, 5, 6, 0),
(41, 690408, 7, 3, 3, 5, 2, 0, 828492, 6, 2, 3, 7, 2, 0, 1019818, 6, 2, 3, 5, 3, 0),
(42, 779437, 7, 4, 3, 5, 6, 0, 935326, 6, 3, 3, 7, 6, 0, 1151714, 6, 4, 3, 5, 7, 0),
(43, 879592, 8, 5, 3, 6, 7, 0, 1055514, 7, 4, 3, 8, 7, 0, 1300096, 7, 4, 3, 6, 8, 0),
(44, 992268, 6, 3, 3, 4, 5, 0, 1190725, 5, 2, 3, 6, 5, 0, 1448478, 5, 3, 3, 4, 6, 0),
(45, 1119028, 5, 8, 3, 3, 4, 4, 1325936, 5, 8, 3, 5, 4, 18, 1596860, 5, 8, 3, 3, 5, 4),
(46, 1245788, 6, 5, 3, 4, 5, 0, 1461147, 5, 4, 3, 6, 5, 0, 1745242, 5, 5, 3, 4, 6, 0),
(47, 1372548, 7, 4, 3, 5, 6, 0, 1596358, 6, 3, 3, 7, 6, 0, 1893624, 6, 3, 3, 5, 7, 0),
(48, 1499308, 6, 4, 3, 4, 5, 0, 1731569, 5, 3, 3, 6, 5, 0, 2042006, 5, 4, 3, 4, 6, 0),
(49, 1626068, 5, 3, 3, 3, 4, 0, 1866780, 4, 2, 3, 5, 4, 0, 2190388, 4, 2, 3, 3, 5, 0),
(50, 1752828, 15, 3, 3, 5, 5, 0, 2001991, 15, 2, 3, 7, 5, 0, 2338770, 15, 3, 3, 5, 6, 0),
(51, 1879588, 6, 2, 3, 4, 5, 9, 2137202, 5, 1, 3, 6, 5, 13, 2487152, 5, 1, 3, 4, 6, 13),
(52, 2006348, 7, 2, 3, 5, 6, 0, 2272413, 6, 1, 3, 7, 6, 0, 2635534, 6, 2, 3, 5, 7, 0),
(53, 2133108, 8, 2, 3, 6, 7, 0, 2407624, 7, 1, 3, 8, 7, 0, 2783916, 7, 1, 3, 6, 8, 0),
(54, 2259868, 8, 4, 3, 6, 7, 0, 2542835, 7, 3, 3, 8, 7, 0, 2932298, 7, 4, 3, 6, 8, 0),
(55, 2386628, 7, 4, 3, 5, 6, 0, 2678046, 6, 3, 3, 7, 6, 0, 3080680, 6, 3, 3, 5, 7, 0),
(56, 2513388, 7, 4, 3, 5, 6, 0, 2813257, 6, 3, 3, 7, 6, 0, 3229062, 6, 4, 3, 5, 7, 9),
(57, 2640148, 6, 5, 3, 4, 5, 0, 2948468, 6, 4, 3, 6, 5, 0, 3377444, 6, 4, 3, 4, 6, 0),
(58, 2766908, 5, 5, 3, 3, 4, 0, 3083679, 5, 4, 3, 5, 4, 19, 3525826, 5, 5, 3, 3, 5, 0),
(59, 2893668, 8, 3, 3, 6, 7, 0, 3218890, 7, 2, 3, 8, 7, 0, 3674208, 7, 2, 3, 6, 8, 0),
(60, 3020428, 15, 4, 4, 6, 6, 19, 3354101, 15, 3, 4, 8, 6, 0, 3822590, 15, 4, 4, 6, 7, 15),
(61, 3147188, 8, 5, 4, 6, 7, 0, 3489312, 7, 4, 4, 8, 7, 0, 3970972, 7, 4, 4, 6, 8, 0),
(62, 3273948, 8, 4, 4, 6, 7, 0, 3624523, 7, 3, 4, 8, 7, 0, 4119354, 7, 4, 4, 6, 8, 0),
(63, 3400708, 9, 5, 4, 7, 8, 0, 3759734, 8, 4, 4, 9, 8, 0, 4267736, 8, 4, 4, 7, 9, 0),
(64, 3527468, 5, 5, 4, 3, 4, 0, 3894945, 5, 4, 4, 5, 4, 0, 4416118, 5, 5, 4, 3, 5, 0),
(65, 3654228, 6, 4, 4, 4, 5, 0, 4030156, 6, 3, 4, 6, 5, 0, 4564500, 6, 3, 4, 4, 6, 0),
(66, 3780988, 8, 4, 4, 6, 7, 0, 4165367, 8, 3, 4, 8, 7, 0, 4712882, 8, 4, 4, 6, 8, 0),
(67, 3907748, 7, 3, 4, 5, 6, 0, 4300578, 7, 2, 4, 7, 6, 0, 4861264, 7, 2, 4, 5, 7, 0),
(68, 4034508, 9, 3, 4, 7, 8, 0, 4435789, 8, 2, 4, 9, 8, 0, 5009646, 8, 3, 4, 7, 9, 0),
(69, 4161268, 5, 4, 4, 3, 4, 0, 4571000, 5, 3, 4, 5, 4, 0, 5158028, 5, 3, 4, 3, 5, 0),
(70, 4288028, 20, 4, 4, 6, 6, 5, 4706211, 20, 3, 4, 8, 6, 16, 5306410, 20, 4, 4, 6, 7, 0),
(71, 4414788, 5, 5, 4, 3, 4, 0, 4841422, 5, 4, 4, 5, 4, 0, 5454792, 5, 4, 4, 3, 5, 0),
(72, 4541548, 6, 2, 4, 4, 5, 0, 4976633, 5, 1, 4, 6, 5, 0, 5603174, 5, 2, 4, 4, 6, 0),
(73, 4668308, 8, 4, 4, 6, 7, 0, 5111844, 8, 3, 4, 8, 7, 0, 5751556, 8, 3, 4, 6, 8, 0),
(74, 4795068, 7, 5, 4, 5, 6, 0, 5247055, 6, 4, 4, 7, 6, 0, 5899938, 6, 5, 4, 5, 7, 0),
(75, 4921828, 5, 3, 4, 3, 4, 0, 5382266, 5, 2, 4, 5, 4, 0, 6048320, 5, 2, 4, 3, 5, 0),
(76, 5048588, 6, 3, 4, 4, 5, 0, 5517477, 6, 2, 4, 6, 5, 0, 6196702, 6, 3, 4, 4, 6, 0),
(77, 5175348, 6, 4, 4, 4, 5, 0, 5652688, 7, 3, 4, 6, 5, 0, 6345084, 7, 3, 4, 4, 6, 0),
(78, 5302108, 7, 4, 4, 5, 6, 0, 5787899, 7, 3, 4, 7, 6, 0, 6493466, 7, 4, 4, 5, 7, 0),
(79, 5428868, 8, 4, 4, 6, 7, 10, 5923110, 7, 3, 4, 8, 7, 0, 6641848, 7, 3, 4, 6, 8, 0),
(80, 5555628, 20, 5, 4, 6, 7, 0, 6058321, 20, 4, 4, 8, 7, 0, 6790230, 20, 5, 4, 6, 8, 0),
(81, 5682388, 7, 3, 4, 5, 6, 0, 6193532, 7, 2, 4, 7, 6, 0, 6938612, 7, 2, 4, 5, 7, 0),
(82, 5809148, 6, 4, 4, 4, 5, 0, 6328743, 5, 3, 4, 6, 5, 0, 7086994, 5, 4, 4, 4, 6, 0),
(83, 5935908, 6, 2, 4, 4, 5, 0, 6463954, 6, 1, 4, 6, 5, 0, 7235376, 6, 1, 4, 4, 6, 0),
(84, 6062668, 5, 4, 4, 3, 4, 0, 6599165, 5, 3, 4, 5, 4, 0, 7383758, 5, 4, 4, 3, 5, 0),
(85, 6189428, 7, 4, 4, 5, 6, 0, 6734376, 6, 3, 4, 7, 6, 0, 7532140, 6, 3, 4, 5, 7, 0),
(86, 6316188, 8, 5, 4, 6, 7, 0, 6869587, 8, 4, 4, 8, 7, 0, 7680522, 8, 5, 4, 6, 8, 0),
(87, 6442948, 8, 4, 4, 6, 7, 0, 7004798, 7, 3, 4, 8, 7, 0, 7828904, 7, 3, 4, 6, 8, 0),
(88, 6569708, 9, 5, 4, 7, 8, 0, 7140009, 8, 4, 4, 9, 8, 0, 7977286, 8, 5, 4, 7, 9, 0),
(89, 6696468, 5, 2, 4, 3, 4, 0, 7275220, 5, 1, 4, 5, 4, 0, 8125668, 5, 1, 4, 3, 5, 0),
(90, 6823228, 20, 2, 5, 7, 8, 0, 7410431, 20, 1, 5, 9, 8, 0, 8274050, 20, 2, 5, 7, 9, 0),
(91, 6949988, 5, 3, 5, 3, 4, 0, 7545642, 5, 2, 5, 5, 4, 0, 8422432, 5, 2, 5, 3, 5, 0),
(92, 7076748, 6, 3, 5, 4, 5, 0, 7680853, 4, 2, 5, 6, 5, 0, 8570814, 4, 3, 5, 4, 6, 0),
(93, 7203508, 8, 4, 5, 6, 7, 0, 7816064, 6, 2, 5, 8, 7, 0, 8719196, 6, 2, 5, 6, 8, 0),
(94, 7330268, 4, 4, 5, 3, 3, 0, 7951275, 4, 3, 5, 5, 3, 0, 8867578, 4, 4, 5, 3, 4, 0),
(95, 7457028, 3, 3, 5, 5, 2, 0, 8086486, 4, 2, 5, 7, 2, 0, 9015960, 4, 2, 5, 5, 3, 0),
(96, 7583788, 5, 3, 5, 4, 3, 0, 8221697, 5, 2, 5, 7, 3, 0, 9164342, 5, 3, 5, 4, 4, 0),
(97, 7710548, 5, 4, 5, 4, 5, 0, 8356908, 5, 3, 5, 7, 5, 0, 9312724, 5, 3, 5, 4, 6, 0),
(98, 7837308, 4, 5, 5, 4, 3, 0, 8492119, 4, 3, 5, 7, 3, 0, 9461106, 4, 4, 5, 4, 4, 0),
(99, 7964068, 50, 5, 5, 6, 5, 0, 8627330, 50, 3, 5, 9, 5, 0, 9609488, 50, 4, 5, 6, 6, 0),
(100, 16777215, 0, 0, 0, 0, 0, 0, 16777215, 0, 0, 0, 0, 0, 0, 16777215, 0, 0, 0, 0, 0, 0);
SQL);
$page .= table_status_msg($query === true, 'Levels', 'populate');
$query = db()->exec(<<<SQL
CREATE TABLE monsters (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` TEXT NOT NULL DEFAULT '',
`maxhp` INTEGER NOT NULL DEFAULT 0,
`maxdam` INTEGER NOT NULL DEFAULT 0,
`armor` INTEGER NOT NULL DEFAULT 0,
`level` INTEGER NOT NULL DEFAULT 0,
`maxexp` INTEGER NOT NULL DEFAULT 0,
`maxgold` INTEGER NOT NULL DEFAULT 0,
`immune` INTEGER NOT NULL DEFAULT 0
);
SQL);
$page .= table_status_msg($query === true, 'Monsters', 'create');
$query = db()->exec(<<<SQL
INSERT INTO monsters VALUES
(1, 'Blue Slime', 4, 3, 1, 1, 1, 1, 0),
(2, 'Red Slime', 6, 5, 1, 1, 2, 1, 0),
(3, 'Critter', 6, 5, 2, 1, 4, 2, 0),
(4, 'Creature', 10, 8, 2, 2, 4, 2, 0),
(5, 'Shadow', 10, 9, 3, 2, 6, 2, 1),
(6, 'Drake', 11, 10, 3, 2, 8, 3, 0),
(7, 'Shade', 12, 10, 3, 3, 10, 3, 1),
(8, 'Drakelor', 14, 12, 4, 3, 10, 3, 0),
(9, 'Silver Slime', 15, 100, 200, 30, 15, 1000, 2),
(10, 'Scamp', 16, 13, 5, 4, 15, 5, 0),
(11, 'Raven', 16, 13, 5, 4, 18, 6, 0),
(12, 'Scorpion', 18, 14, 6, 5, 20, 7, 0),
(13, 'Illusion', 20, 15, 6, 5, 20, 7, 1),
(14, 'Nightshade', 22, 16, 6, 6, 24, 8, 0),
(15, 'Drakemal', 22, 18, 7, 6, 24, 8, 0),
(16, 'Shadow Raven', 24, 18, 7, 6, 26, 9, 1),
(17, 'Ghost', 24, 20, 8, 6, 28, 9, 0),
(18, 'Frost Raven', 26, 20, 8, 7, 30, 10, 0),
(19, 'Rogue Scorpion', 28, 22, 9, 7, 32, 11, 0),
(20, 'Ghoul', 29, 24, 9, 7, 34, 11, 0),
(21, 'Magician', 30, 24, 10, 8, 36, 12, 0),
(22, 'Rogue', 30, 25, 12, 8, 40, 13, 0),
(23, 'Drakefin', 32, 26, 12, 8, 40, 13, 0),
(24, 'Shimmer', 32, 26, 14, 8, 45, 15, 1),
(25, 'Fire Raven', 34, 28, 14, 9, 45, 15, 0),
(26, 'Dybbuk', 34, 28, 14, 9, 50, 17, 0),
(27, 'Knave', 36, 30, 15, 9, 52, 17, 0),
(28, 'Goblin', 36, 30, 15, 10, 54, 18, 0),
(29, 'Skeleton', 38, 30, 18, 10, 58, 19, 0),
(30, 'Dark Slime', 38, 32, 18, 10, 62, 21, 0),
(31, 'Silver Scorpion', 30, 160, 350, 40, 63, 2000, 2),
(32, 'Mirage', 40, 32, 20, 11, 64, 21, 1),
(33, 'Sorceror', 41, 33, 22, 11, 68, 23, 0),
(34, 'Imp', 42, 34, 22, 12, 70, 23, 0),
(35, 'Nymph', 43, 35, 22, 12, 70, 23, 0),
(36, 'Scoundrel', 43, 35, 22, 12, 75, 25, 0),
(37, 'Megaskeleton', 44, 36, 24, 13, 78, 26, 0),
(38, 'Grey Wolf', 44, 36, 24, 13, 82, 27, 0),
(39, 'Phantom', 46, 38, 24, 14, 85, 28, 1),
(40, 'Specter', 46, 38, 24, 14, 90, 30, 0),
(41, 'Dark Scorpion', 48, 40, 26, 15, 95, 32, 1),
(42, 'Warlock', 48, 40, 26, 15, 100, 33, 1),
(43, 'Orc', 49, 42, 28, 15, 104, 35, 0),
(44, 'Sylph', 49, 42, 28, 15, 106, 35, 0),
(45, 'Wraith', 50, 45, 30, 16, 108, 36, 0),
(46, 'Hellion', 50, 45, 30, 16, 110, 37, 0),
(47, 'Bandit', 52, 45, 30, 16, 114, 38, 0),
(48, 'Ultraskeleton', 52, 46, 32, 16, 116, 39, 0),
(49, 'Dark Wolf', 54, 47, 36, 17, 120, 40, 1),
(50, 'Troll', 56, 48, 36, 17, 120, 40, 0),
(51, 'Werewolf', 56, 48, 38, 17, 124, 41, 0),
(52, 'Hellcat', 58, 50, 38, 18, 128, 43, 0),
(53, 'Spirit', 58, 50, 38, 18, 132, 44, 0),
(54, 'Nisse', 60, 52, 40, 19, 132, 44, 0),
(55, 'Dawk', 60, 54, 40, 19, 136, 45, 0),
(56, 'Figment', 64, 55, 42, 19, 140, 47, 1),
(57, 'Hellhound', 66, 56, 44, 20, 140, 47, 0),
(58, 'Wizard', 66, 56, 44, 20, 144, 48, 0),
(59, 'Uruk', 68, 58, 44, 20, 146, 49, 0),
(60, 'Siren', 68, 400, 800, 50, 10000, 50, 2),
(61, 'Megawraith', 70, 60, 46, 21, 155, 52, 0),
(62, 'Dawkin', 70, 60, 46, 21, 155, 52, 0),
(63, 'Grey Bear', 70, 62, 48, 21, 160, 53, 0),
(64, 'Haunt', 72, 62, 48, 22, 160, 53, 0),
(65, 'Hellbeast', 74, 64, 50, 22, 165, 55, 0),
(66, 'Fear', 76, 66, 52, 23, 165, 55, 0),
(67, 'Beast', 76, 66, 52, 23, 170, 57, 0),
(68, 'Ogre', 78, 68, 54, 23, 170, 57, 0),
(69, 'Dark Bear', 80, 70, 56, 24, 175, 58, 1),
(70, 'Fire', 80, 72, 56, 24, 175, 58, 0),
(71, 'Polgergeist', 84, 74, 58, 25, 180, 60, 0),
(72, 'Fright', 86, 76, 58, 25, 180, 60, 0),
(73, 'Lycan', 88, 78, 60, 25, 185, 62, 0),
(74, 'Terra Elemental', 88, 80, 62, 25, 185, 62, 1),
(75, 'Necromancer', 90, 80, 62, 26, 190, 63, 0),
(76, 'Ultrawraith', 90, 82, 64, 26, 190, 63, 0),
(77, 'Dawkor', 92, 82, 64, 26, 195, 65, 0),
(78, 'Werebear', 92, 84, 65, 26, 195, 65, 0),
(79, 'Brute', 94, 84, 65, 27, 200, 67, 0),
(80, 'Large Beast', 96, 88, 66, 27, 200, 67, 0),
(81, 'Horror', 96, 88, 68, 27, 210, 70, 0),
(82, 'Flame', 100, 90, 70, 28, 210, 70, 0),
(83, 'Lycanthor', 100, 90, 70, 28, 210, 70, 0),
(84, 'Wyrm', 100, 92, 72, 28, 220, 73, 0),
(85, 'Aero Elemental', 104, 94, 74, 29, 220, 73, 1),
(86, 'Dawkare', 106, 96, 76, 29, 220, 73, 0),
(87, 'Large Brute', 108, 98, 78, 29, 230, 77, 0),
(88, 'Frost Wyrm', 110, 100, 80, 30, 230, 77, 0),
(89, 'Knight', 110, 102, 80, 30, 240, 80, 0),
(90, 'Lycanthra', 112, 104, 82, 30, 240, 80, 0),
(91, 'Terror', 115, 108, 84, 31, 250, 83, 0),
(92, 'Blaze', 118, 108, 84, 31, 250, 83, 0),
(93, 'Aqua Elemental', 120, 110, 90, 31, 260, 87, 1),
(94, 'Fire Wyrm', 120, 110, 90, 32, 260, 87, 0),
(95, 'Lesser Wyvern', 122, 110, 92, 32, 270, 90, 0),
(96, 'Doomer', 124, 112, 92, 32, 270, 90, 0),
(97, 'Armor Knight', 130, 115, 95, 33, 280, 93, 0),
(98, 'Wyvern', 134, 120, 95, 33, 290, 97, 0),
(99, 'Nightmare', 138, 125, 100, 33, 300, 100, 0),
(100, 'Fira Elemental', 140, 125, 100, 34, 310, 103, 1),
(101, 'Megadoomer', 140, 128, 105, 34, 320, 107, 0),
(102, 'Greater Wyvern', 145, 130, 105, 34, 335, 112, 0),
(103, 'Advocate', 148, 132, 108, 35, 350, 117, 0),
(104, 'Strong Knight', 150, 135, 110, 35, 365, 122, 0),
(105, 'Liche', 150, 135, 110, 35, 380, 127, 0),
(106, 'Ultradoomer', 155, 140, 115, 36, 395, 132, 0),
(107, 'Fanatic', 160, 140, 115, 36, 410, 137, 0),
(108, 'Green Dragon', 160, 140, 115, 36, 425, 142, 0),
(109, 'Fiend', 160, 145, 120, 37, 445, 148, 0),
(110, 'Greatest Wyvern', 162, 150, 120, 37, 465, 155, 0),
(111, 'Lesser Devil', 164, 150, 120, 37, 485, 162, 0),
(112, 'Liche Master', 168, 155, 125, 38, 505, 168, 0),
(113, 'Zealot', 168, 155, 125, 38, 530, 177, 0),
(114, 'Serafiend', 170, 155, 125, 38, 555, 185, 0),
(115, 'Pale Knight', 175, 160, 130, 39, 580, 193, 0),
(116, 'Blue Dragon', 180, 160, 130, 39, 605, 202, 0),
(117, 'Obsessive', 180, 160, 135, 40, 630, 210, 0),
(118, 'Devil', 184, 164, 135, 40, 666, 222, 0),
(119, 'Liche Prince', 190, 168, 138, 40, 660, 220, 0),
(120, 'Cherufiend', 195, 170, 140, 41, 690, 230, 0),
(121, 'Red Dragon', 200, 180, 145, 41, 720, 240, 0),
(122, 'Greater Devil', 200, 180, 145, 41, 750, 250, 0),
(123, 'Renegade', 205, 185, 150, 42, 780, 260, 0),
(124, 'Archfiend', 210, 190, 150, 42, 810, 270, 0),
(125, 'Liche Lord', 210, 190, 155, 42, 850, 283, 0),
(126, 'Greatest Devil', 215, 195, 160, 43, 890, 297, 0),
(127, 'Dark Knight', 220, 200, 160, 43, 930, 310, 0),
(128, 'Giant', 220, 200, 165, 43, 970, 323, 0),
(129, 'Shadow Dragon', 225, 200, 170, 44, 1010, 337, 0),
(130, 'Liche King', 225, 205, 170, 44, 1050, 350, 0),
(131, 'Incubus', 230, 205, 175, 44, 1100, 367, 1),
(132, 'Traitor', 230, 205, 175, 45, 1150, 383, 0),
(133, 'Demon', 240, 210, 180, 45, 1200, 400, 0),
(134, 'Dark Dragon', 245, 215, 180, 45, 1250, 417, 1),
(135, 'Insurgent', 250, 220, 190, 46, 1300, 433, 0),
(136, 'Leviathan', 255, 225, 190, 46, 1350, 450, 0),
(137, 'Grey Daemon', 260, 230, 190, 46, 1400, 467, 0),
(138, 'Succubus', 265, 240, 200, 47, 1460, 487, 1),
(139, 'Demon Prince', 270, 240, 200, 47, 1520, 507, 0),
(140, 'Black Dragon', 275, 250, 205, 47, 1580, 527, 1),
(141, 'Nihilist', 280, 250, 205, 47, 1640, 547, 0),
(142, 'Behemoth', 285, 260, 210, 48, 1700, 567, 0),
(143, 'Demagogue', 290, 260, 210, 48, 1760, 587, 0),
(144, 'Demon Lord', 300, 270, 220, 48, 1820, 607, 0),
(145, 'Red Daemon', 310, 280, 230, 48, 1880, 627, 0),
(146, 'Colossus', 320, 300, 240, 49, 1940, 647, 0),
(147, 'Demon King', 330, 300, 250, 49, 2000, 667, 0),
(148, 'Dark Daemon', 340, 320, 260, 49, 2200, 733, 1),
(149, 'Titan', 360, 340, 270, 50, 2400, 800, 0),
(150, 'Black Daemon', 400, 400, 280, 50, 3000, 1000, 1),
(151, 'Lucifuge', 600, 600, 400, 50, 10000, 10000, 2);
SQL);
$page .= table_status_msg($query === true, 'Monsters', 'populate');
$query = db()->exec(<<<SQL
CREATE TABLE news (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`author` TEXT NOT NULL DEFAULT 'Guild Master',
`postdate` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`content` TEXT NOT NULL
);
SQL);
$page .= table_status_msg($query === true, 'News', 'create');
$query = db()->exec("INSERT INTO news (content) VALUES ('This is the first news post. Please use the admin control panel to add another one and make this one go away.');");
$page .= table_status_msg($query === true, 'News', 'populate');
$query = db()->exec(<<<SQL
CREATE TABLE spells (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` TEXT NOT NULL,
`mp` INTEGER NOT NULL DEFAULT 0,
`attribute` INTEGER NOT NULL DEFAULT 0,
`type` INTEGER NOT NULL DEFAULT 0
);
SQL);
$page .= table_status_msg($query === true, 'Spells', 'create');
$query = db()->exec(<<<SQL
INSERT INTO spells VALUES
(1, 'Heal', 5, 10, 1),
(2, 'Revive', 10, 25, 1),
(3, 'Life', 25, 50, 1),
(4, 'Breath', 50, 100, 1),
(5, 'Gaia', 75, 150, 1),
(6, 'Hurt', 5, 15, 2),
(7, 'Pain', 12, 35, 2),
(8, 'Maim', 25, 70, 2),
(9, 'Rend', 40, 100, 2),
(10, 'Chaos', 50, 130, 2),
(11, 'Sleep', 10, 5, 3),
(12, 'Dream', 30, 9, 3),
(13, 'Nightmare', 60, 13, 3),
(14, 'Craze', 10, 10, 4),
(15, 'Rage', 20, 25, 4),
(16, 'Fury', 30, 50, 4),
(17, 'Ward', 10, 10, 5),
(18, 'Fend', 20, 25, 5),
(19, 'Barrier', 30, 50, 5);
SQL);
$page .= table_status_msg($query === true, 'Spells', 'populate');
$query = db()->exec(<<<SQL
CREATE TABLE towns (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` TEXT NOT NULL,
`latitude` INTEGER NOT NULL DEFAULT 0,
`longitude` INTEGER NOT NULL DEFAULT 0,
`innprice` INTEGER NOT NULL DEFAULT 0,
`mapprice` INTEGER NOT NULL DEFAULT 0,
`travelpoints` INTEGER NOT NULL DEFAULT 0,
`itemslist` TEXT NOT NULL
);
SQL);
$page .= table_status_msg($query === true, 'Towns', 'create');
$query = db()->exec(<<<SQL
INSERT INTO towns VALUES
(1, 'Midworld', 0, 0, 5, 0, 0, '1,2,3,17,18,19,28,29'),
(2, 'Roma', 30, 30, 10, 25, 5, '2,3,4,18,19,29'),
(3, 'Bris', 70, -70, 25, 50, 15, '2,3,4,5,18,19,20,29.30'),
(4, 'Kalle', -100, 100, 40, 100, 30, '5,6,8,10,12,21,22,23,29,30'),
(5, 'Narcissa', -130, -130, 60, 500, 50, '4,7,9,11,13,21,22,23,29,30,31'),
(6, 'Hambry', 170, 170, 90, 1000, 80, '10,11,12,13,14,23,24,30,31'),
(7, 'Gilead', 200, -200, 100, 3000, 110, '12,13,14,15,24,25,26,32'),
(8, 'Endworld', -250, -250, 125, 9000, 160, '16,27,33');
SQL);
$page .= table_status_msg($query === true, 'Towns', 'populate');
$query = db()->exec(<<<SQL
CREATE TABLE users (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`username` TEXT NOT NULL,
`password` TEXT NOT NULL,
`email` TEXT NOT NULL,
`verify` TEXT NOT NULL default '',
`regdate` datetime NOT NULL default CURRENT_TIMESTAMP,
`onlinetime` datetime NOT NULL default CURRENT_TIMESTAMP,
`authlevel` INTEGER NOT NULL default 0,
`latitude` INTEGER NOT NULL default 0,
`longitude` INTEGER NOT NULL default 0,
`charclass` INTEGER NOT NULL default 0,
'class_id' INTEGER NOT NULL DEFAULT 1,
`currentaction` TEXT NOT NULL default 'In Town',
`currentfight` INTEGER NOT NULL default 0,
`currentmonster` INTEGER NOT NULL default 0,
`currentmonsterhp` INTEGER NOT NULL default 0,
`currentmonstersleep` INTEGER NOT NULL default 0,
`currentmonsterimmune` INTEGER NOT NULL default 0,
`currentuberdamage` INTEGER NOT NULL default 0,
`currentuberdefense` INTEGER NOT NULL default 0,
`currenthp` INTEGER NOT NULL default 15,
`currentmp` INTEGER NOT NULL default 0,
`currenttp` INTEGER NOT NULL default 10,
`maxhp` INTEGER NOT NULL default 15,
`maxmp` INTEGER NOT NULL default 0,
`maxtp` INTEGER NOT NULL default 10,
`level` INTEGER NOT NULL default 1,
`gold` INTEGER NOT NULL default 100,
`experience` INTEGER NOT NULL default 0,
`goldbonus` INTEGER NOT NULL default 0,
`expbonus` INTEGER NOT NULL default 0,
`strength` INTEGER NOT NULL default 5,
`dexterity` INTEGER NOT NULL default 5,
`attackpower` INTEGER NOT NULL default 5,
`defensepower` INTEGER NOT NULL default 5,
`weaponid` INTEGER NOT NULL default 0,
`armorid` INTEGER NOT NULL default 0,
`shieldid` INTEGER NOT NULL default 0,
`slot1id` INTEGER NOT NULL default 0,
`slot2id` INTEGER NOT NULL default 0,
`slot3id` INTEGER NOT NULL default 0,
`weaponname` TEXT NOT NULL default 'None',
`armorname` TEXT NOT NULL default 'None',
`shieldname` TEXT NOT NULL default 'None',
`slot1name` TEXT NOT NULL default 'None',
`slot2name` TEXT NOT NULL default 'None',
`slot3name` TEXT NOT NULL default 'None',
`dropcode` INTEGER NOT NULL default 0,
`spells` TEXT NOT NULL default '0',
`towns` TEXT NOT NULL default '0',
`game_skin` INTEGER NOT NULL DEFAULT 0
);
SQL);
$page .= table_status_msg($query === true, 'Users', 'create');
$time = round((microtime(true) - START), 4);
return $page . "<br>Database setup complete in $time seconds.<br><br><a href=\"/install/third\">Click here to continue with installation.</a></body></html>";
}
/**
* Gather user info for admin account.
*/
function third()
{
return <<<HTML
<html>
<head>
<title>Dragon Knight Installation</title>
</head>
<body>
<b>Dragon Knight Installation: Page Three</b><br><br>
Now you must create an administrator account so you can use the control panel. Fill out the form below to create your account. You will be able to customize the class names through the control panel once your admin account is created.<br><br>
<form action="/install/fourth" method="post">
<table width="50%">
<tr><td width="20%" style="vertical-align:top;">Username:</td><td><input type="text" name="username" /><br><br><br></td></tr>
<tr><td style="vertical-align:top;">Password:</td><td><input type="password" name="password" /></td></tr>
<tr><td style="vertical-align:top;">Verify Password:</td><td><input type="password" name="confirm_password" /><br><br><br></td></tr>
<tr><td style="vertical-align:top;">Email Address:</td><td><input type="text" name="email" /></td></tr>
<tr><td style="vertical-align:top;">Verify Email:</td><td><input type="text" name="confirm_email" /><br><br><br></td></tr>
<tr><td style="vertical-align:top;">Character Class:</td><td><select name="charclass"><option value="1">Mage</option><option value="2">Warrior</option><option value="3">Paladin</option></select></td></tr>
<tr><td colspan="2"><input type="submit" name="submit" value="Submit" /> <input type="reset" name="reset" value="Reset" /></td></tr>
</table>
</form>
</body>
</html>
HTML;
}
/**
* Final page: insert new user row, congratulate the person on a job well done.
*/
function fourth()
{
$form = validate($_POST, [
'username' => ['length:3-18', 'alpha-spaces'],
'email' => ['email'],
'confirm_email' => ['confirm'],
'password' => ['length:6-255'],
'confirm_password' => ['confirm']
]);
if (!$form['valid']) exit(ul_from_validate_errors($form['errors']));
$form = $form['data'];
if (db()->query(
"INSERT INTO users (username, password, email, verify, charclass, authlevel) VALUES (?, ?, ?, 'g2g', ?, 1)",
[$form['username'], password_hash($form['password'], PASSWORD_ARGON2ID), $form['email'], $form['charclass']]
) === false) {
exit("Failed to create user.");
}
file_put_contents('../.installed', date('Y-m-d H:i:s'));
return <<<HTML
<html>
<head>
<title>Dragon Knight Installation</title>
</head>
<body>
<b>Dragon Knight Installation: Page Four</b><br><br>
Your admin account was created successfully. Installation is complete.<br><br>
Be sure to delete install.php from your Dragon Knight directory for security purposes.<br><br>
You are now ready to <a href="/">play the game</a>. Note that you must log in through the public section before being allowed into the control panel. Once logged in, an "Admin" link will appear in the Functions box of the left sidebar panel.<br><br/>
Thank you for using Dragon Knight!<br><br>-----<br><br>
<b>Optional:</b> Dragon Knight is a free product, and does not require registration of any sort. However, there is an
optional "call home" function in the installer, which notifies the author of your game installation. The ONLY information
transmitted with this function is the URL to your game. This is included mainly to satisfy the author's curiosity about
how many copies of the game are being installed and used. If you choose to submit your URL to the author, please
<a href="/install/fifth">click here</a>.
</body>
</html>
HTML;
}
/**
* Call Home function.
*/
function fifth()
{
if (mail("sky@sharkk.net", "Dragon Knight Call Home", $_SERVER["SERVER_NAME"].$_SERVER["PHP_SELF"]) !== true) {
exit('Dragon Knight was unable to send your URL. Please go back and try again, or just continue on to <a href=\"/\">the game</a>.');
}
return <<<HTML
<html>
<head>
<title>Dragon Knight Installation</title>
</head>
<body>
<b>Dragon Knight Installation: Page Five</b><br><br>
Thank you for submitting your URL!<br><br>
You are now ready to <a href="/">play the game</a>. Note that you must log in through the public section before being allowed into the control panel. Once logged in, an "Admin" link will appear in the Functions box of the left sidebar panel.
</body>
</html>
HTML;
}
function table_status_msg(bool $condition, string $table_name, string $verb): string
{
$verb = match($verb) {
'create' => ['created', 'creating'],
'populate' => ['populated', 'populating']
};
if ($condition === false) {
return "Error {$verb[1]} $table_name table. (".db()->lastErrorMsg().")<br>";
}
return "$table_name table {$verb[0]}.<br>";
}

View File

@ -1,401 +0,0 @@
<?php
// towns.php :: Handles all actions you can do in town.
namespace Towns;
use Router;
function register_routes(Router $r): Router
{
$r->form('/inn', 'Towns\inn');
$r->get('/shop', 'Towns\shop');
$r->form('/buy/:id', 'Towns\buy');
// $r->get('/sell', 'Towns\sell');
$r->get('/maps', 'Towns\maps');
$r->form('/maps/:id', 'Towns\buy_map');
$r->get('/gotown/:id', 'Towns\travelto');
return $r;
}
/**
* Spit out the main town page.
*/
function town()
{
$town = get_town_by_xy(user()->longitude, user()->latitude);
if ($town === false) exit('There is an error with your user account, or with the town data. Please try again.');
$page = ['news' => '', 'whos_online' => ''];
// News box. Grab latest news entry and display it. Something a little more graceful coming soon maybe.
if (env('show_news')) {
$news = db()->query('SELECT * FROM news ORDER BY id DESC LIMIT 1;')->fetchArray(SQLITE3_ASSOC);
$news_date = pretty_date($news["postdate"]);
$news_content = nl2br($news["content"]);
$page['news'] = <<<HTML
<div class="title">Latest News</div>
<span class="light">$news_date</span><br>
$news_content
HTML;
}
// Who's Online. Currently just members. Guests maybe later.
if (env('show_online')) {
$onlinequery = db()->query(<<<SQL
SELECT id, username
FROM users
WHERE onlinetime >= datetime('now', '-600 seconds')
ORDER BY username;
SQL);
$online_count = 0;
$online_rows = [];
while ($onlinerow = $onlinequery->fetchArray(SQLITE3_ASSOC)) {
$online_count++;
$online_rows[] = "<a href=\"javascript:opencharpopup({$onlinerow['id']})\">".$onlinerow["username"]."</a>";
}
$online_rows = implode(', ', $online_rows);
$page['whos_online'] = <<<HTML
<div class="title">Who's Online</div>
There are <b>$online_count</b> user(s) online within the last 10 minutes: $online_rows
HTML;
}
page_title($town['name']);
return render('towns', ['town' => $town, 'news' => $page['news'], 'whos_online' => $page['whos_online']]);
}
/**
* Staying at the inn resets all expendable stats to their max values.
* GET/POST /inn
*/
function inn()
{
$town = get_town_by_xy(user()->longitude, user()->latitude);
if ($town === false) { exit('Cheat attempt detected.<br><br>Get a life, loser.'); }
if (user()->gold < $town['innprice']) {
$page = <<<HTML
You do not have enough gold to stay at this Inn tonight. <br><br>
You may return to <a hx-get="/" hx-target="#middle">town</a>, or use the direction buttons on the left to start exploring.
HTML;
} elseif (is_post() && $_POST['rest']) {
user()->gold -= $town['innprice'];
user()->restore_points()->save();
$page = <<<HTML
You wake up feeling refreshed and ready for action. <br><br>
You may return to <a hx-get="/" hx-target="#middle">town</a>, or use the direction buttons on the left to start exploring.
HTML;
} elseif (is_post() && !$_POST['rest']) {
redirect('/');
} else {
$page = <<<HTML
Resting at the inn will refill your current HP, MP, and TP to their maximum levels.<br><br>
A night's sleep at this Inn will cost you <b>{$town['innprice']} gold</b>. Is that ok?<br><br>
<form hx-post="/inn" hx-target="#middle">
<button name="rest" value="1">Yes</button>
<button name="rest" value="0">No</button>
</form>
HTML;
}
page_title($town['name'] . ' Inn');
return $page;
}
/**
* Displays a list of available items for purchase from the town the user is currently in. If the user is not in a town,
* redirects to home.
* GET /shop
*/
function shop()
{
$town = get_town_by_xy(user()->longitude, user()->latitude);
if ($town === false) exit('Cheat attempt detected.<br><br>Get a life, loser.');
$page = <<<HTML
Buying weapons will increase your Attack Power. Buying armor and shields will increase your Defense Power.<br><br>
Click an item name to purchase it.<br><br>
The following items are available at this town:<br><br>
<table>
HTML;
$items = db()->query('SELECT * FROM items WHERE id IN (' . $town["itemslist"] . ');');
while ($item = $items->fetchArray(SQLITE3_ASSOC)) {
$attrib = ($item["type"] == 1) ? "Attack Power:" : "Defense Power:";
$page .= '<tr><td width="4%">';
$page .= match ($item["type"]) {
1 => '<img src="/img/icon_weapon.gif" alt="weapon">',
2 => '<img src="/img/icon_armor.gif" alt="armor">',
3 => '<img src="/img/icon_shield.gif" alt="shield">'
};
$page .= '</td>';
if (user()->weaponid === $item["id"] || user()->armorid === $item["id"] || user()->shieldid === $item["id"]) {
$page .= <<<HTML
<td width="32%"><span class="light">{$item["name"]}</span></td>
<td width="32%"><span class="light">$attrib {$item['attribute']}</span></td>
<td width="32%"><span class="light">Already purchased</span></td>
HTML;
} else {
$specialdot = $item['special'] !== 'X' ? '<span class="highlight">&#42;</span>' : '';
$page .= <<<HTML
<td width="32%"><b><a hx-get="/buy/{$item['id']}" hx-target="#middle">{$item['name']}</a>$specialdot</b></td>
<td width="32%">$attrib <b>{$item['attribute']}</b></td>
<td width="32%">Price: <b>{$item['buycost']} gold</b></td>
HTML;
}
$page .= '</tr>';
}
$page .= <<<HTML
</table><br>
If you've changed your mind, you may also return back to <a hx-get="/" hx-target="#middle">town</a>.
HTML;
page_title($town['name'] . ' Shop');
return $page;
}
/**
* Confirm user's intent to purchase item.
*/
function buy(int $id)
{
$town = get_town_by_xy(user()->longitude, user()->latitude);
if ($town === false) redirect('/');
if (!in_array($id, explode(',', $town['itemslist']))) redirect('/shop');
$item = get_item($id);
$can_afford = user()->gold >= $item['buycost'];
if (!$can_afford) {
$page = <<<HTML
You do not have enough gold to buy <b>{$item['name']}</b>.<br><br>
You may return to <a hx-get="/" hx-target="#middle">town</a>, <a hx-get="/shop" hx-target="#middle">shop</a>,
or use the direction buttons on the left to start exploring.
HTML;
} elseif (is_post() && !$_POST['buy']) {
redirect('/shop');
} elseif (is_post() && $_POST['buy']) {
$type_mapping = [
1 => ['id' => 'weaponid', 'name' => 'weaponname', 'power' => 'attackpower'],
2 => ['id' => 'armorid', 'name' => 'armorname', 'power' => 'defensepower'],
3 => ['id' => 'shieldid', 'name' => 'shieldname', 'power' => 'defensepower']
];
if (!isset($type_mapping[$item["type"]])) { // should never happen
return 'Error! Invalid item type...<br>'.var_dump($item);
}
// Retrieve current equipped item or create a default
$current_equip_id = user()->{$type_mapping[$item["type"]]['id']};
if ($current_equip_id != 0) {
$item2 = get_item($current_equip_id);
} else {
$item2 = ["attribute" => 0, "buycost" => 0, "special" => "X"];
}
// Process special item effects
$specialFields = [];
$specialValues = [];
$powerAdjustments = 0;
foreach ([$item, $item2] as $index => $process_item) {
if ($process_item["special"] != "X") {
$special = explode(",", $process_item["special"]);
$toChange = $special[0];
$changeAmount = $index === 0 ? $special[1] : -$special[1];
user()->$toChange += $changeAmount;
$specialFields[] = "$toChange = ?";
$specialValues[] = user()->$toChange;
// Adjust attack or defense power
if ($toChange == "strength" || $toChange == "dexterity") {
$powerType = $toChange == "strength" ? "attackpower" : "defensepower";
$powerAdjustments += $changeAmount;
}
}
}
// Determine power and type-specific updates
$currentType = $type_mapping[$item['type']];
$powerField = $currentType['power'];
user()->$powerField += $item['attribute'] - $item2['attribute'];
// Calculate new gold with trade-in value
user()->gold += ceil($item2['buycost'] / 2) - $item['buycost'];
// Ensure current HP/MP/TP don't exceed max values
user()->currenthp = min(user()->currenthp, user()->maxhp);
user()->currentmp = min(user()->currentmp, user()->maxmp);
user()->currenttp = min(user()->currenttp, user()->maxtp);
// Update item info in user
user()->{$type_mapping[$item['type']]['id']} = $item['id'];
user()->{$type_mapping[$item['type']]['name']} = $item['name'];
user()->save();
$page = <<<HTML
Thank you for purchasing <b>{$item['name']}</b>.<br><br>
You may return to <a hx-get="/" hx-target="#middle">town</a>, <a hx-get="/shop" hx-target="#middle">shop</a>, or use the direction buttons on the
left to start exploring.
HTML;
} else {
$type_to_row_mapping = [1 => 'weaponid', 2 => 'armorid', 3 => 'shieldid'];
$current_equipped_id = user()->{$type_to_row_mapping[$item['type']]} ?? 0;
if ($current_equipped_id != 0) {
$item2 = get_item($current_equipped_id);
$sell_price = ceil($item2['buycost'] / 2);
$page = <<<HTML
If you are buying the {$item['name']}, then I will buy your {$item2['name']} for $sell_price gold. Is that ok?<br><br>
<form hx-post="/buy/$id" hx-target="#middle">
<button name="buy" value="1">Yes</button>
<button name="buy" value="0">No</button>
</form>
HTML;
} else {
$page = <<<HTML
You are buying {$item['name']} for {$item['buycost']} gold, is that ok?<br><br>
<form hx-post="/buy/$id" hx-target="#middle">
<button name="buy" value="1">Yes</button>
<button name="buy" value="0">No</button>
</form>
HTML;
}
}
page_title('Buying '.$item['name']);
return $page;
}
/**
* List maps the user can buy.
*/
function maps()
{
$page = <<<HTML
Buying maps will put the town in your Travel To box, and it won't cost you as many TP to get there.<br><br>
Click a town name to purchase its map.<br><br>
<table>
HTML;
$mapped = explode(',', user()->towns);
$towns = db()->query('SELECT * FROM towns ORDER BY id;');
while ($town = $towns->fetchArray(SQLITE3_ASSOC)) {
$latitude = ($town["latitude"] >= 0) ? $town["latitude"] . "N," : ($town["latitude"] * -1) . "S,";
$longitude = ($town["longitude"] >= 0) ? $town["longitude"] . "E" : ($town["longitude"] * -1) . "W";
if (in_array($town['id'], $mapped)) {
$page .= <<<HTML
<tr>
<td width="25%"><span class="light">{$town['name']}</span></td>
<td width="25%"><span class="light">Already mapped.</span></td>
<td width="35%"><span class="light">Location: $latitude $longitude</span></td>
<td width="15%"><span class="light">TP: {$town['travelpoints']}</span></td>
</tr>
HTML;
} else {
$page .= <<<HTML
<tr>
<td width="25%"><a href="/maps/{$town['id']}">{$town['name']}</a></td>
<td width="25%">Price: {$town['mapprice']} gold</td>
<td width="50%" colspan="2">Buy map to reveal details.</td>
</tr>
HTML;
}
}
$page .= <<<HTML
</table><br>
If you've changed your mind, you may also return back to <a hx-get="/" hx-target="#middle">town</a>.
HTML;
page_title('Maps');
return $page;
}
function buy_map(int $id): string
{
$town = get_town_by_id($id);
if ($town === false) redirect('/maps');
if (user()->gold < $town['mapprice']) {
$page = <<<HTML
You do not have enough gold to buy this map.<br><br>
You may return to <a hx-get="/" hx-target="#middle">town</a>, <a hx-get="/maps" hx-target="#middle">store</a>, or use the direction buttons on the left to start exploring.
HTML;
} elseif (is_post() && $_POST['buy']) {
user()->towns .= ",$id";
user()->gold -= $town['mapprice'];
user()->save();
$page = <<<HTML
Thank you for purchasing this map.<br><br>
You may return to <a hx-get="/" hx-target="#middle">town</a>, <a hx-get="/maps" hx-target="#middle">map shop</a>, or use the direction buttons on the left to start exploring.
HTML;
} elseif (is_post() && !$_POST['buy']) {
redirect('/maps');
} else {
$page = <<<HTML
You are buying the <b>{$town['name']}</b> map for {$town['mapprice']} gold. Is that ok?<br><br>
<form action="/maps/$id" method="post">
<button name="buy" value="1">Yes</button>
<button name="buy" value="0">No</button>
</form>
HTML;
}
page_title('Buying '.$town['name'].' Map');
return $page;
}
/**
* Send a user to a town from the Travel To menu.
*/
function travelto(int $id, bool $use_points = true): string
{
if (user()->currentaction == "Fighting") redirect('/fight');
$town = get_town_by_id($id);
$cost = $use_points ? $town['travelpoints'] : 0;
$mapped = explode(',', user()->towns);
$travelled = false;
if ($use_points && !in_array($id, $mapped)) {
// trying to teleport to this town when it is not mapped
redirect('/');
} elseif (user()->currenttp < $cost) {
$page = 'You do not have enough TP to travel here. Please <a href="/" hx-get="/" hx-target="#middle">go back</a> and try again when you get more TP.';
} elseif ((user()->latitude == $town['latitude']) && (user()->longitude == $town['longitude'])) {
if (!in_array($id, $mapped)) {
// add town to user's mapped if they travelled here
user()->towns .= ",$id";
$travelled = true;
$page = <<<HTML
You have discovered <b>{$town['name']}</b>! It has been added to your mapped towns.<br><br>
You may now <a href="/" hx-get="/" hx-target="#middle">enter this town</a>.
HTML;
} else {
$page = 'You are already in this town. <a href="/" hx-get="/" hx-target="#middle">Click here</a> to return.';
}
} else {
user()->latitude = $town['latitude'];
user()->longitude = $town['longitude'];
user()->currenttp -= $cost;
$travelled = true;
$page = 'You have travelled to <b>'.$town['name'].'</b>. You may now <a href="/" hx-get="/" hx-target="#middle">enter this town</a>.';
}
if ($travelled) {
user()->currentaction = 'In Town';
user()->save();
}
page_title('Travelling to '.$town['name']);
return $page;
}

View File

@ -1,226 +0,0 @@
<?php
namespace Users;
use Router;
function register_routes(Router $r): Router
{
$r->form('/login', 'Users\login');
$r->get('/logout', 'Users\logout');
$r->form('/register', 'Users\register');
$r->form('/lostpassword', 'Users\lostpassword');
$r->post('/changepassword', 'Users\changepassword');
$r->form('/verify', 'Users\verify');
$r->form('/settings', 'Users\settings');
return $r;
}
/**
* Displays the login page, and processes login requests.
*/
function login()
{
global $auth;
if (is_post()) {
$form = validate($_POST, [
'username' => ['length:3-18', 'alpha-spaces'],
'password' => ['length:6-255']
]);
if (!$form['valid']) exit(ul_from_validate_errors($form['errors']));
$good = $auth->login($form['data']['username'], $form['data']['password']);
if (!$good) exit('Invalid username or password. Please go back and try again.');
redirect('/');
}
page_title('Login');
return render('login');
}
/**
* Delete the current cookie and redirect to home.
*/
function logout()
{
global $auth;
$auth->logout();
redirect('/login');
}
/**
* Register a new account.
*/
function register()
{
if (isset($_POST["submit"])) {
$form = validate($_POST, [
'username' => ['length:3-18', 'alpha-spaces', 'unique:users,username'],
'email' => ['email', 'unique:users,email'],
'confirm_email' => ['confirm'],
'password' => ['length:6-255'],
'confirm_password' => ['confirm'],
'charclass' => ['in:1,2,3']
]);
if (!$form['valid']) {
$err = ul_from_validate_errors($form['errors']);
$page = "The following error(s) occurred when your account was being made:<br><span style=\"color:red;\">$err</span><br>Please go back and try again.";
} else {
$form = $form['data'];
$password = password_hash($form['password'], PASSWORD_ARGON2ID);
$token = env('verify_email') ? token(8) : 'g2g';
db()->query('INSERT INTO users (verify, username, password, email, charclass) VALUES (?, ?, ?, ?, ?)', [
$token, $form['username'], $password, $form['email'], $form['charclass']
]);
if (env('verify_email')) {
if (sendregmail($form['email'], $token)) {
$page = "Your account was created successfully.<br><br>You should receive an Account Verification email shortly. You will need the verification code contained in that email before you are allowed to log in. Once you have received the email, please visit the <a href=\"users.php?do=verify\">Verification Page</a> to enter your code and start playing.";
} else {
$page = "Your account was created successfully.<br><br>However, there was a problem sending your verification email. Please check with the game administrator to help resolve this problem.";
}
} else {
$page = "Your account was created succesfully.<br><br>You may now continue to the <a href=\"/login\">Login Page</a> and continue playing ".env('game_name')."!";
}
}
} else {
if (env('verify_email')) {
$verify_text = "<br><span class=\"small\">A verification code will be sent to the address above, and you will not be able to log in without first entering the code. Please be sure to enter your correct email address.</span>";
} else {
$verify_text = "";
}
$page = render('register', ['verify_text' => $verify_text]);
}
page_title('Register');
return $page;
}
function verify()
{
if (isset($_POST["submit"])) {
$u = trim($_POST['username'] ?? '');
$e = trim($_POST['email'] ?? '');
$t = trim($_POST['token'] ?? '');
$query = db()->query('SELECT id FROM users WHERE username=? AND email=? AND verify=? LIMIT 1;', [$u, $e, $t]);
if ($query === false) exit('Verification failed. Go back, double-check your details, and try again.');
db()->query("UPDATE users SET verify='g2g' WHERE username=?;", [$u]);
return "Your account was verified successfully.<br><br>You may now continue to the <a href=\"/login\">Login Page</a> and start playing the game.<br><br>Thanks for playing!";
}
return render('verify');
}
function lostpassword()
{
if (isset($_POST["submit"])) {
$e = trim($_POST['email'] ?? '');
if (!db()->exists('users', 'email', $e)) exit("No account with that email address.");
$newpass = token(16);
$hashed = password_hash($newpass, PASSWORD_ARGON2ID);
db()->query('UPDATE users SET password=? WHERE email=?;', [$hashed, $e]);
if (sendpassemail($e, $newpass)) {
return "Your new password was emailed to the address you provided.<br><br>Once you receive it, you may <a href=\"/login\">Log In</a> and continue playing.<br><br>Thank you.";
} else {
return "There was an error sending your new password.<br><br>Please check with the game administrator for more information.<br><br>We apologize for the inconvience.";
}
}
return render('lostpassword');
}
function changepassword()
{
global $auth;
if (isset($_POST["submit"])) {
$u = trim($_POST['username'] ?? '');
$p = $_POST['password'] ?? '';
$np = $_POST['new_password'] ?? '';
$np2 = $_POST['new_password2'] ?? '';
$user = db()->query("SELECT password FROM users WHERE username=? LIMIT 1;", [$u]);
$user = $user->fetchArray(SQLITE3_ASSOC);
if ($user === false) exit("No account with that username.");
if (!password_verify($p, $user['password'])) exit("The old password you provided was incorrect.");
if (empty($np) || strlen($np) < 6) {
$errors[] = 'New password is required and must be at least 6 characters long.';
}
if ($np2 !== $np) {
$errors[] = 'Verify New Password must match.';
}
$realnewpass = password_hash($np, PASSWORD_ARGON2ID);
db()->query('UPDATE users SET password=? WHERE username=?;', [$realnewpass, $u]);
$auth->logout();
return "Your password was changed successfully.<br><br>You have been logged out of the game to avoid errors.<br><br>Please <a href=\"/login\">log back in</a> to continue playing.";
}
}
function settings()
{
if (is_post()) {
$form = validate($_POST, [
'game_skin' => ['in:0,1']
]);
if (!$form['valid']) exit(ul_from_validate_errors($form['errors']));
$form = $form['data'];
user()->game_skin = $form['game_skin'];
user()->save();
$alert = '<div class="alert">Settings updated</div>';
return $alert . render('settings');
}
return render('settings');
}
function sendpassemail($emailaddress, $password)
{
$email = <<<HTML
You or someone using your email address submitted a Lost Password application on the {env('game_name')} server, located at {env('game_url')}.
We have issued you a new password so you can log back into the game.
Your new password is: $password
Thanks for playing.
HTML;
return send_email($emailaddress, env('game_name')." Lost Password", $email);
}
function sendregmail($emailaddress, $vercode)
{
$verurl = env('game_url') . "/verify";
$email = <<<HTML
You or someone using your email address recently signed up for an account on the {env('game_name')} server, located at {env('game_url')}.
This email is sent to verify your registration email. In order to begin using your account, you must verify your email address.
Please visit the Verification Page ($verurl) and enter the code below to activate your account.
Verification code: $vercode
If you were not the person who signed up for the game, please disregard this message. You will not be emailed again.
HTML;
return send_email($emailaddress, env('game_name')." Account Verification", $email);
}

View File

@ -1,76 +0,0 @@
<?php
require_once 'lib.php';
require_once 'router.php';
require_once 'auth.php';
require_once 'mail.php';
require_once 'render.php';
require_once 'actions/explore.php';
require_once 'actions/heal.php';
require_once 'actions/users.php';
require_once 'actions/help.php';
require_once 'actions/towns.php';
require_once 'actions/fight.php';
require_once 'actions/forum.php';
require_once 'actions/install.php';
require_once 'actions/admin.php';
require_once 'models/model.php';
require_once 'models/user.php';
env_load('../.env');
$uri = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
$GLOBALS['cache'] = [];
$GLOBALS['state'] = [];
/**
* These are table names whose data we want to be able to edit in the admin panel in bulk.
*/
define('ADMIN_BULK_DATA_STRUCTS', [
'users', 'items', 'drops', 'towns', 'monsters', 'levels', 'spells'
]);
if (!file_exists('../.installed') && $uri[0] !== 'install') { // need to install the game
redirect('/install');
} elseif (file_exists(('../.installed')) && $uri[0] === 'install') { // game is installed, go play!
redirect('/');
} elseif (file_exists(('../.installed')) && $uri[0] !== 'install') { // boostrap the game
if (!env('game_open')) {
echo Render\content('The game is currently closed for maintanence. Please check back later.');
exit;
}
$auth = new Auth;
// Login (or verify) if not logged in.
if (user() === false) {
if (!in_array($uri[0], ['login', 'register', 'verify', 'lostpassword', 'help'])) {
redirect('/login');
}
} elseif ($auth->good()) {
// Block user if he/she has been banned.
if (user()->authlevel === 2) {
exit("Your account has been banned.");
}
// Force verify if the user isn't verified yet.
if (env('verify_email') && user()->verify !== 'g2g' && !in_array($uri[0], ['verify', 'logout'])) {
redirect('/verify');
}
// Ensure the user can't use the admin panel.
if (user()->authlevel !== 1 && $uri[0] === 'admin') {
redirect('/');
}
// Update default page layout based on root endpoint
page_layout('layouts/primary');
if ($uri[0] === 'admin') page_layout('layouts/admin');
if ($uri[0] === 'help') page_layout('layouts/help');
user()->update_online_time();
} else {
$auth->logout();
redirect('/login');
}
}

View File

@ -1,546 +0,0 @@
<?php
require_once __DIR__ . '/database.php';
define('VERSION', '1.2.5');
define('BUILD', 'Reawaken');
define('START', microtime(true));
/**
* Open or get SQLite database connection.
*/
function db(): Database
{
return $GLOBALS['database'] ??= new Database(__DIR__ . '/../database.db');
}
/**
* Redirect to a different URL, exit.
*/
function redirect(string $location): void
{
if (is_htmx()) {
$target = isset($_SERVER['HTTP_HX_TARGET']) ? '#'.$_SERVER['HTTP_HX_TARGET'] : '#middle';
$json = json_encode(['path' => $location, 'target' => $target]);
header("HX-Location: $json");
} else {
header("Location: $location");
}
exit;
}
/**
* Render a view with the given data. Can be used redundantly within the template.
*/
function render(string $path_to_base_view, array $data = []): string|false
{
ob_start();
extract($data);
require "../templates/$path_to_base_view.php";
return ob_get_clean();
}
/**
* Replace tags with given content.
*/
function parse(string $template, array $array): string
{
return strtr($template, array_combine(
array_map(fn($key) => "{{{$key}}}", array_keys($array)),
array_values($array)
));
}
/**
* Change the SQLite3 datetime format (YYYY-MM-DD HH:MM:SS) into something friendlier.
*/
function pretty_date(string $uglydate): string
{
return date("l, F j, Y", mktime(
0,
0,
0,
substr($uglydate, 5, 2), // Month
substr($uglydate, 8, 2), // Day
substr($uglydate, 0, 4) // Year
));
}
/**
* Use htmlentities with UTF-8 encoding to ensure we're only outputting healthy, safe and effective HTML.
*/
function make_safe(string $content): string
{
return htmlentities($content, ENT_QUOTES, 'UTF-8');
}
/**
* Finalize admin page and output to browser.
*/
function display_admin($content, $title)
{
echo render('layouts/admin', [
"title" => $title,
"content" => $content
]);
exit;
}
/**
* Determine what game skin to use. If a user is logged in then it uses their setting, otherwise defaults to 0 (retro).
*/
function game_skin(): int
{
return user() !== false ? user()->game_skin : 0;
}
/**
* Get a town's data by it's coordinates.
*/
function get_town_by_xy(int $x, int $y): array|false
{
$cache_tag = "town-$x-$y";
if (!isset($GLOBALS['cache'][$cache_tag])) {
$query = db()->query('SELECT * FROM towns WHERE longitude = ? AND latitude = ? LIMIT 1;', [$x, $y]);
if ($query === false) return false;
$GLOBALS['cache'][$cache_tag] = $query->fetchArray(SQLITE3_ASSOC);
}
return $GLOBALS['cache'][$cache_tag];
}
/**
* Get a town's data by it's ID.
*/
function get_town_by_id(int $id): array|false
{
$query = db()->query('SELECT * FROM towns WHERE id = ? LIMIT 1;', [$id]);
if ($query === false) return false;
return $query->fetchArray(SQLITE3_ASSOC);
}
/**
* Get a user's data by their ID, username or email.
*/
function get_user(int|string $id, string $data = '*'): array|false
{
$query = db()->query(
"SELECT $data FROM users WHERE id=? OR username=? COLLATE NOCASE OR email=? COLLATE NOCASE LIMIT 1;",
[$id, $id, $id]
);
if ($query === false) return false;
return $query->fetchArray(SQLITE3_ASSOC);
}
/**
* Get an item by it's ID.
*/
function get_item(int $id): array|false
{
$query = db()->query('SELECT * FROM items WHERE id=? LIMIT 1;', [$id]);
if ($query === false) return false;
return $query->fetchArray(SQLITE3_ASSOC);
}
/**
* Get a drop by it's ID.
*/
function get_drop(int $id): array|false
{
$query = db()->query('SELECT * FROM drops WHERE id=? LIMIT 1;', [$id]);
if ($query === false) return false;
return $query->fetchArray(SQLITE3_ASSOC);
}
/**
* Get a spell by it's ID.
*/
function get_spell(int $id): array|false
{
$query = db()->query('SELECT * FROM spells WHERE id=? LIMIT 1;', [$id]);
if ($query === false) return false;
return $query->fetchArray(SQLITE3_ASSOC);
}
/**
* Get a monster by it's ID.
*/
function get_monster(int $id): array|false
{
$query = db()->query('SELECT * FROM monsters WHERE id=? LIMIT 1;', [$id]);
if ($query === false) return false;
return $query->fetchArray(SQLITE3_ASSOC);
}
/**
* Translate a Specials keyword to it's string.
*/
function special_to_string(string $special): string
{
return match ($special) {
'maxhp' => 'Max HP',
'maxmp' => 'Max MP',
'maxtp' => 'Max TP',
'goldbonus' => 'Gold Bonus (%)',
'expbonus' => 'Experience Bonus (%)',
'strength' => 'Strength',
'dexterity' => 'Dexterity',
'attackpower' => 'Attack Power',
'defensepower' => 'Defense Power',
default => $special
};
}
/**
* Generate a pretty dope token.
*/
function token($length = 32): string
{
return bin2hex(random_bytes($length));
}
/**
* Validate any given array of data against rules. Returns [valid, data, error]. Data contains the trimmed
* values from the input array. Note: all fields with rules are assumed to be required, unless the optional
* rule is used.
*
* Example: ['required', 'no-trim', 'length:5-20', 'alphanum-spaces']
*/
function validate(array $input_data, array $rules): array
{
$data = [];
$errors = [];
foreach ($rules as $field => $field_rules) {
$value = $input_data[$field] ?? null;
$field_name = ucfirst(str_replace('_', ' ', $field));
$is_required = true;
$default_value = null;
if (in_array('optional', $field_rules)) {
$is_required = false;
}
foreach ($field_rules as $rule) {
if (strpos($rule, 'default:') === 0) {
$default_value = substr($rule, 8);
break;
}
}
if (($value === null || $value === '') && $default_value !== null) {
$value = $default_value;
}
if (($value === null || $value === '') && !$is_required) continue;
if ($is_required && ($value === null || $value === '')) {
$errors[$field][] = "{$field_name} is required.";
continue;
}
if (!in_array('no-trim', $field_rules)) {
$value = trim($value);
}
$data[$field] = $value;
foreach ($field_rules as $rule) {
// Parse rule and arguments
if (strpos($rule, ':') !== false) {
list($rule_name, $rule_args) = explode(':', $rule, 2);
} else {
$rule_name = $rule;
$rule_args = null;
}
if ($rule_name === 'optional') continue;
switch ($rule_name) {
case 'bool':
if (!isset($input_data[$field]) || empty($value)) {
$value = false;
} else {
$value = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if ($value === null) {
$errors[$field][] = "{$field_name} must be a valid boolean value.";
}
}
break;
case 'length':
list($min, $max) = explode('-', $rule_args);
$len = strlen((string)$value);
if ($len < $min || $len > $max) {
$errors[$field][] = "{$field_name} must be between {$min} and {$max} characters.";
}
break;
case 'alphanum':
if (!preg_match('/^[a-zA-Z0-9]+$/', $value)) {
$errors[$field][] = "{$field_name} must contain only letters and numbers.";
}
break;
case 'alpha':
if (!preg_match('/^[a-zA-Z]+$/', $value)) {
$errors[$field][] = "{$field_name} must contain only letters and numbers.";
}
break;
case 'alphanum-spaces':
if (!preg_match('/^[a-zA-Z0-9\s_]+$/', $value)) {
$errors[$field][] = "{$field_name} must contain only letters, numbers, spaces, and underscores.";
}
break;
case 'alpha-spaces':
if (!preg_match('/^[a-zA-Z\s_]+$/', $value)) {
$errors[$field][] = "{$field_name} must contain only letters, numbers, spaces, and underscores.";
}
break;
case 'email':
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
$errors[$field][] = "{$field_name} must be a valid email address.";
}
break;
case 'int':
if (filter_var($value, FILTER_VALIDATE_INT) === false) {
$errors[$field][] = "{$field_name} must be an integer.";
}
break;
case 'min':
if ($value < $rule_args) {
$errors[$field][] = "{$field_name} must be at least {$rule_args}.";
}
break;
case 'max':
if ($value > $rule_args) {
$errors[$field][] = "{$field_name} must be no more than {$rule_args}.";
}
break;
case 'regex':
if (!preg_match($rule_args, $value)) {
$errors[$field][] = "{$field_name} does not match the required pattern.";
}
break;
case 'in':
$options = explode(',', $rule_args);
if (!in_array($value, $options)) {
$errors[$field][] = "{$field_name} must be one of: " . implode(', ', $options);
}
break;
case 'confirm':
$field_to_confirm = substr($field, 8);
$confirm_value = $data[$field_to_confirm] ?? '';
$confirm_field_name = ucfirst(str_replace('_', ' ', $field_to_confirm));
if ($value !== $confirm_value) {
$errors[$field][] = "{$field_name} must match {$confirm_field_name}.";
}
break;
case 'unique':
list($table, $column) = explode(',', $rule_args, 2);
if (db()->exists($table, $column, $value)) {
$errors[$field][] = "{$field_name} must be unique.";
}
break;
}
}
}
foreach ($input_data as $field => $value) {
if (!isset($data[$field])) $data[$field] = trim($value);
}
return [
'valid' => empty($errors),
'data' => $data,
'errors' => $errors
];
}
/**
* Generates a ul list from `validate()`'s errors.
*/
function ul_from_validate_errors(array $errors): string
{
$string = '<ul>';
foreach ($errors as $field => $errors) {
$string .= '<li>';
foreach ($errors as $error) $string .= $error;
$string .= '</li>';
}
return $string . '</ul>';
}
/**
* Load the environment variables from the .env file.
*/
function env_load(string $filePath): void
{
if (!file_exists($filePath)) throw new Exception("The .env file does not exist. (el)");
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
$line = trim($line);
// Skip lines that are empty after trimming or are comments
if ($line === '' || str_starts_with($line, '#')) continue;
// Skip lines without an '=' character
if (strpos($line, '=') === false) continue;
[$name, $value] = explode('=', $line, 2);
$name = trim($name);
$value = trim($value, " \t\n\r\0\x0B\"'"); // Trim whitespace and quotes
if (!array_key_exists($name, $_SERVER) && !array_key_exists($name, $_ENV)) {
putenv("$name=$value");
$_ENV[$name] = $value;
$_SERVER[$name] = $value;
}
}
}
/**
* Retrieve an environment variable.
*/
function env(string $key, mixed $default = null): mixed
{
$v = $_ENV[$key] ?? $_SERVER[$key] ?? (getenv($key) ?: $default);
return match(true) {
$v === 'true' => true,
$v === 'false' => false,
is_numeric($v) => (int) $v,
is_float($v) => (float) $v,
default => $v
};
}
/**
* Get the data on spells from a given list of IDs.
*/
function get_spells_from_list(array|string $spell_ids): array|false
{
if (is_string($spell_ids)) $spell_ids = explode(',', $spell_ids);
$placeholders = implode(',', array_fill(0, count($spell_ids), '?'));
$query = db()->query("SELECT id, name, type FROM spells WHERE id IN($placeholders)", $spell_ids);
if ($query === false) return false;
$rows = [];
while ($row = $query->fetchArray(SQLITE3_ASSOC)) $rows[] = $row;
return !empty($rows) ? $rows : false;
}
function generate_stat_bar(int $current, int $max): string
{
$percent = $max > 0 ? round(max(0, $current) / $max * 100, 4) : 0;
if ($percent < 0) $percent = 0;
if ($percent > 100) $percent = 100;
$color = $percent >= 66 ? 'green' : ($percent >= 33 ? 'yellow' : 'red');
return <<<HTML
<div class="stat-bar" style="width: 15px; height: 100px; border: solid 1px black;">
<div style="height: $percent%; background-image: url(/img/bars_$color.gif);"></div>
</div>
HTML;
}
function create_stat_table(): string
{
$stat_table = '<div class="stat-table">' .
'<div class="stat-row">' .
'<div class="stat-col">' . generate_stat_bar((int)user()->currenthp, (int)user()->maxhp) . '<div>HP</div></div>' .
'<div class="stat-col">' . generate_stat_bar((int)user()->currentmp, (int)user()->maxmp) . '<div>MP</div></div>' .
'<div class="stat-col">' . generate_stat_bar((int)user()->currenttp, (int)user()->maxtp) . '<div>TP</div></div>' .
'</div>' .
'</div>';
return $stat_table;
}
/**
* Returns the user in the GLOBALS state, if there is one. If not, populates it if there is a SESSION user_id.
*/
function user(): User|false
{
$GLOBALS['state']['user'] ??= (isset($_SESSION['user_id']) ? User::find($_SESSION['user_id']) : false);
return $GLOBALS['state']['user'];
}
/**
* Determine whether a request is from HTMX. If HTMX is trying to restore history, we will say no in order to render
* full pages.
*/
function is_htmx(): bool
{
if (isset($_SERVER['HTTP_HX_HISTORY_RESTORE_REQUEST']) && $_SERVER['HTTP_HX_HISTORY_RESTORE_REQUEST'] === 'true') return false;
return isset($_SERVER['HTTP_HX_REQUEST']) && $_SERVER['HTTP_HX_REQUEST'] === 'true';
}
/**
* Return whether the request is POST.
*/
function is_post(): bool
{
return $_SERVER['REQUEST_METHOD'] === 'POST';
}
/**
* Get the current page title per updates. Optionally set a new title.
*/
function page_title(string $new_title = ''): string
{
if ($new_title) return $GLOBALS['state']['new-page-title'] = $new_title;
return $GLOBALS['state']['new-page-title'] ?? env('game_name');
}
/**
* Render the response for the browser based on the request context. The main point is to seperate the handling
* of HTMX responses from normal responses.
*/
function render_response(array $uri, string $content): string
{
if ($uri[0] === 'babblebox') return $content;
if (is_htmx()) {
header('HX-Push-Url: '.$_SERVER['REQUEST_URI']);
$content .= '<title>'.page_title().'</title>';
$content .= Render\debug_db_info();
if (env('debug', false)) {
$content .= Render\debug_query_log();
}
if ($GLOBALS['state']['user-state-changed'] ?? false) {
$content .= Render\right_nav();
$content .= Render\left_nav();
}
}
return Render\content($content, page_layout());
}
/**
* Get/set page layout through GLOBALS state.
*/
function page_layout(string $layout = ''): string
{
if ($layout === '') return $GLOBALS['state']['page-layout'] ?? 'layouts/primary';
return $GLOBALS['state']['page-layout'] = $layout;
}

View File

@ -1,109 +0,0 @@
<?php
/**
* Send an email or log email details
*
* @param string $to Recipient email address
* @param string $subject Email subject
* @param string $message Email body
* @param array $options Optional configuration options
* @return bool Success status of email sending or logging
*/
function send_email(string $to, string $subject, string $message, array $options = []): bool
{
// Default configuration
$config = array_merge([
'from' => env('admin_email', 'noreply@'.$_SERVER['SERVER_NAME']),
'log_path' => '../logs/email.log',
'method' => 'smtp', // 'smtp' or 'log'
'smtp_host' => env('smtp_host', 'localhost'),
'smtp_port' => env('smtp_port', 25),
'smtp_username' => env('smtp_username', null),
'smtp_password' => env('smtp_password', null),
'smtp_encryption' => env('smtp_encryption', null)
], $options);
// Always send to log during debug
if (env('debug', false)) $config['method'] = 'log';
// Validate input
if (empty($to) || empty($subject) || empty($message)) {
error_log('Email sending failed: Missing required parameters');
return false;
}
// Prepare email headers
$headers = [
'From: ' . $config['from'],
'X-Mailer: PHP/' . phpversion()
];
// Choose sending method
switch ($config['method']) {
case 'log':
// Log email details to file
$logMessage = sprintf(
"[%s] To: %s, Subject: %s, Message:\n\n %s\n\n\n\n",
date('Y-m-d H:i:s'),
$to,
$subject,
$message
);
// Attempt to log to file
if (file_put_contents($config['log_path'], $logMessage, FILE_APPEND) === false) {
error_log('Failed to write to log file: ' . $config['log_path']);
return false;
}
return true;
case 'smtp':
default:
// Attempt to send via SMTP
try {
// Prepare SMTP connection
$smtpConfig = [
'host' => $config['smtp_host'],
'port' => $config['smtp_port'],
'username' => $config['smtp_username'],
'password' => $config['smtp_password'],
'encryption' => $config['smtp_encryption']
];
// Send email using PHP's mail function (basic SMTP)
$result = mail(
$to,
$subject,
$message,
implode("\r\n", $headers)
);
if (!$result) {
error_log('SMTP email sending failed');
return false;
}
return true;
} catch (Exception $e) {
error_log('Email sending error: ' . $e->getMessage());
return false;
}
}
}
// Example usage:
// Send via SMTP
// send_email('recipient@example.com', 'Test Subject', 'Email body text');
// Send via log
// send_email('recipient@example.com', 'Test Subject', 'Email body text', ['method' => 'log']);
// Customize SMTP settings
// send_email('recipient@example.com', 'Test Subject', 'Email body text', [
// 'method' => 'smtp',
// 'smtp_host' => 'smtp.yourserver.com',
// 'smtp_port' => 587,
// 'smtp_username' => 'your_username',
// 'smtp_password' => 'your_password',
// 'smtp_encryption' => 'tls'
// ]);

View File

@ -1,98 +0,0 @@
<?php
namespace Math;
/*
Internal math functions, such as to calculate EXP, HP, stats, etc.
*/
/**
* Calculates the ***total*** EXP required at a particular level in order to level up.
*/
function calculate_exp(int $level, int $growth_rate): int
{
if ($level < 1) throw new \InvalidArgumentException("Level must be 1 or greater");
// Growth rates:
// 0 = Erratic
// 1 = Fast
// 2 = Medium Fast
// 3 = Medium Slow
// 4 = Slow
// 5 = Fluctuating
if ($growth_rate < 0 || $growth_rate > 5) throw new \InvalidArgumentException("Growth rate must be between 0 and 5");
return match($growth_rate) {
0 => calculate_erratic_exp($level),
1 => (4 * pow($level, 3)) / 5,
2 => pow($level, 3),
3 => ((6 * pow($level, 3)) / 5) - (15 * pow($level, 2)) + (100 * $level) - 140,
4 => (5 * pow($level, 3)) / 4,
5 => calculate_fluctuating_exp($level),
};
}
/**
* Calculate the ***total*** EXP for a given level in the Erratic formula.
*/
function calculate_erratic_exp(int $level): int
{
if ($level <= 50) {
return (pow($level, 3) * (100 - $level)) / 50;
} elseif ($level <= 68) {
return (pow($level, 3) * (150 - $level)) / 100;
} elseif ($level <= 98) {
return (pow($level, 3) * ((1911 - (10 * $level)) / 3)) / 500;
} else {
return (pow($level, 3) * (160 - $level)) / 100;
}
}
/**
* Calculate the ***total*** EXP for a given level in the Fluctuating formula.
*/
function calculate_fluctuating_exp(int $level): int
{
if ($level <= 15) {
return pow($level, 3) * ((((($level + 1) / 3) + 24) / 50));
} elseif ($level <= 36) {
return pow($level, 3) * (($level + 14) / 50);
} else {
return pow($level, 3) * ((($level / 2) + 32) / 50);
}
}
/**
* Calculate a points total from a base. Modes: 1 (weak), 2 (normal), 3 (strong)
*/
function calculate_points(int $base_points, int $level, int $mode = 2): int
{
if ($level < 1) throw new \InvalidArgumentException("Level must be 1 or greater");
$growth_multiplier = match($mode) {
1 => 0.15,
2 => 0.3,
3 => 0.6,
default => throw new \InvalidArgumentException("Invalid mode. Use 1 (weak), 2 (normal), or 3 (strong)")
};
return floor((2 * $base_points * $level * $growth_multiplier) / 100) + $level + 10;
}
/**
* Calculate a stat total from a base. Modes: 1 (weak), 2 (normal), 3 (strong)
*/
function calculate_stat(int $base_stat, int $level, int $mode = 2): int
{
if ($level < 1) throw new \InvalidArgumentException("Level must be 1 or greater");
$growth_multiplier = match($mode) {
1 => 0.15,
2 => 0.3,
3 => 0.6,
default => throw new \InvalidArgumentException("Invalid mode. Use 1 (weak), 2 (normal), or 3 (strong)")
};
return floor((2 * $base_stat * $level * $growth_multiplier) / 100) + 5;
}

View File

@ -1,46 +0,0 @@
<?php
class Model
{
protected string $table_name = '';
protected array $original_data = [];
protected array $changes = [];
public function __construct(array $data)
{
$this->original_data = $data;
$this->changes = [];
}
public function __get(string $key): mixed
{
return array_key_exists($key, $this->changes) ? $this->changes[$key] : $this->original_data[$key] ?? false;
}
public function __set(string $key, mixed $value): void
{
if (array_key_exists($key, $this->original_data)) {
if ($value !== $this->original_data[$key]) $this->changes[$key] = $value;
} else {
throw new InvalidArgumentException("Attempted to write to $key, which doesn't exist in the data for this model.");
}
}
public function save(): bool
{
if (empty($this->changes)) return true;
$placeholders = [];
$values = [];
foreach ($this->changes as $key => $value) {
$placeholders[] = "$key=?";
$values[] = $value;
}
$values[] = $this->id;
$query = 'UPDATE ' . $this->table_name . ' SET ' . implode(', ', $placeholders) . ' WHERE id = ?;';
$result = db()->query($query, $values);
return $result === false ? false : true;
}
}

View File

@ -1,85 +0,0 @@
<?php
class User extends Model
{
protected string $table_name = 'users';
/**
* Find a user by their ID, username or email. Returns false on any failure.
*/
public static function find(int|string $id): User|false
{
$query = db()->query(
"SELECT * FROM users WHERE id=? OR username=? COLLATE NOCASE OR email=? COLLATE NOCASE LIMIT 1;",
[$id, $id, $id]
);
if ($query === false) return false;
$data = $query->fetchArray(SQLITE3_ASSOC);
if ($data === false) return false;
return new User($data);
}
/**
* Return a list of spells from this user's spell list.
*/
public function spells(): array|false
{
return get_spells_from_list($this->spells);
}
/**
* Restore all HP, MP, and TP values to their max.
*/
public function restore_points(): User
{
$this->currenthp = $this->maxhp;
$this->currentmp = $this->maxmp;
$this->currenttp = $this->maxtp;
return $this;
}
/**
* Sends a manual update to online time for this user.
*/
public function update_online_time(): void
{
if ($this->onlinetime && strtotime($this->onlinetime) > strtotime('-9 minutes')) return;
db()->query('UPDATE users SET onlinetime=CURRENT_TIMESTAMP WHERE id=?;', [$this->id]);
}
/**
* Heal HP by a given amount. Caps to max HP. Returns number of points restored.
*/
function restore_hp(int $amount): int
{
$initial_hp = $this->currenthp;
$this->currenthp += $amount;
if ($this->currenthp > $this->maxhp) $this->currenthp = $this->maxhp;
return $this->currenthp - $initial_hp;
}
/**
* Save works just as it does on the Model class. In our case, though, user state changing may necessitate
* OOB swaps for parts of the UI that have user data displayed. Left and right nav, for example. In these cases,
* we set a flag in GLOBALS state to signify this.
*/
public function save(): bool
{
if (empty($this->changes)) return true;
$placeholders = [];
$values = [];
foreach ($this->changes as $key => $value) {
$placeholders[] = "$key=?";
$values[] = $value;
}
$values[] = $this->id;
$query = 'UPDATE ' . $this->table_name . ' SET ' . implode(', ', $placeholders) . ' WHERE id = ?;';
$result = db()->query($query, $values);
if ($result === false) return false;
$GLOBALS['state']['user-state-changed'] = true;
return true;
}
}

View File

@ -1,62 +0,0 @@
<?php
namespace Render;
/*
This file contains functions to render various UI elements. The goal is to begin shifting elements in the game
to HTMX/AJAX for more fluid gameplay.
*/
/**
* Prepare content for final render. If the request is HTMX-based, will return just the content passed to it. Otherwise
* it will render() onto $layout with some additional bits.
*/
function content(string $content, string $layout = 'layouts/primary'): string
{
if (is_htmx()) return $content;
return render($layout, ['content' => $content]);
}
function debug_db_info(): string {
$total_time = round(microtime(true) - START, 4);
$htmx = is_htmx() ? ' (htmx)' : '';
return '<div id="debug-db-info" hx-swap-oob="true">'. $total_time . ' Seconds, ' . db()->count . ' Queries'.$htmx.'</div>';
}
function right_nav(): string
{
if (user() === false) return '';
// Flashy numbers if they're low
$hp = (user()->currenthp <= (user()->maxhp / 5)) ? "<blink><span class=\"highlight\"><b>*" . user()->currenthp . "*</b></span></blink>" : user()->currenthp;
$mp = (user()->currentmp <= (user()->maxmp / 5)) ? "<blink><span class=\"highlight\"><b>*" . user()->currentmp . "*</b></span></blink>" : user()->currentmp;
$template = render('right_nav', ['hp' => $hp, 'mp' => $mp]);
if (is_htmx()) $template = '<section id="right" hx-swap-oob="true">'.$template."</section>";
return $template;
}
function left_nav(): string
{
if (user() === false) return '';
$template = render('left_nav');
if (is_htmx()) $template = '<section id="left" hx-swap-oob="true">'.$template."</section>";
return $template;
}
function babblebox(): string
{
return render('babblebox', ['messages' => babblebox_messages()]);
}
function debug_query_log(): string
{
$html = '<pre id="debug-query-log" hx-swap-oob="true">';
foreach (db()->log as $record) {
$query_string = str_replace(["\r\n", "\n", "\r"], ' ', $record[0]);
$error_string = !empty($record[2]) ? '// '.$record[2] : '';
$html .= '<div>['.round($record[1], 2)."s] {$query_string}{$error_string}</div>";
}
return $html . '</pre>';
}

View File

@ -1,187 +0,0 @@
<?php
/**
* A radix-trie based URI router. Seperates URIs into chunks, then turns those chunks into an efficiently parsed
* trie. Supports URI variables!
*/
class Router
{
/**
* List of valid HTTP verbs.
*/
private const VALID_METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
/**
* The tree of currently registered routes.
*/
private array $routes = [];
/**
* Store the last inserted node so we can register middleware and attributes to it.
*/
private array $last_inserted_node;
/**
* Add a route to the route tree. The route must be a URI path, and contain dynamic segments
* using a colon prefix. (:id, :slug, etc)
*
* Example:
* `$r->add($routes, 'GET', '/posts/:id', function($id) { echo "Viewing post $id"; });`
*/
public function add(string $method, string $route, callable $handler): Router
{
$this->validateMethod($method);
$this->validateRoute($route);
$segments = $route === '/' ? [''] : explode('/', trim($route, '/'));
$node = &$this->routes;
foreach ($segments as $segment) {
$segment = str_starts_with($segment, ':') ? ':x' : $segment;
if ($segment === '') continue;
$node = &$node[$segment];
}
$node[$method] = [
'handler' => $handler,
'middleware' => []
];
$this->last_inserted_node = &$node[$method];
return $this;
}
/**
* Perform a lookup in the route tree for a given method and URI. Returns an array with a result code,
* a handler if found, and any dynamic parameters. Codes are 200 for success, 404 for not found, and
* 405 for method not allowed.
*
* @return array ['code', 'handler', 'params']
*/
public function lookup(string $method, string $uri): array|int
{
$node = $this->routes;
$params = [];
if ($uri === '/') return $node[$method] ?? 405;
foreach (explode('/', trim($uri, '/')) as $segment) {
if (isset($node[$segment])) {
$node = $node[$segment];
continue;
}
if (isset($node[':x'])) {
$params[] = $segment;
$node = $node[':x'];
continue;
}
return 404;
}
$node[$method]['params'] = $params;
return $node[$method] ?? 405;
}
/**
* Add a middleware function to the last inserted node's stack.
*/
public function middleware(callable $middleware): Router
{
$this->last_inserted_node['middleware'][] = $middleware;
return $this;
}
/**
* Shorthand to register a GET route.
*/
public function get(string $route, callable $handler): Router
{
return $this->add('GET', $route, $handler);
}
/**
* Shorthand to register a POST route.
*/
public function post(string $route, callable $handler): Router
{
return $this->add('POST', $route, $handler);
}
/**
* Shorthand to register a PUT route.
*/
public function put(string $route, callable $handler): Router
{
return $this->add('PUT', $route, $handler);
}
/**
* Shorthand to register a DELETE route.
*/
public function delete(string $route, callable $handler): Router
{
return $this->add('DELETE', $route, $handler);
}
/**
* Shorthand to register a PATCH route.
*/
public function patch(string $route, callable $handler): Router
{
return $this->add('PATCH', $route, $handler);
}
/**
* Register multiple verbs to the same route.
*/
public function many(array $methods, string $route, callable $handler): Router
{
foreach ($methods as $method) $this->add($method, $route, $handler);
return $this;
}
/**
* Register all verbs to the same route.
*/
public function any(string $route, callable $handler): Router
{
foreach (SELF::VALID_METHODS as $method) $this->add($method, $route, $handler);
return $this;
}
/**
* Some pages function entirely as forms; thus we can shorthand a GET/POST route.
*/
public function form(string $route, callable $handler): Router
{
return $this->many(['GET', 'POST'], $route, $handler);
}
/**
* Validate the given method against valid HTTP verbs.
*/
private function validateMethod(string $method): void
{
if (!in_array($method, self::VALID_METHODS)) {
throw new InvalidArgumentException("Invalid HTTP method: $method");
}
}
/**
* Validate that a new route follows expected formatting.
*/
private function validateRoute(string $route): void
{
if ($route === '') {
throw new InvalidArgumentException("Route cannot be empty");
}
// Ensure route starts with a slash
if (!str_starts_with($route, '/')) {
throw new InvalidArgumentException("Route must start with a '/'");
}
}
}

View File

@ -1,19 +1,19 @@
<h2>Editing <?= $drop['name'] ?></h2>
<form action="/admin/drops/<?= $drop['id'] ?>" method="post" hx-post="/admin/drops/<?= $drop['id'] ?>" hx-target="#main">
<h2>Editing <?php echo $drop['name'] ?></h2>
<form action="/admin/drops/<?php echo $drop['id'] ?>" method="post" hx-post="/admin/drops/<?php echo $drop['id'] ?>" hx-target="#main">
<table width="90%">
<tr><td width="20%">ID:</td><td><?= $drop['id'] ?></td></tr>
<tr><td width="20%">Name:</td><td><input type="text" name="name" value="<?= $drop['name'] ?>"></td></tr>
<tr><td width="20%">ID:</td><td><?php echo $drop['id'] ?></td></tr>
<tr><td width="20%">Name:</td><td><input type="text" name="name" value="<?php echo $drop['name'] ?>"></td></tr>
<tr>
<td width="20%">Monster Level:</td>
<td>
<input type="number" name="mlevel" value="<?= $drop['mlevel'] ?>"><br>
<input type="number" name="mlevel" value="<?php echo $drop['mlevel'] ?>"><br>
<span class="small">Minimum monster level that will drop this item.</span>
</td>
</tr>
<tr>
<td width="20%">Attribute 1:</td>
<td>
<input type="text" name="attribute1" value="<?= $drop['attribute1'] ?>"><br>
<input type="text" name="attribute1" value="<?php echo $drop['attribute1'] ?>"><br>
<span class="small">Must be a special code. First attribute cannot be disabled. Edit this field very
carefully because mistakes to formatting or field names can create problems in the game.</span>
</td>
@ -21,7 +21,7 @@
<tr>
<td width="20%">Attribute 2:</td>
<td>
<input type="text" name="attribute2" value="<?= $drop['attribute2'] ?>"><br>
<input type="text" name="attribute2" value="<?php echo $drop['attribute2'] ?>"><br>
<span class="small">Should be either a special code or <span class="highlight">X</span> to
disable. Edit this field very carefully because mistakes to formatting or field names can create
problems in the game.</span>

View File

@ -1,34 +1,34 @@
<h2>Edit <?= $item['name'] ?></h2>
<form action="/admin/items/<?= $item['id'] ?>" method="post" hx-post="/admin/items/<?= $item['id'] ?>" hx-target="#main">
<h2>Edit <?php echo $item['name'] ?></h2>
<form action="/admin/items/<?php echo $item['id'] ?>" method="post" hx-post="/admin/items/<?php echo $item['id'] ?>" hx-target="#main">
<table>
<tr><td width="20%">ID:</td><td><?= $item['id'] ?></td></tr>
<tr><td width="20%">ID:</td><td><?php echo $item['id'] ?></td></tr>
<tr>
<td width="20%">Name:</td>
<td><input type="text" name="name" value="<?= $item['name'] ?>"></td>
<td><input type="text" name="name" value="<?php echo $item['name'] ?>"></td>
</tr>
<tr>
<td width="20%">Type:</td>
<td><select name="type">
<option value="1" <?= $item['type'] === 1 ? 'selected' : '' ?>>Weapon</option>
<option value="2" <?= $item['type'] === 2 ? 'selected' : '' ?>>Armor</option>
<option value="3" <?= $item['type'] === 3 ? 'selected' : '' ?>>Shield</option>
<option value="1" <?php echo $item['type'] === 1 ? 'selected' : '' ?>>Weapon</option>
<option value="2" <?php echo $item['type'] === 2 ? 'selected' : '' ?>>Armor</option>
<option value="3" <?php echo $item['type'] === 3 ? 'selected' : '' ?>>Shield</option>
</select></td>
</tr>
<tr>
<td width="20%">Cost:</td>
<td><input type="text" name="buycost" value="<?= $item['buycost'] ?>"> gold</td>
<td><input type="text" name="buycost" value="<?php echo $item['buycost'] ?>"> gold</td>
</tr>
<tr>
<td width="20%">Attribute:</td>
<td>
<input type="number" name="attribute" value="<?= $item['attribute'] ?>"><br>
<input type="number" name="attribute" value="<?php echo $item['attribute'] ?>"><br>
<span class="small">How much the item adds to total attackpower (weapons) or defensepower (armor/shields).</span>
</td>
</tr>
<tr>
<td width="20%">Special:</td>
<td>
<input type="text" name="special" value="<?= $item['special'] ?>"><br>
<input type="text" name="special" value="<?php echo $item['special'] ?>"><br>
<span class="small">Should be either a special code or <span class="highlight">X</span> to disable. Edit
this field very carefully because mistakes to formatting or field names can create problems in the game.</span>
</td>

View File

@ -1,29 +1,29 @@
<h2>Edit Level <?= $level['id'] ?></h2>
<h2>Edit Level <?php echo $level['id'] ?></h2>
Experience values for each level should be the cumulative total amount of experience up to this point. All other values should be only the new amount to add this level.<br><br>
<form action="/admin/levels" method="post" hx-post="/admin/levels" hx-target="#main">
<input type="hidden" name="save" value="true">
<input type="hidden" name="level" value="<?= $level['id'] ?>">
<input type="hidden" name="level" value="<?php echo $level['id'] ?>">
<table>
<colgroup><col><col></colgroup>
<tbody>
<tr>
<td>ID:</td>
<td><?= $level['id'] ?></td>
<td><?php echo $level['id'] ?></td>
</tr>
<tr><td colspan="2"></td></tr>
<?php foreach ([1, 2, 3] as $n): ?>
<?php $class_name = env("class_{$n}_name"); ?>
<tr><td><?= $class_name ?> EXP</td> <td><input type="number" name="<?= $n ?>_exp" value="<?= $level["{$n}_exp"] ?>"></td></tr>
<tr><td><?= $class_name ?> HP</td> <td><input type="number" name="<?= $n ?>_hp" value="<?= $level["{$n}_hp"] ?>"></td></tr>
<tr><td><?= $class_name ?> MP</td> <td><input type="number" name="<?= $n ?>_mp" value="<?= $level["{$n}_mp"] ?>"></td></tr>
<tr><td><?= $class_name ?> TP</td> <td><input type="number" name="<?= $n ?>_tp" value="<?= $level["{$n}_tp"] ?>"></td></tr>
<tr><td><?= $class_name ?> Strength</td> <td><input type="number" name="<?= $n ?>_strength" value="<?= $level["{$n}_strength"] ?>"></td></tr>
<tr><td><?= $class_name ?> Dexterity</td><td><input type="number" name="<?= $n ?>_dexterity" value="<?= $level["{$n}_dexterity"] ?>"></td></tr>
<tr><td><?= $class_name ?> Spells</td> <td><input type="number" name="<?= $n ?>_spells" value="<?= $level["{$n}_spells"] ?>"></td></tr>
<?= $n !== 3 ? '<tr><td colspan="2"></td></tr>' : '' ?>
<?php $class_name = DragonKnight\env("class_{$n}_name"); ?>
<tr><td><?php echo $class_name ?> EXP</td> <td><input type="number" name="<?php echo $n ?>_exp" value="<?php echo $level["{$n}_exp"] ?>"></td></tr>
<tr><td><?php echo $class_name ?> HP</td> <td><input type="number" name="<?php echo $n ?>_hp" value="<?php echo $level["{$n}_hp"] ?>"></td></tr>
<tr><td><?php echo $class_name ?> MP</td> <td><input type="number" name="<?php echo $n ?>_mp" value="<?php echo $level["{$n}_mp"] ?>"></td></tr>
<tr><td><?php echo $class_name ?> TP</td> <td><input type="number" name="<?php echo $n ?>_tp" value="<?php echo $level["{$n}_tp"] ?>"></td></tr>
<tr><td><?php echo $class_name ?> Strength</td> <td><input type="number" name="<?php echo $n ?>_strength" value="<?php echo $level["{$n}_strength"] ?>"></td></tr>
<tr><td><?php echo $class_name ?> Dexterity</td><td><input type="number" name="<?php echo $n ?>_dexterity" value="<?php echo $level["{$n}_dexterity"] ?>"></td></tr>
<tr><td><?php echo $class_name ?> Spells</td> <td><input type="number" name="<?php echo $n ?>_spells" value="<?php echo $level["{$n}_spells"] ?>"></td></tr>
<?php echo $n !== 3 ? '<tr><td colspan="2"></td></tr>' : '' ?>
<?php endforeach; ?>
</tbody>
</table>

View File

@ -1,56 +1,56 @@
<h2>Edit <?= $monster['name'] ?></h2>
<h2>Edit <?php echo $monster['name'] ?></h2>
<form action="/admin/monsters/<?= $monster['id'] ?>"
<form action="/admin/monsters/<?php echo $monster['id'] ?>"
method="post"
hx-post="/admin/monsters/<?= $monster['id'] ?>"
hx-post="/admin/monsters/<?php echo $monster['id'] ?>"
hx-target="#main">
<table>
<colgroup><col><col></colgroup>
<tbody>
<tr>
<td>ID</td>
<td><?= $monster['id'] ?></td>
<td><?php echo $monster['id'] ?></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?= $monster['name'] ?>"></td>
<td><input type="text" name="name" value="<?php echo $monster['name'] ?>"></td>
</tr>
<tr>
<td>Max HP</td>
<td><input type="number" name="maxhp" value="<?= $monster['maxhp'] ?>"></td>
<td><input type="number" name="maxhp" value="<?php echo $monster['maxhp'] ?>"></td>
</tr>
<tr>
<td>Max Damage</td>
<td>
<input type="number" name="maxdam" value="<?= $monster['maxdam'] ?>"><br>
<input type="number" name="maxdam" value="<?php echo $monster['maxdam'] ?>"><br>
<span class="small">Compares to player's attack power.</span>
</td>
</tr>
<tr>
<td>Armor</td>
<td>
<input type="number" name="armor" value="<?= $monster['armor'] ?>"><br>
<input type="number" name="armor" value="<?php echo $monster['armor'] ?>"><br>
<span class="small">Compares to player's defense power.</span>
</td>
</tr>
<tr>
<td>Monster Level</td>
<td>
<input type="number" name="level" value="<?= $monster['level'] ?>"><br>
<input type="number" name="level" value="<?php echo $monster['level'] ?>"><br>
<span class="small">Determines spawn location and item drops.</span>
</td>
</tr>
<tr>
<td>Max EXP</td>
<td>
<input type="number" name="maxexp" value="<?= $monster['maxexp'] ?>"><br>
<input type="number" name="maxexp" value="<?php echo $monster['maxexp'] ?>"><br>
<span class="small">Max experience gained from defeating monster.</span>
</td>
</tr>
<tr>
<td>Max Gold</td>
<td>
<input type="number" name="maxgold" value="<?= $monster['maxgold'] ?>"><br>
<input type="number" name="maxgold" value="<?php echo $monster['maxgold'] ?>"><br>
<span class="small">Max gold gained from defeating monster.</span>
</td>
</tr>
@ -58,9 +58,9 @@
<td>Immunity</td>
<td>
<select name="immune">
<option value="0" <?= $monster['immune'] == 0 ? 'selected' : '' ?>>None</option>
<option value="1" <?= $monster['immune'] == 1 ? 'selected' : '' ?>>Hurt Spells</option>
<option value="2" <?= $monster['immune'] == 2 ? 'selected' : '' ?>>Hurt & Sleep Spells</option>
<option value="0" <?php echo $monster['immune'] == 0 ? 'selected' : '' ?>>None</option>
<option value="1" <?php echo $monster['immune'] == 1 ? 'selected' : '' ?>>Hurt Spells</option>
<option value="2" <?php echo $monster['immune'] == 2 ? 'selected' : '' ?>>Hurt & Sleep Spells</option>
</select>
<br>
<span class="small">Some monsters may not be hurt by certain spells.</span>

View File

@ -1,21 +1,21 @@
<h2>Edit <?= $spell['name'] ?></h2>
<h2>Edit <?php echo $spell['name'] ?></h2>
<form action="/admin/spells/<?= $spell['id'] ?>" method="post", hx-post="/admin/spells/<?= $spell['id'] ?>" hx-target="#main">
<form action="/admin/spells/<?php echo $spell['id'] ?>" method="post", hx-post="/admin/spells/<?php echo $spell['id'] ?>" hx-target="#main">
<table>
<colgroup><col><col></colgroup>
<tbody>
<tr>
<td>ID</td>
<td><?= $spell['id'] ?></td>
<td><?php echo $spell['id'] ?></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?= $spell['name'] ?>"></td>
<td><input type="text" name="name" value="<?php echo $spell['name'] ?>"></td>
</tr>
<tr>
<td>MP</td>
<td>
<input type="number" name="mp" value="<?= $spell['mp'] ?>">
<input type="number" name="mp" value="<?php echo $spell['mp'] ?>">
<br>
<span class="small">MP required to cast spell.</span>
</td>
@ -23,7 +23,7 @@
<tr>
<td>Attribute</td>
<td>
<input type="number" name="attribute" value="<?= $spell['attribute'] ?>">
<input type="number" name="attribute" value="<?php echo $spell['attribute'] ?>">
<br>
<span class="small">Numeric value of the spell's effect. Ties with type, below.</span>
</td>
@ -32,11 +32,11 @@
<td>Type</td>
<td>
<select name="type">
<option value="1" <?= $spell['type'] == 1 ? 'selected' : '' ?>>Heal</option>
<option value="2" <?= $spell['type'] == 2 ? 'selected' : '' ?>>Hurt</option>
<option value="3" <?= $spell['type'] == 3 ? 'selected' : '' ?>>Sleep</option>
<option value="4" <?= $spell['type'] == 4 ? 'selected' : '' ?>>Uber Attack</option>
<option value="5" <?= $spell['type'] == 5 ? 'selected' : '' ?>>Uber Defense</option>
<option value="1" <?php echo $spell['type'] == 1 ? 'selected' : '' ?>>Heal</option>
<option value="2" <?php echo $spell['type'] == 2 ? 'selected' : '' ?>>Hurt</option>
<option value="3" <?php echo $spell['type'] == 3 ? 'selected' : '' ?>>Sleep</option>
<option value="4" <?php echo $spell['type'] == 4 ? 'selected' : '' ?>>Uber Attack</option>
<option value="5" <?php echo $spell['type'] == 5 ? 'selected' : '' ?>>Uber Defense</option>
</select>
<br>
<span class="small">

View File

@ -1,51 +1,51 @@
<h2>Edit <?= $town['name'] ?></h2>
<form action="/admin/towns/<?= $town['id'] ?>" method="post" hx-post="/admin/towns/<?= $town['id'] ?>" hx-target="#main">
<h2>Edit <?php echo $town['name'] ?></h2>
<form action="/admin/towns/<?php echo $town['id'] ?>" method="post" hx-post="/admin/towns/<?php echo $town['id'] ?>" hx-target="#main">
<table>
<colgroup><col><col></colgroup>
<tbody>
<tr>
<td>ID</td> <td><?= $town['id'] ?></td>
<td>ID</td> <td><?php echo $town['id'] ?></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?= $town['name'] ?>"></td>
<td><input type="text" name="name" value="<?php echo $town['name'] ?>"></td>
</tr>
<tr>
<td>Latitude</td>
<td>
<input type="number" name="latitude" value="<?= $town['latitude'] ?>"><br>
<input type="number" name="latitude" value="<?php echo $town['latitude'] ?>"><br>
<span class="small">Positive or negative integer.</span>
</td>
</tr>
<tr>
<td>Longitude</td>
<td>
<input type="number" name="longitude" value="<?= $town['longitude'] ?>" /><br>
<input type="number" name="longitude" value="<?php echo $town['longitude'] ?>" /><br>
<span class="small">Positive or negative integer.</span>
</td>
</tr>
<tr>
<td>Inn Price</td>
<td><input type="number" name="innprice" value="<?= $town['innprice'] ?>"> gold</td>
<td><input type="number" name="innprice" value="<?php echo $town['innprice'] ?>"> gold</td>
</tr>
<tr>
<td>Map Price</td>
<td>
<input type="number" name="mapprice" value="<?= $town['mapprice'] ?>"> gold<br>
<input type="number" name="mapprice" value="<?php echo $town['mapprice'] ?>"> gold<br>
<span class="small">How much it costs to buy the map to this town.</span>
</td>
</tr>
<tr>
<td>Travel Points</td>
<td>
<input type="number" name="travelpoints" value="<?= $town['travelpoints'] ?>"><br>
<input type="number" name="travelpoints" value="<?php echo $town['travelpoints'] ?>"><br>
<span class="small">How many TP are consumed when travelling to this town.</span>
</td>
</tr>
<tr>
<td>Items List</td>
<td>
<input type="text" name="itemslist" value="<?= $town['itemslist'] ?>"><br>
<input type="text" name="itemslist" value="<?php echo $town['itemslist'] ?>"><br>
<span class="small">Comma-separated list of item ID numbers available for purchase at this town.
(Example: <span class="highlight">1,2,3,6,9,10,13,20</span>)</span>
</td>

View File

@ -1,86 +1,86 @@
<h2>Edit <?= $user['username'] ?></h2>
<form action="/admin/users/<?= $user['id'] ?>" method="post" hx-post="/admin/users/<?= $user['id'] ?>" hx-target="#main">
<h2>Edit <?php echo $user['username'] ?></h2>
<form action="/admin/users/<?php echo $user['id'] ?>" method="post" hx-post="/admin/users/<?php echo $user['id'] ?>" hx-target="#main">
<table>
<colgroup><col><col></colgroup>
<tbody>
<tr><td>ID</td><td><?= $user['id'] ?></td></tr>
<tr><td>Username</td><td><input type="text" name="username" value="<?= $user['username'] ?>"></td></tr>
<tr><td>Email</td><td><input type="text" name="email" value="<?= $user['email'] ?>"></td></tr>
<tr><td>Register Date</td><td><?= pretty_date($user['regdate']) ?></td></tr>
<tr><td>Last Online</td><td><?= pretty_date($user['onlinetime']) ?></td></tr>
<tr><td>ID</td><td><?php echo $user['id'] ?></td></tr>
<tr><td>Username</td><td><input type="text" name="username" value="<?php echo $user['username'] ?>"></td></tr>
<tr><td>Email</td><td><input type="text" name="email" value="<?php echo $user['email'] ?>"></td></tr>
<tr><td>Register Date</td><td><?php echo pretty_date($user['regdate']) ?></td></tr>
<tr><td>Last Online</td><td><?php echo pretty_date($user['onlinetime']) ?></td></tr>
<tr><td>Auth Level</td><td>
<select name="authlevel">
<option value="0" <?= $user['authlevel'] == 0 ? 'selected' : '' ?>>User</option>
<option value="1" <?= $user['authlevel'] == 1 ? 'selected' : '' ?>>Admin</option>
<option value="2" <?= $user['authlevel'] == 2 ? 'selected' : '' ?>>Blocked</option>
<option value="0" <?php echo $user['authlevel'] == 0 ? 'selected' : '' ?>>User</option>
<option value="1" <?php echo $user['authlevel'] == 1 ? 'selected' : '' ?>>Admin</option>
<option value="2" <?php echo $user['authlevel'] == 2 ? 'selected' : '' ?>>Blocked</option>
</select><br>
<span class="small">Set to "Blocked" to temporarily (or permanently) ban a user.</span>
</td></tr>
<tr><td colspan="2"></td></tr>
<tr><td>Latitude</td><td><input type="number" name="latitude" value="<?= $user['latitude'] ?>" /></td></tr>
<tr><td>Longitude</td><td><input type="number" name="longitude" value="<?= $user['longitude'] ?>" /></td></tr>
<tr><td>Latitude</td><td><input type="number" name="latitude" value="<?php echo $user['latitude'] ?>" /></td></tr>
<tr><td>Longitude</td><td><input type="number" name="longitude" value="<?php echo $user['longitude'] ?>" /></td></tr>
<tr><td>Character Class</td><td>
<select name="charclass">
<option value="1" <?= $user['charclass'] == 1 ? 'selected' : '' ?>><?= env('class_1_name') ?></option>
<option value="2" <?= $user['charclass'] == 2 ? 'selected' : '' ?>><?= env('class_2_name') ?></option>
<option value="3" <?= $user['charclass'] == 3 ? 'selected' : '' ?>><?= env('class_3_name') ?></option>
<option value="1" <?php echo $user['charclass'] == 1 ? 'selected' : '' ?>><?php echo DragonKnight\env('class_1_name') ?></option>
<option value="2" <?php echo $user['charclass'] == 2 ? 'selected' : '' ?>><?php echo DragonKnight\env('class_2_name') ?></option>
<option value="3" <?php echo $user['charclass'] == 3 ? 'selected' : '' ?>><?php echo DragonKnight\env('class_3_name') ?></option>
</select>
</td></tr>
<tr><td colspan="2"></td></tr>
<tr><td>Current Action</td><td><input type="text" name="currentaction" value="<?= $user['currentaction'] ?>" /></td></tr>
<tr><td>Current Fight</td><td><input type="number" name="currentfight" value="<?= $user['currentfight'] ?>" /></td></tr>
<tr><td>Current Monster</td><td><input type="number" name="currentmonster" value="<?= $user['currentmonster'] ?>" /></td></tr>
<tr><td>Current Monster HP</td><td><input type="number" name="currentmonsterhp" value="<?= $user['currentmonsterhp'] ?>" /></td></tr>
<tr><td>Current Monster Sleep</td><td><input type="number" name="currentmonsterimmune" value="<?= $user['currentmonsterimmune'] ?>" /></td></tr>
<tr><td>Current Monster Immune</td><td><input type="number" name="currentmonstersleep" value="<?= $user['currentmonstersleep'] ?>" /></td></tr>
<tr><td>Current Uber Damage</td><td><input type="number" name="currentuberdamage" value="<?= $user['currentuberdamage'] ?>" /></td></tr>
<tr><td>Current Uber Defense</td><td><input type="number" name="currentuberdefense" value="<?= $user['currentuberdefense'] ?>" /></td></tr>
<tr><td>Current Action</td><td><input type="text" name="currentaction" value="<?php echo $user['currentaction'] ?>" /></td></tr>
<tr><td>Current Fight</td><td><input type="number" name="currentfight" value="<?php echo $user['currentfight'] ?>" /></td></tr>
<tr><td>Current Monster</td><td><input type="number" name="currentmonster" value="<?php echo $user['currentmonster'] ?>" /></td></tr>
<tr><td>Current Monster HP</td><td><input type="number" name="currentmonsterhp" value="<?php echo $user['currentmonsterhp'] ?>" /></td></tr>
<tr><td>Current Monster Sleep</td><td><input type="number" name="currentmonsterimmune" value="<?php echo $user['currentmonsterimmune'] ?>" /></td></tr>
<tr><td>Current Monster Immune</td><td><input type="number" name="currentmonstersleep" value="<?php echo $user['currentmonstersleep'] ?>" /></td></tr>
<tr><td>Current Uber Damage</td><td><input type="number" name="currentuberdamage" value="<?php echo $user['currentuberdamage'] ?>" /></td></tr>
<tr><td>Current Uber Defense</td><td><input type="number" name="currentuberdefense" value="<?php echo $user['currentuberdefense'] ?>" /></td></tr>
<tr><td colspan="2"></td></tr>
<tr><td>Current HP</td><td><input type="number" name="currenthp" value="<?= $user['currenthp'] ?>" /></td></tr>
<tr><td>Current MP</td><td><input type="number" name="currentmp" value="<?= $user['currentmp'] ?>" /></td></tr>
<tr><td>Current TP</td><td><input type="number" name="currenttp" value="<?= $user['currenttp'] ?>" /></td></tr>
<tr><td>Max HP</td><td><input type="number" name="maxhp" value="<?= $user['maxhp'] ?>" /></td></tr>
<tr><td>Max MP</td><td><input type="number" name="maxmp" value="<?= $user['maxmp'] ?>" /></td></tr>
<tr><td>Max TP</td><td><input type="number" name="maxtp" value="<?= $user['maxtp'] ?>" /></td></tr>
<tr><td>Current HP</td><td><input type="number" name="currenthp" value="<?php echo $user['currenthp'] ?>" /></td></tr>
<tr><td>Current MP</td><td><input type="number" name="currentmp" value="<?php echo $user['currentmp'] ?>" /></td></tr>
<tr><td>Current TP</td><td><input type="number" name="currenttp" value="<?php echo $user['currenttp'] ?>" /></td></tr>
<tr><td>Max HP</td><td><input type="number" name="maxhp" value="<?php echo $user['maxhp'] ?>" /></td></tr>
<tr><td>Max MP</td><td><input type="number" name="maxmp" value="<?php echo $user['maxmp'] ?>" /></td></tr>
<tr><td>Max TP</td><td><input type="number" name="maxtp" value="<?php echo $user['maxtp'] ?>" /></td></tr>
<tr><td colspan="2"></td></tr>
<tr><td>Level</td><td><input type="number" name="level" value="<?= $user['level'] ?>" /></td></tr>
<tr><td>Gold</td><td><input type="number" name="gold" value="<?= $user['gold'] ?>" /></td></tr>
<tr><td>Experience</td><td><input type="number" name="experience" value="<?= $user['experience'] ?>" /></td></tr>
<tr><td>Gold Bonus</td><td><input type="number" name="goldbonus" value="<?= $user['goldbonus'] ?>" /></td></tr>
<tr><td>EXP Bonus</td><td><input type="number" name="expbonus" value="<?= $user['expbonus'] ?>" /></td></tr>
<tr><td>Strength</td><td><input type="number" name="strength" value="<?= $user['strength'] ?>" /></td></tr>
<tr><td>Dexterity</td><td><input type="number" name="dexterity" value="<?= $user['dexterity'] ?>" /></td></tr>
<tr><td>Attack Power</td><td><input type="number" name="attackpower" value="<?= $user['attackpower'] ?>" /></td></tr>
<tr><td>Defense Power</td><td><input type="number" name="defensepower" value="<?= $user['defensepower'] ?>" /></td></tr>
<tr><td>Level</td><td><input type="number" name="level" value="<?php echo $user['level'] ?>" /></td></tr>
<tr><td>Gold</td><td><input type="number" name="gold" value="<?php echo $user['gold'] ?>" /></td></tr>
<tr><td>Experience</td><td><input type="number" name="experience" value="<?php echo $user['experience'] ?>" /></td></tr>
<tr><td>Gold Bonus</td><td><input type="number" name="goldbonus" value="<?php echo $user['goldbonus'] ?>" /></td></tr>
<tr><td>EXP Bonus</td><td><input type="number" name="expbonus" value="<?php echo $user['expbonus'] ?>" /></td></tr>
<tr><td>Strength</td><td><input type="number" name="strength" value="<?php echo $user['strength'] ?>" /></td></tr>
<tr><td>Dexterity</td><td><input type="number" name="dexterity" value="<?php echo $user['dexterity'] ?>" /></td></tr>
<tr><td>Attack Power</td><td><input type="number" name="attackpower" value="<?php echo $user['attackpower'] ?>" /></td></tr>
<tr><td>Defense Power</td><td><input type="number" name="defensepower" value="<?php echo $user['defensepower'] ?>" /></td></tr>
<tr><td colspan="2"></td></tr>
<tr><td>Weapon ID</td><td><input type="number" name="weaponid" value="<?= $user['weaponid'] ?>"></td></tr>
<tr><td>Armor ID</td><td><input type="number" name="armorid" value="<?= $user['armorid'] ?>"></td></tr>
<tr><td>Shield ID</td><td><input type="number" name="shieldid" value="<?= $user['shieldid'] ?>"></td></tr>
<tr><td>Slot 1 ID</td><td><input type="number" name="slot1id" value="<?= $user['slot1id'] ?>"></td></tr>
<tr><td>Slot 2 ID</td><td><input type="number" name="slot2id" value="<?= $user['slot2id'] ?>"></td></tr>
<tr><td>Slot 3 ID</td><td><input type="number" name="slot3id" value="<?= $user['slot3id'] ?>"></td></tr>
<tr><td>Weapon Name</td><td><input type="text" name="weaponname" value="<?= $user['weaponname'] ?>"></td></tr>
<tr><td>Armor Name</td><td><input type="text" name="armorname" value="<?= $user['armorname'] ?>"></td></tr>
<tr><td>Shield Name</td><td><input type="text" name="shieldname" value="<?= $user['shieldname'] ?>"></td></tr>
<tr><td>Slot 1 Name</td><td><input type="text" name="slot1name" value="<?= $user['slot1name'] ?>"></td></tr>
<tr><td>Slot 2 Name</td><td><input type="text" name="slot2name" value="<?= $user['slot2name'] ?>"></td></tr>
<tr><td>Slot 3 Name</td><td><input type="text" name="slot3name" value="<?= $user['slot3name'] ?>"></td></tr>
<tr><td>Weapon ID</td><td><input type="number" name="weaponid" value="<?php echo $user['weaponid'] ?>"></td></tr>
<tr><td>Armor ID</td><td><input type="number" name="armorid" value="<?php echo $user['armorid'] ?>"></td></tr>
<tr><td>Shield ID</td><td><input type="number" name="shieldid" value="<?php echo $user['shieldid'] ?>"></td></tr>
<tr><td>Slot 1 ID</td><td><input type="number" name="slot1id" value="<?php echo $user['slot1id'] ?>"></td></tr>
<tr><td>Slot 2 ID</td><td><input type="number" name="slot2id" value="<?php echo $user['slot2id'] ?>"></td></tr>
<tr><td>Slot 3 ID</td><td><input type="number" name="slot3id" value="<?php echo $user['slot3id'] ?>"></td></tr>
<tr><td>Weapon Name</td><td><input type="text" name="weaponname" value="<?php echo $user['weaponname'] ?>"></td></tr>
<tr><td>Armor Name</td><td><input type="text" name="armorname" value="<?php echo $user['armorname'] ?>"></td></tr>
<tr><td>Shield Name</td><td><input type="text" name="shieldname" value="<?php echo $user['shieldname'] ?>"></td></tr>
<tr><td>Slot 1 Name</td><td><input type="text" name="slot1name" value="<?php echo $user['slot1name'] ?>"></td></tr>
<tr><td>Slot 2 Name</td><td><input type="text" name="slot2name" value="<?php echo $user['slot2name'] ?>"></td></tr>
<tr><td>Slot 3 Name</td><td><input type="text" name="slot3name" value="<?php echo $user['slot3name'] ?>"></td></tr>
<tr><td colspan="2"></td></tr>
<tr><td>Drop Code</td><td><input type="number" name="dropcode" value="<?= $user['dropcode'] ?>"></td></tr>
<tr><td>Spells</td><td><input type="text" name="spells" value="<?= $user['spells'] ?>"></td></tr>
<tr><td>Towns</td><td><input type="text" name="towns" value="<?= $user['towns'] ?>"></td></tr>
<tr><td>Drop Code</td><td><input type="number" name="dropcode" value="<?php echo $user['dropcode'] ?>"></td></tr>
<tr><td>Spells</td><td><input type="text" name="spells" value="<?php echo $user['spells'] ?>"></td></tr>
<tr><td>Towns</td><td><input type="text" name="towns" value="<?php echo $user['towns'] ?>"></td></tr>
</tbody>
</table>

View File

@ -8,8 +8,8 @@
<td width="20%"><span class="highlight">Game Open:</span></td>
<td>
<select name="gameopen">
<option value="1" <?= env('game_open') ? 'selected' : '' ?>>Open</option>
<option value="0" <?= !env('game_open') ? 'selected' : '' ?>>Closed</option>
<option value="1" <?php echo DragonKnight\env('game_open') ? 'selected' : '' ?>>Open</option>
<option value="0" <?php echo ! DragonKnight\env('game_open') ? 'selected' : '' ?>>Closed</option>
</select><br>
<span class="small">Close the game if you are upgrading or working on settings and don't want to
cause odd errors for end-users. Closing the game will completely halt all activity.</span>
@ -18,14 +18,14 @@
<tr>
<td width="20%">Game Name:</td>
<td>
<input type="text" name="gamename" value="<?= env('game_name') ?>"><br>
<input type="text" name="gamename" value="<?php echo DragonKnight\env('game_name') ?>"><br>
<span class="small">Change this if you want to change to call your game something different.</span>
</td>
</tr>
<tr>
<td width="20%">Game URL:</td>
<td>
<input type="text" name="gameurl" value="<?= env('game_url') ?>"><br>
<input type="text" name="gameurl" value="<?php echo DragonKnight\env('game_url') ?>"><br>
<span class="small">Please specify the full URL to your game installation
("https://www.dragonknight.com/"). This gets used in the registration email sent to users. If
you leave this field blank or incorrect, users may not be able to register correctly.</span>
@ -34,7 +34,7 @@
<tr>
<td width="20%">Admin Email:</td>
<td>
<input type="text" name="adminemail" value="<?= env('admin_email') ?>"><br>
<input type="text" name="adminemail" value="<?php echo DragonKnight\env('admin_email') ?>"><br>
<span class="small">Please specify your email address. This gets used when the game has to send an
email to users.</span>
</td>
@ -42,7 +42,7 @@
<tr>
<td width="20%">Map Size:</td>
<td>
<input type="number" name="gamesize" value="<?= env('game_size') ?>"><br>
<input type="number" name="gamesize" value="<?php echo DragonKnight\env('game_size') ?>"><br>
<span class="small">
Default is 250. This is the size of each map quadrant. Note that monster
levels increase every 5 spaces, so you should ensure that you have at least (map size / 5)
@ -55,8 +55,8 @@
<td width="20%">Email Verification:</td>
<td>
<select name="verifyemail">
<option value="0" <?= !env('verify_email') ? 'selected' : '' ?>>Disabled</option>
<option value="1" <?= env('verify_email') ? 'selected' : '' ?>>Enabled</option>
<option value="0" <?php echo ! DragonKnight\env('verify_email') ? 'selected' : '' ?>>Disabled</option>
<option value="1" <?php echo DragonKnight\env('verify_email') ? 'selected' : '' ?>>Enabled</option>
</select><br>
<span class="small">Make users verify their email address for added security.</span>
</td>
@ -65,8 +65,8 @@
<td width="20%">Show News:</td>
<td>
<select name="shownews">
<option value="0" <?= !env('show_news') ? 'selected' : '' ?>>No</option>
<option value="1" <?= env('show_news') ? 'selected' : '' ?>>Yes</option>
<option value="0" <?php echo ! DragonKnight\env('show_news') ? 'selected' : '' ?>>No</option>
<option value="1" <?php echo DragonKnight\env('show_news') ? 'selected' : '' ?>>Yes</option>
</select><br>
<span class="small">Toggle display of the Latest News box in towns.
</td>
@ -75,8 +75,8 @@
<td width="20%">Show Who's Online:</td>
<td>
<select name="showonline">
<option value="0" <?= !env('show_online') ? 'selected' : '' ?>>No</option>
<option value="1" <?= env('show_online') ? 'selected' : '' ?>>Yes</option>
<option value="0" <?php echo ! DragonKnight\env('show_online') ? 'selected' : '' ?>>No</option>
<option value="1" <?php echo DragonKnight\env('show_online') ? 'selected' : '' ?>>Yes</option>
</select><br>
<span class="small">Toggle display of the Who's Online box in towns.</span>
</td>
@ -85,23 +85,23 @@
<td width="20%">Show Babblebox:</td>
<td>
<select name="showbabble">
<option value="0" <?= !env('show_babble') ? 'selected' : '' ?>>No</option>
<option value="1" <?= env('show_babble') ? 'selected' : '' ?>>Yes</option>
<option value="0" <?php echo ! DragonKnight\env('show_babble') ? 'selected' : '' ?>>No</option>
<option value="1" <?php echo DragonKnight\env('show_babble') ? 'selected' : '' ?>>Yes</option>
</select><br>
<span class="small">Toggle display of the Babble Box in towns.</span>
</td>
</tr>
<tr>
<td width="20%">Class 1 Name:</td>
<td><input type="text" name="class1name" value="<?= env('class_1_name') ?>"><br></td>
<td><input type="text" name="class1name" value="<?php echo DragonKnight\env('class_1_name') ?>"><br></td>
</tr>
<tr>
<td width="20%">Class 2 Name:</td>
<td><input type="text" name="class2name" value="<?= env('class_2_name') ?>"><br></td>
<td><input type="text" name="class2name" value="<?php echo DragonKnight\env('class_2_name') ?>"><br></td>
</tr>
<tr>
<td width="20%">Class 3 Name:</td>
<td><input type="text" name="class3name" value="<?= env('class_3_name') ?>"><br></td>
<td><input type="text" name="class3name" value="<?php echo DragonKnight\env('class_3_name') ?>"><br></td>
</tr>
</table>

View File

@ -1,6 +1,6 @@
<div id="babblebox">
<div class="messages" hx-get="/babblebox/messages" hx-trigger="every 5s">
<?= $messages ?>
<?php echo $messages ?>
</div>
<form hx-post="/babblebox" hx-target="#babblebox > .messages" style="margin-top: 1rem;">

View File

@ -1,10 +1,10 @@
<table width="100%">
<tr><td class="title"><img src="/img/title_fighting.gif" alt="Fighting" /></td></tr>
<tr><td>
You are fighting a <b><?= $page['monstername'] ?></b><br><br>
<?= $page['monsterhp'] ?>
<?= $page['yourturn'] ?>
<?= $page['monsterturn'] ?>
<?= $page['command'] ?>
You are fighting a <b><?php echo $page['monstername'] ?></b><br><br>
<?php echo $page['monsterhp'] ?>
<?php echo $page['yourturn'] ?>
<?php echo $page['monsterturn'] ?>
<?php echo $page['command'] ?>
</td></tr>
</table>

View File

@ -3,14 +3,14 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= page_title() ?></title>
<title><?php echo DragonKnight\page_title() ?></title>
<link rel="stylesheet" href="/css/admin.css">
<script src="/js/htmx.js"></script>
</head>
<body>
<div id="admin-container">
<header>
<h1><?= env('game_name') ?></h1>
<h1><?php echo DragonKnight\env('game_name') ?></h1>
<h3>Admin</h3>
</header>
<main>
@ -33,18 +33,20 @@
</nav>
<section id="main">
<?= $content ?>
<?php echo $content ?>
</section>
</main>
<footer>
<div>Powered by <a href="/" target="_new">Dragon Knight</a></div>
<div>&copy; 2024 Sharkk</div>
<?= Render\debug_db_info(); ?>
<div>Version <?= VERSION ?> <?= BUILD ?></div>
<?php echo DragonKnight\Render::debug_db_info(); ?>
<div>Version <?php echo DragonKnight\DragonKnight::VERSION ?> <?php echo DragonKnight\DragonKnight::BUILD ?></div>
</footer>
<?php if (env('debug', false)) echo Render\debug_query_log(); ?>
<?php if (DragonKnight\env('debug', false)) {
echo DragonKnight\Render::debug_query_log();
} ?>
</div>
</body>
</html>

View File

@ -3,25 +3,25 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= env('game_name', 'Dragon Knight') ?> Help</title>
<title><?php echo DragonKnight\env('game_name', 'Dragon Knight') ?> Help</title>
<link rel="stylesheet" href="/css/help.css">
</head>
<body>
<a name="top"></a>
<h1><?= env('game_name', 'Dragon Knight') ?> Help</h1>
<h1><?php echo DragonKnight\env('game_name', 'Dragon Knight') ?> Help</h1>
[ <a href="/help">Back to Help</a> ]<br>
[ <a href="/">Return to Game</a> ]
<br><br><hr>
<?= $content ?>
<?php echo $content ?>
<br><br>
<footer>
<div>Powered by <a href="/" target="_new">Dragon Knight</a></div>
<div>&copy; 2024 Sharkk</div>
<div>Version <?= $version ?> <?= $build ?></div>
<div>Version <?php echo $version ?> <?php echo $build ?></div>
</footer>
</body>
</html>

View File

@ -2,10 +2,10 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $title ?></title>
<title><?php echo $title ?></title>
<link rel="stylesheet" href="/css/dk.css">
</head>
<body>
<?= $content ?>
<?php echo $content ?>
</body>
</html>

View File

@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= page_title() ?></title>
<title><?php echo DragonKnight\page_title() ?></title>
<link rel="stylesheet" href="/css/dk.css">
<script src="/js/htmx.js"></script>
@ -20,12 +20,12 @@
}
</script>
</head>
<body class="skin-<?= game_skin() ?>">
<body class="skin-<?php echo DragonKnight\game_skin() ?>">
<div id="game-container">
<header>
<a href="/"><img id="logo" src="/img/logo.gif" alt="<?= env('game_name', 'Dragon Knight') ?>" title="<?= env('game_name', 'Dragon Knight') ?>"></a>
<a href="/"><img id="logo" src="/img/logo.gif" alt="<?php echo DragonKnight\env('game_name', 'Dragon Knight') ?>" title="<?php echo DragonKnight\env('game_name', 'Dragon Knight') ?>"></a>
<nav>
<?php if (user() !== false): ?>
<?php if (DragonKnight\user() !== false): ?>
<a href='/logout'><img src='/img/button_logout.gif' alt='Log Out' title='Log Out'></a>
<?php else: ?>
<a href='/login'><img src='/img/button_login.gif' alt='Log In' title='Log In'></a>
@ -36,19 +36,21 @@
</header>
<main>
<section id="left"><?= Render\left_nav() ?></section>
<section id="middle"><?= $content ?></section>
<section id="right"><?= Render\right_nav() ?></section>
<section id="left"><?php echo DragonKnight\Render::left_nav() ?></section>
<section id="middle"><?php echo $content ?></section>
<section id="right"><?php echo DragonKnight\Render::right_nav() ?></section>
</main>
<footer>
<div>Powered by <a href="/" target="_new">Dragon Knight</a></div>
<div>&copy; 2024 Sharkk</div>
<?= Render\debug_db_info(); ?>
<div>Version <?= VERSION ?> <?= BUILD ?></div>
<?php echo DragonKnight\Render::debug_db_info(); ?>
<div>Version <?php echo DragonKnight\DragonKnight::VERSION ?> <?php echo DragonKnight\DragonKnight::BUILD ?></div>
</footer>
<?php if (env('debug', false)) echo Render\debug_query_log(); ?>
<?php if (DragonKnight\env('debug', false)) {
echo DragonKnight\Render::debug_query_log();
} ?>
</div>
</body>
</html>

View File

@ -1,14 +1,22 @@
<section>
<div class="title"><img src="/img/button_location.gif" alt="Location" title="Location"></div>
Currently: <?= user()->currentaction ?><br>
Currently: <?php echo DragonKnight\user()->currentaction ?><br>
<?php
$lat = user()->latitude;
$lon = user()->longitude;
if ($lat < 0) { $lat = ($lat * -1) . "S"; } else { $lat .= "N"; }
if ($lon < 0) { $lon = ($lon * -1) . "W"; } else { $lon .= "E"; }
$lat = DragonKnight\user()->latitude;
$lon = DragonKnight\user()->longitude;
if ($lat < 0) {
$lat = ($lat * -1).'S';
} else {
$lat .= 'N';
}
if ($lon < 0) {
$lon = ($lon * -1).'W';
} else {
$lon .= 'E';
}
?>
Latitude: <?= $lat ?><br>
Longitude: <?= $lon ?><br>
Latitude: <?php echo $lat ?><br>
Longitude: <?php echo $lon ?><br>
<a href="javascript:openmappopup()">View Map</a><br>
<form action="/move" method="post" hx-post="/move" hx-target="#middle" class="move-compass">
<button name="direction" value="north" class="north">North</button>
@ -23,15 +31,15 @@
<section>
<div class="title"><img src="/img/button_towns.gif" alt="Towns" title="Towns"></div>
<?php
if (user()->currentaction == 'In Town') {
$town = get_town_by_xy((int) user()->latitude, (int) user()->longitude);
if (DragonKnight\user()->currentaction == 'In Town') {
$town = DragonKnight\get_town_by_xy((int) DragonKnight\user()->latitude, (int) DragonKnight\user()->longitude);
echo "Welcome to <b>{$town['name']}</b>.<br><br>";
}
?>
Travel To:<br>
<?php
$town_list = explode(",", user()->towns);
$towns = db()->query('SELECT * FROM towns ORDER BY id;');
$town_list = explode(',', DragonKnight\user()->towns);
$towns = DragonKnight\db()->query('SELECT * FROM towns ORDER BY id;');
$mapped = false;
while ($row = $towns->fetchArray(SQLITE3_ASSOC)) {
$mapped = true;
@ -41,7 +49,9 @@
HTML;
}
}
if (!$mapped) echo 'You have no towns mapped.';
if (! $mapped) {
echo 'You have no towns mapped.';
}
?>
</section>
@ -50,7 +60,7 @@
<a href="/" hx-get="/" hx-target="#middle">Home</a><br>
<a href="/forum" hx-get="/forum" hx-target="#middle">Forum</a><br>
<a href="/settings">Settings</a><br>
<?php if (user()->authlevel === 1): ?>
<?php if (DragonKnight\user()->authlevel === 1): ?>
<a href="/admin">Admin</a><br>
<?php endif; ?>
<a href="/help">Help</a><br>

View File

@ -4,14 +4,14 @@
<tr><td>Password:</td><td><input type="password" name="password"></td></tr>
<tr><td>Verify Password:</td><td><input type="password" name="confirm_password"><br>Passwords must be 10 alphanumeric characters or less.<br><br><br></td></tr>
<tr><td>Email Address:</td><td><input type="email" name="email"></td></tr>
<tr><td>Verify Email:</td><td><input type="email" name="confirm_email"><?= $verify_text ?><br><br><br></td></tr>
<tr><td>Verify Email:</td><td><input type="email" name="confirm_email"><?php echo $verify_text ?><br><br><br></td></tr>
<tr>
<td>Character Class:</td>
<td>
<select name="charclass">
<option value="1"><?= env('class_1_name') ?></option>
<option value="2"><?= env('class_2_name') ?></option>
<option value="3"><?= env('class_3_name') ?></option>
<option value="1"><?php echo DragonKnight\env('class_1_name') ?></option>
<option value="2"><?php echo DragonKnight\env('class_2_name') ?></option>
<option value="3"><?php echo DragonKnight\env('class_3_name') ?></option>
</select>
</td>
</tr>

View File

@ -1,37 +1,39 @@
<section>
<div class="title"><img src="/img/button_character.gif" alt="Character" title="Character"></div>
<b><?= user()->username ?></b><br>
Level: <?= user()->level ?><br>
Exp: <?= number_format(user()->experience) ?><br>
Gold: <?= number_format(user()->gold) ?><br>
HP: <?= $hp ?><br>
MP: <?= $mp ?><br>
TP: <?= user()->currenttp ?><br><br>
<?= create_stat_table() ?><br>
<b><?php echo DragonKnight\user()->username ?></b><br>
Level: <?php echo DragonKnight\user()->level ?><br>
Exp: <?php echo number_format(DragonKnight\user()->experience) ?><br>
Gold: <?php echo number_format(DragonKnight\user()->gold) ?><br>
HP: <?php echo $hp ?><br>
MP: <?php echo $mp ?><br>
TP: <?php echo DragonKnight\user()->currenttp ?><br><br>
<?php echo DragonKnight\create_stat_table() ?><br>
<a href="javascript:opencharpopup()">Extended Stats</a>
</section>
<section>
<div class="title"><img src="/img/button_inventory.gif" alt="Inventory" title="Inventory"></div>
<img src="/img/icon_weapon.gif" alt="Weapon" title="Weapon"> <?= user()->weaponname ?><br>
<img src="/img/icon_armor.gif" alt="Armor" title="Armor"> <?= user()->armorname ?><br>
<img src="/img/icon_shield.gif" alt="Shield" title="Shield"> <?= user()->shieldname ?><br>
Slot 1: <?= user()->slot1name ?><br>
Slot 2: <?= user()->slot2name ?><br>
Slot 3: <?= user()->slot3name ?>
<img src="/img/icon_weapon.gif" alt="Weapon" title="Weapon"> <?php echo DragonKnight\user()->weaponname ?><br>
<img src="/img/icon_armor.gif" alt="Armor" title="Armor"> <?php echo DragonKnight\user()->armorname ?><br>
<img src="/img/icon_shield.gif" alt="Shield" title="Shield"> <?php echo DragonKnight\user()->shieldname ?><br>
Slot 1: <?php echo DragonKnight\user()->slot1name ?><br>
Slot 2: <?php echo DragonKnight\user()->slot2name ?><br>
Slot 3: <?php echo DragonKnight\user()->slot3name ?>
</section>
<section>
<div class="title"><img src="/img/button_fastspells.gif" alt="Fast Spells" title="Fast Spells"></div>
<?php
$user_spells = user()->spells();
$user_spells = DragonKnight\user()->spells();
if ($user_spells !== false) {
foreach ($user_spells as $spell) {
// list only healing spells for now
if ($spell['type'] === 1) echo <<<HTML
if ($spell['type'] === 1) {
echo <<<HTML
<a href="/spell/{$spell['id']}" hx-get="/spell/{$spell['id']}" hx-target="#middle">{$spell['name']}</a><br>
HTML;
}
}
} else {
echo 'None';
}

View File

@ -1,36 +1,38 @@
<div class="title"><img src="/img/button_character.gif" alt="Character" title="Character"></div>
<b><?= $char->username ?></b><br><br>
<b><?php echo $char->username ?></b><br><br>
Class: <?= match ($char->charclass) {
1 => env('class_1_name'),
2 => env('class_2_name'),
3 => env('class_3_name')
Class: <?php echo match ($char->charclass) {
1 => DragonKnight\env('class_1_name'),
2 => DragonKnight\env('class_2_name'),
3 => DragonKnight\env('class_3_name')
}; ?><br><br>
Level: <?= $char->level ?><br>
Experience: <?= number_format($char->experience) ?>
<?php if ($char->expbonus !== 0): ?> <span class="light">(<?= $char->expbonus > 0 ? '+' : '' ?>) <?= $char->expbonus ?>%)</span> <?php endif; ?><br>
Next Level: <?php if ($char->level < 99) { echo number_format($level[$char->charclass."_exp"]); } else { ?> <span class="light">None</span> <?php } ?><br>
Gold: <?= number_format($char->gold) ?>
<?php if ($char->goldbonus !== 0): ?> <span class="light">(<?= $char->goldbonus > 0 ? '+' : '' ?>) <?= $char->goldbonus ?>%)</span> <?php endif; ?><br>
Hit Points: <?= number_format($char->currenthp) ?> / <?= number_format($char->maxhp) ?><br>
Magic Points: <?= number_format($char->currentmp) ?> / <?= number_format($char->maxmp) ?><br>
Travel Points: <?= number_format($char->currenttp) ?> / <?= number_format($char->maxtp) ?><br><br>
Level: <?php echo $char->level ?><br>
Experience: <?php echo number_format($char->experience) ?>
<?php if ($char->expbonus !== 0): ?> <span class="light">(<?php echo $char->expbonus > 0 ? '+' : '' ?>) <?php echo $char->expbonus ?>%)</span> <?php endif; ?><br>
Next Level: <?php if ($char->level < 99) {
echo number_format($level[$char->charclass.'_exp']);
} else { ?> <span class="light">None</span> <?php } ?><br>
Gold: <?php echo number_format($char->gold) ?>
<?php if ($char->goldbonus !== 0): ?> <span class="light">(<?php echo $char->goldbonus > 0 ? '+' : '' ?>) <?php echo $char->goldbonus ?>%)</span> <?php endif; ?><br>
Hit Points: <?php echo number_format($char->currenthp) ?> / <?php echo number_format($char->maxhp) ?><br>
Magic Points: <?php echo number_format($char->currentmp) ?> / <?php echo number_format($char->maxmp) ?><br>
Travel Points: <?php echo number_format($char->currenttp) ?> / <?php echo number_format($char->maxtp) ?><br><br>
Strength: <?= number_format($char->strength) ?><br>
Dexterity: <?= number_format($char->dexterity) ?><br>
Attack Power: <?= number_format($char->attackpower) ?><br>
Defense Power: <?= number_format($char->defensepower) ?><br>
Strength: <?php echo number_format($char->strength) ?><br>
Dexterity: <?php echo number_format($char->dexterity) ?><br>
Attack Power: <?php echo number_format($char->attackpower) ?><br>
Defense Power: <?php echo number_format($char->defensepower) ?><br>
<br>
<div class="title"><img src="/img/button_inventory.gif" alt="Inventory" title="Inventory"></div>
<img src="/img/icon_weapon.gif" alt="Weapon" title="Weapon"> <?= $char->weaponname ?><br>
<img src="/img/icon_armor.gif" alt="Armor" title="Armor"> <?= $char->armorname ?><br>
<img src="/img/icon_shield.gif" alt="Shield" title="Shield"> <?= $char->shieldname ?><br>
Slot 1: <?= $char->slot1name ?><br>
Slot 2: <?= $char->slot2name ?><br>
Slot 3: <?= $char->slot3name ?>
<img src="/img/icon_weapon.gif" alt="Weapon" title="Weapon"> <?php echo $char->weaponname ?><br>
<img src="/img/icon_armor.gif" alt="Armor" title="Armor"> <?php echo $char->armorname ?><br>
<img src="/img/icon_shield.gif" alt="Shield" title="Shield"> <?php echo $char->shieldname ?><br>
Slot 1: <?php echo $char->slot1name ?><br>
Slot 2: <?php echo $char->slot2name ?><br>
Slot 3: <?php echo $char->slot3name ?>
<br>
<div class="title"><img src="/img/button_spells.gif" alt="Spells" title="Spells"></div>
<?= $magic_list ?>
<?php echo $magic_list ?>

View File

@ -1,6 +1,6 @@
<div class="town-content">
<div class="options">
<div class="title"><img src="/img/town_<?= $town['id'] ?>.gif" alt="Welcome to <?= $town['name'] ?>" title="Welcome to <?= $town['name'] ?>"></div>
<div class="title"><img src="/img/town_<?php echo $town['id'] ?>.gif" alt="Welcome to <?php echo $town['name'] ?>" title="Welcome to <?php echo $town['name'] ?>"></div>
<b>Town Options:</b><br>
<ul hx-boost="true" hx-target="#middle">
<li><a href="/inn">Rest at the Inn</a></li>
@ -10,15 +10,15 @@
</div>
<div class="news">
<?= $news ?>
<?php echo $news ?>
</div>
<div class="whos-online">
<?= $whos_online ?>
<?php echo $whos_online ?>
</div>
<div class="babblebox">
<div class="title">Babblebox</div>
<?= Render\babblebox() ?>
<?php echo DragonKnight\Render::babblebox() ?>
</div>
</div>