Esempio n. 1
0
 /**
  * Update profile
  *
  * @param Container
  */
 public function updateProfile(Container $p_dependencies)
 {
     $char = $p_dependencies['current_player'];
     $new_profile = trim(RequestWrapper::getPostOrGet('newprofile', null));
     $profile_changed = false;
     $error = '';
     if (!empty($new_profile)) {
         DatabaseConnection::getInstance();
         $statement = DatabaseConnection::$pdo->prepare('UPDATE players SET messages = :profile WHERE player_id = :char_id');
         $statement->bindValue(':profile', $new_profile);
         $statement->bindValue(':char_id', $char->id());
         $statement->execute();
         $profile_changed = true;
     } else {
         $error = 'Cannot enter a blank profile.';
     }
     $query_str = [];
     if ($profile_changed) {
         $query_str['profile_changed'] = 1;
     } else {
         $query_str['error'] = $error;
     }
     $raw_query_str = count($query_str) ? '?' . http_build_query($query_str, null, '&') : null;
     return new RedirectResponse('/stats' . $raw_query_str);
 }
Esempio n. 2
0
 /**
  * User command for betting on the coin toss game in the casino
  *
  * @param Container
  * @param bet int The amount of money to bet on the coin toss game
  * @return Response
  *
  * @note
  * If the player bets within ~1% of the maximum bet, they will receive a
  * reward item
  */
 public function bet(Container $p_dependencies)
 {
     $player = $p_dependencies['current_player'];
     if (!$player) {
         return new RedirectResponse('/casino/?error=' . rawurlencode('Become a ninja first!'));
     }
     $bet = intval(RequestWrapper::getPostOrGet('bet'));
     $pageParts = ['reminder-max-bet'];
     if ($bet < 0) {
         $pageParts = ['result-cheat'];
         $player->harm(self::CHEAT_DMG);
     } else {
         if ($bet > $player->gold) {
             $pageParts = ['result-no-gold'];
         } else {
             if ($bet > 0 && $bet <= self::MAX_BET) {
                 if (rand(0, 1) === 1) {
                     $pageParts = ['result-win'];
                     $player->setGold($player->gold + $bet);
                     if ($bet >= round(self::MAX_BET * 0.99)) {
                         // within about 1% of the max bet & you win, you get a reward item.
                         $inventory = new Inventory($player);
                         $inventory->add(self::REWARD, 1);
                     }
                 } else {
                     $player->setGold($player->gold - $bet);
                     $pageParts = ['result-lose'];
                 }
             }
         }
     }
     $player->save();
     return $this->render(['pageParts' => $pageParts, 'player' => $player]);
 }
Esempio n. 3
0
 /**
  * Action to request the Dim Mak form AND execute the purchase
  *
  * @todo split form request (GET) and purchase (POST) into separate funcs
  * @return ViewSpec
  */
 public function buyDimMak()
 {
     if (is_logged_in()) {
         $player = new Player(self_char_id());
         $showMonks = false;
         $parts = [];
         RequestWrapper::init();
         if (RequestWrapper::$request && RequestWrapper::$request->isMethod('POST')) {
             $error = $this->dimMakReqs($player, self::DIM_MAK_COST);
             if (!$error) {
                 $player->changeTurns(-1 * self::DIM_MAK_COST);
                 add_item($player->id(), 'dimmak', 1);
                 $parts['pageParts'] = ['success-dim-mak'];
                 $showMonks = true;
             } else {
                 $parts['error'] = $error;
             }
         } else {
             $parts['pageParts'] = ['form-dim-mak'];
             $parts['dim_mak_cost'] = self::DIM_MAK_COST;
         }
         return $this->render($parts, $player, $showMonks);
     } else {
         return $this->accessDenied();
     }
 }
Esempio n. 4
0
 public function testPostWithinMockedEnvironment()
 {
     $posted = RequestWrapper::getPost('post_post_field', 'Bob');
     $this->assertEquals('Bob', $posted);
     $default = RequestWrapper::getPost('blah_doesnt_exist', 7777);
     $this->assertEquals(7777, $default);
 }
 public function tearDown()
 {
     RequestWrapper::destroy();
     $session = SessionFactory::getSession();
     $session->invalidate();
     parent::tearDown();
 }
Esempio n. 6
0
 /**
  * Take an enemy off a pc's list.
  */
 public function deleteEnemy(Container $p_dependencies)
 {
     $enemy = Player::find(RequestWrapper::getPostOrGet('remove_enemy'));
     if ($enemy) {
         $this->removeEnemyFromPlayer(Player::find(SessionFactory::getSession()->get('player_id')), $enemy);
     }
     return new RedirectResponse('/enemies');
 }
 function tearDown()
 {
     removeItem($this->char->id(), self::ITEM);
     TestAccountCreateAndDestroy::destroy();
     RequestWrapper::inject(new Request([]));
     $session = SessionFactory::getSession();
     $session->invalidate();
 }
