Created
April 2, 2020 21:30
-
-
Save f2r/b9fbe5870009be67b99780fab7134726 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Classe permettant d'interagir avec un moteur de jeu | |
*/ | |
final class Game | |
{ | |
private const BASE_URL = 'https://code-challenge.webandcow.com'; | |
private string $codeEngine; | |
private string $key; | |
private string $token; | |
public function __construct(string $key, string $codeEngine) | |
{ | |
$this->key = $key; | |
$this->codeEngine = $codeEngine; | |
} | |
public function loadData(): array | |
{ | |
$data = $this->requestApi('/games/launch/' . $this->key . '/' . $this->codeEngine); | |
$this->token = $data['token']; | |
$data = $this->requestApi('/games/init/' . $this->token); | |
return $data['game']; | |
} | |
public function pushResponse(string $response): void | |
{ | |
$response = base64_encode(json_encode(['reponse' => $response])); | |
$data = $this->requestApi('/games/push/' . $this->token . '/' . $response); | |
$color = $data['success_game'] ? 'green' : 'red'; | |
printf( | |
'<p><b style="color: %s;">%s</b></p>', | |
$color, | |
$data['message'] | |
); | |
printf( | |
'<p><b>Token de ta game :</b> <a href="%s" target="_blank">%s</a></p>', | |
self::BASE_URL .'/games/story/'. $this->token, | |
$this->token | |
); | |
} | |
private function requestApi(string $url): array | |
{ | |
$data = file_get_contents(self::BASE_URL . $url); | |
$data = json_decode($data, true); | |
if (empty($data['errors']) === false) { | |
foreach ((array)$data['errors'] as $error) { | |
echo "<p><b>Erreur : </b>{$error}</p>"; | |
} | |
exit; | |
} | |
assert(isset($data['data'])); | |
return $data['data']; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment