Dragon-Knight/server/models/Player.php

74 lines
2.9 KiB
PHP

<?php
class Player
{
public static function create(array $data): int
{
// get the player's class
$class = Classes::get($data['class_id'] ?? 1);
if ($class == false) die('Player::create: Invalid class selected. ' . print_r($data, true));
// get player level
$l = $data['level'] ?? 1;
// calculate player stats
$data['hp'] = $data['max_hp'] = $data['max_hp'] ?? ($class['start_hp'] + ($class['growth_hp'] * ($l - 1)));
$data['mp'] = $data['max_mp'] = $data['max_mp'] ?? ($class['start_mp'] + ($class['growth_mp'] * ($l - 1)));
$data['tp'] = $data['max_tp'] = $data['max_tp'] ?? (5 + (App::$s['tp_growth'] * ($l - 1)));
$data['str'] = $data['str'] ?? ($class['start_str'] + ($class['growth_str'] * ($l - 1)));
$data['atk'] = $data['atk'] ?? ($class['start_atk'] + ($class['growth_atk'] * ($l - 1)));
$data['def'] = $data['def'] ?? ($class['start_def'] + ($class['growth_def'] * ($l - 1)));
$data['dex'] = $data['dex'] ?? ($class['start_dex'] + ($class['growth_dex'] * ($l - 1)));
$data['stat_points'] = $data['stat_points'] ?? (App::$s['stat_point_gain'] * ($l - 1));
$data['exp2l'] = $data['exp2l'] ?? expToLevel($l + 1);
// award spells
if (!isset($data['spells']) || empty($data['spells'])) {
$spells = Classes::spellsAtLevel($class['id'], $l);
$data['spells'] = implode(',', $spells);
}
// compress data and generate placeholers
$keys = implode(', ', array_keys($data));
$placeholders = implode(', ', array_fill(0, count($data), '?'));
// insert into db
App::$db->do("INSERT INTO 'players' ($keys) VALUES ($placeholders);", array_values($data));
return App::$db->lastInsertID();
}
public static function validateCredentials(string $identifier, string $password, bool $fetch = false): int|false
{
// get the player from their username or email
$player = App::$db->do("SELECT " . ($fetch ? '*' : 'id, password') . " FROM players WHERE LOWER(username) = :i OR LOWER(email) = :i LIMIT 1;", ['i' => strtolower($identifier)]);
if ($player == false) return false;
$player = $player->fetch();
// check password, return the player data if good
if (password_verify($password, $player['password'])) {
unset($player['password']);
return $fetch ? $player : $player['id'];
}
return false;
}
public static function goodUsername(string $username): bool
{
// username must be alphanumeric and between 2 and 20 characters, allow single spaces
return preg_match('/^(?!.* )[a-zA-Z0-9 ]{2,20}$/', $username);
}
public static function uniqueUsername(string $username): bool
{
$player = App::$db->do("SELECT id FROM players WHERE LOWER(username) = :i LIMIT 1;", ['i' => strtolower($username)]);
return $player->fetch() == false;
}
public static function uniqueEmail(string $email): bool
{
$player = App::$db->do("SELECT id FROM players WHERE LOWER(email) = :i LIMIT 1;", ['i' => strtolower($email)]);
return $player->fetch() == false;
}
}