Esempio n. 8
0
 public function testShopPurchaseHandlesNoItemNoQuantity()
 {
     // Inject post request.
     RequestWrapper::inject(new Request([], []));
     $shop = new ShopController();
     $shop_outcome = $shop->buy();
     $this->assertNotEmpty($shop_outcome);
 }
Esempio n. 9
0
 public function tearDown()
 {
     $this->char = null;
     TestAccountCreateAndDestroy::destroy();
     RequestWrapper::inject(new Request([]));
     $session = SessionFactory::getSession();
     $session->invalidate();
 }
 public function tearDown()
 {
     $this->inventory->remove(self::ITEM);
     TestAccountCreateAndDestroy::destroy();
     RequestWrapper::inject(new Request([]));
     $session = SessionFactory::getSession();
     $session->invalidate();
     parent::tearDown();
 }
Esempio n. 11
0
 public function testViewingOfPlayerProfileMyselfViewingOwnProfile()
 {
     $viewing_char_id = $this->char->id();
     $request = new Request(['player_id' => $viewing_char_id]);
     RequestWrapper::inject($request);
     $sess = SessionFactory::getSession();
     $sess->set('player_id', $this->char->id());
     $player = new PlayerController();
     $player_outcome = $player->index();
     $this->assertNotEmpty($player_outcome);
 }
Esempio n. 12
0
 public function testSearch()
 {
     $request = new Request(['term' => $this->char->uname, 'limit' => 5], []);
     RequestWrapper::inject($request);
     $result = $this->controller->nw_json('char_search', self::CALLBACK);
     $payload = $this->extractPayload($result);
     $this->assertObjectHasAttribute('char_matches', $payload);
     $this->assertCount(1, $payload->char_matches);
     $this->assertObjectHasAttribute('uname', $payload->char_matches[0]);
     $this->assertObjectHasAttribute('player_id', $payload->char_matches[0]);
 }
Esempio n. 13
0
 public function testWorkDoesNothingWithNegativeWorkRequest()
 {
     // Note that this had to have an active logged in character to not just get an ignored result of "0" gold.
     $this->char = TestAccountCreateAndDestroy::char();
     SessionFactory::getSession()->set('player_id', $this->char->id());
     $request = new Request([], ['worked' => -999]);
     RequestWrapper::inject($request);
     $work = new WorkController();
     $work_response = $work->requestWork();
     $earned_gold = $work_response['parts']['earned_gold'];
     $this->assertEquals("0", $earned_gold);
 }
Esempio n. 14
0
 /**
  * Display standard login page.
  */
 public function index(Container $p_dependencies)
 {
     $login_error_message = RequestWrapper::getPostOrGet('error');
     // Error to display after unsuccessful login and redirection.
     $stored_username = isset($_COOKIE['username']) ? $_COOKIE['username'] : null;
     $referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
     if (SessionFactory::getSession()->get('authenticated', false)) {
         return new RedirectResponse(WEB_ROOT);
     } else {
         $parts = ['authenticated' => false, 'login_error_message' => $login_error_message, 'referrer' => $referrer, 'stored_username' => $stored_username];
         return $this->render('Login', $parts);
     }
 }
Esempio n. 15
0
 public function testDeleteWithEmptyPassword()
 {
     RequestWrapper::inject(new Request(['passw' => '']));
     $session = SessionFactory::getSession();
     $failure_count = $session->get('delete_attempts');
     $controller = new AccountController();
     $response = $controller->deleteAccount();
     $reflection = new \ReflectionProperty(get_class($response), 'data');
     $reflection->setAccessible(true);
     $response_data = $reflection->getValue($response);
     $this->assertNotEmpty($response_data['error']);
     $this->assertGreaterThan($failure_count, $session->get('delete_attempts'));
 }
Esempio n. 16
0
 /**
  * Take in a chat and record it to the database.
  *
  * @return Response
  */
 public function receive()
 {
     $char_id = SessionFactory::getSession()->get('player_id');
     $message = RequestWrapper::getPostOrGet('message');
     $error = null;
     if (!empty($message)) {
         if ($char_id) {
             Message::sendChat($char_id, $message);
         } else {
             $error = 'You must be logged in to chat.';
         }
     }
     return new RedirectResponse('/village/' . ($error ? '?error=' . rawurlencode($error) : ''));
 }
Esempio n. 17
0
 public function testWorkDoesNothingWithNegativeWorkRequest()
 {
     // Note that this had to have an active logged in character to not just get an ignored result of "0" gold.
     $this->char = TestAccountCreateAndDestroy::char();
     SessionFactory::getSession()->set('player_id', $this->char->id());
     $request = new Request([], ['worked' => -999]);
     RequestWrapper::inject($request);
     $work = new WorkController();
     $response = $work->requestWork($this->m_dependencies);
     $reflection = new \ReflectionProperty(get_class($response), 'data');
     $reflection->setAccessible(true);
     $response_data = $reflection->getValue($response);
     $earned_gold = $response_data['earned_gold'];
     $this->assertEquals("0", $earned_gold);
 }
Esempio n. 18
0
 /**
  * View clan messages
  *
  * @param Container
  */
 public function viewClan(Container $p_dependencies)
 {
     $ninja = $p_dependencies['current_player'];
     $page = max(1, (int) RequestWrapper::getPostOrGet('page'));
     $limit = 25;
     $offset = ($page - 1) * $limit;
     $type = 1;
     // Clan chat or normal messages.
     $message_count = Message::countByReceiver($ninja, $type);
     // To count all the messages
     Message::markAsRead($ninja, $type);
     // mark messages as read for next viewing.
     $parts = array_merge($this->configure(), ['messages' => Message::findByReceiver($ninja, $type, $limit, $offset), 'message_count' => $message_count, 'pages' => ceil($message_count / $limit), 'current_page' => $page, 'current_tab' => 'clan', 'has_clan' => (bool) Clan::findByMember($ninja)]);
     return $this->render($parts, 'Clan Messages');
 }
Esempio n. 19
0
 public function testAttackWhenDead()
 {
     $attacker = Player::find(SessionFactory::getSession()->get('player_id'));
     $attacker->death();
     $attacker->save();
     $char_id_2 = TestAccountCreateAndDestroy::char_id_2();
     $params = ['target' => $char_id_2];
     $request = Request::create('/attack', 'GET', $params);
     RequestWrapper::inject($request);
     $response = $this->controller->index($this->m_dependencies);
     $this->assertInstanceOf(StreamedViewResponse::class, $response);
     $reflection = new \ReflectionProperty(get_class($response), 'data');
     $reflection->setAccessible(true);
     $response_data = $reflection->getValue($response);
     $this->assertNotEmpty($response_data['error']);
 }
Esempio n. 20
0
 /**
  * Create new post
  */
 public function create()
 {
     try {
         $create_role = $this->hasCreateRole($this->pc);
     } catch (InvalidArgumentException $e) {
         $error = "Sorry, you must be logged in to create a news post.";
         return new RedirectResponse('/news/?error=' . rawurlencode($error));
     }
     if (!$create_role) {
         $error = 'Sorry, you do not have permission to create a news post.';
         return new RedirectResponse('/news/?error=' . rawurlencode($error));
     }
     $title = 'Make New Post';
     $error = (bool) RequestWrapper::getPostOrGet('error');
     $parts = ['error' => $error, 'heading' => $title, 'authenticated' => SessionFactory::getSession()->get('authenticated', false)];
     return new StreamedViewResponse($title, 'news.create.tpl', $parts);
 }
Esempio n. 21
0
 public function testOfferOfBadNegativeBribe()
 {
     $request = new Request(['bribe' => -40]);
     RequestWrapper::inject($request);
     $bounty_set = 4444;
     $initial_gold = 7777;
     $this->char->setBounty($bounty_set);
     $this->char->setGold($initial_gold);
     $this->char->save();
     $doshin = new DoshinController();
     $doshin->bribe($this->m_dependencies);
     $final_char = Player::find($this->char->id());
     $this->assertLessThan(7777, $final_char->gold);
     $modified_bounty = $final_char->bounty;
     $this->assertLessThan($bounty_set, $modified_bounty);
     $this->assertGreaterThan(0, $modified_bounty);
 }
Esempio n. 22
0
 /**
  * Take in a url parameter of work and try to convert it to gold
  *
  * @param Container
  * @return StreamedViewResponse
  */
 public function requestWork(Container $p_dependencies)
 {
     $earned = 0;
     $worked = Filter::toNonNegativeInt(RequestWrapper::getPostOrGet('worked'));
     // No negative work.
     $char = $p_dependencies['current_player'];
     if (!$char) {
         return new RedirectResponse('/work');
     }
     $sufficient_turns = $worked <= $char->turns;
     if ($sufficient_turns) {
         $earned = $worked * self::WORK_MULTIPLIER;
         // calc amount worked
         $char->setGold($char->gold + $earned);
         $char->setTurns($char->turns - $worked);
         $char->save();
     }
     $parts = ['recommended_to_work' => $worked, 'worked' => $worked, 'work_multiplier' => self::WORK_MULTIPLIER, 'authenticated' => $p_dependencies['session']->get('authenticated', false), 'gold_display' => number_format($char->gold), 'earned_gold' => number_format($earned), 'not_enough_energy' => !$sufficient_turns];
     return $this->render($parts);
 }
 protected function tearDown()
 {
     RequestWrapper::destroy();
     $session = SessionFactory::getSession();
     $session->invalidate();
 }
Esempio n. 24
0
 public function testLatestMessage()
 {
     $request = new Request(['type' => 'latest_message', 'jsoncallback' => self::CALLBACK], []);
     RequestWrapper::inject($request);
     $result = $this->controller->nw_json();
     $payload = $this->extractPayload($result);
     $this->assertObjectHasAttribute('message', $payload);
 }
Esempio n. 25
0
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use NinjaWars\core\RouteNotFoundException;
use NinjaWars\core\Router;
use NinjaWars\core\environment\RequestWrapper;
use NinjaWars\core\data\GameLog;
use NinjaWars\core\data\Player;
use NinjaWars\core\extensions\SessionFactory;
// setup our runtime environment
require_once LIB_ROOT . 'environment/bootstrap.php';
try {
    $container = new Container();
    $container['current_player'] = function ($c) {
        return Player::find(SessionFactory::getSession()->get('player_id'));
    };
    $container['session'] = function ($c) {
        return SessionFactory::getSession();
    };
    // Update the activity of the page viewer in the database.
    RequestWrapper::init();
    GameLog::updateActivityInfo(RequestWrapper::$request, SessionFactory::getSession());
    // get the request information to parse the route
    $response = Router::route(Request::createFromGlobals(), $container);
    if ($response instanceof Response) {
        $response->send();
    } else {
        throw new \RuntimeException('Route returned something other than a Response');
    }
} catch (RouteNotFoundException $e) {
    Router::respond404();
}
Esempio n. 26
0
 public function testPartialHealWithZeroGoldGivesErrorInPageParts()
 {
     $request = new Request(['heal_points' => 999], []);
     RequestWrapper::inject($request);
     $this->char->harm((int) floor($this->char->health / 2));
     // Have to be wounded first.
     $this->char->setGold(0);
     $initial_health = $this->char->health;
     $this->assertGreaterThan(0, $initial_health);
     $this->char->save();
     $this->char->setClass('viper');
     // Default dragon class has chi skill
     $cont = new ShrineController();
     $response = $cont->heal($this->m_dependencies);
     $final_char = Player::find($this->char->id());
     $reflection = new \ReflectionProperty(get_class($response), 'data');
     $reflection->setAccessible(true);
     $response_data = $reflection->getValue($response);
     $this->assertNotEmpty($response_data['error']);
     $this->assertEquals($initial_health, $final_char->health);
 }
Esempio n. 27
0
 protected function tearDown()
 {
     RequestWrapper::destroy();
 }
Esempio n. 28
0
 /**
  */
 public function testDojoChangeClassLowTurnsDoesNotError()
 {
     $request = Request::create('/', 'GET', ['requested_identity' => 'crane']);
     RequestWrapper::inject($request);
     $char = Player::find($this->char_id);
     $char->setStrength(400);
     $char->setTurns(0);
     $char->save();
     $this->assertNotEmpty($this->controller->changeClass($this->m_dependencies));
 }
Esempio n. 29
0
 public function testRandomEncounter()
 {
     $this->controller = new NpcController(['randomness' => function () {
         return 1;
     }]);
     RequestWrapper::inject(Request::create('/npc/attack/peasant'));
     $response = $this->controller->attack($this->m_dependencies);
     $this->assertNotEmpty($response);
 }
Esempio n. 30
0
 /**
  * Command for a user to reduce their bounty by paying their own gold
  *
  * @param Container
  * @param bribe int The amount to spend on reducing bounty
  * @return StreamedViewRespons
  */
 public function bribe(Container $p_dependencies)
 {
     $bribe = intval(RequestWrapper::getPostOrGet('bribe'));
     $char = Player::findPlayable($this->getAccountId());
     $error = 0;
     $quickstat = false;
     if ($bribe <= $char->gold && $bribe > 0) {
         $char->setGold($char->gold - $bribe);
         $char->setBounty(max(0, $char->bounty - floor($bribe / self::BRIBERY_DIVISOR)));
         $char->save();
         $location = 1;
         $quickstat = 'viewinv';
     } else {
         if ($bribe < self::MIN_BRIBE) {
             $this->doshinAttack($char);
             $location = 2;
             $quickstat = 'player';
         } else {
             $location = 0;
             $error = 5;
         }
     }
     return $this->render(['error' => $error, 'quickstat' => $quickstat, 'location' => $location, 'command' => 'bribe']);
 }