Last active
August 29, 2015 14:24
-
-
Save ntd/2a784c861f54e78e1ef9 to your computer and use it in GitHub Desktop.
SilverStripe hangman
This file contains 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 | |
// Code submitted by Nicola Fontana <[email protected]> | |
Director::addRules(100, array('hangman/$Tiles' => 'Hangman')); | |
class Hangman extends Controller { | |
public function index(SS_HTTPRequest $request) { | |
if(!($this->Tiles = $request->param('Tiles'))) { | |
$reflection = new ReflectionClass(array_rand(ClassInfo::allClasses())); | |
Session::set('Word', $reflection->name); // Just to have the class name in CamelCase | |
} | |
$this->Word = Session::get('Word'); | |
$this->Rack = preg_replace("/[^0-9_$this->Tiles]/i", '-', $this->Word); | |
$this->Misses = strlen(preg_replace("/[$this->Word]/i", '', $this->Tiles)) * 100 / 5; | |
$this->Result = $this->Rack == $this->Word ? 'won' : ($this->Misses >= 100 ? 'lost' : ''); | |
return $this->render(); | |
} | |
public function getAllLetters() { | |
return new ArrayList(array_map(function($l) { | |
return new ArrayData(array( | |
'Uppercase' => $l, | |
'Link' => $this->Tiles . $l, | |
'Status' => strpos($this->Tiles, $l) === false ? 'enabled' : 'disabled', | |
)); | |
}, range('A', 'Z'))); | |
} | |
public function getViewer($action) { | |
return SSViewer::fromString(str_replace("\n\t\t\t", "\n", | |
'<!DOCTYPE html> | |
<html lang="en"><head><meta charset="utf-8"><title>SilverStripe Hangman</title> | |
<script src="//cdn.jsdelivr.net/g/jquery@1,bootstrap@3"></script> | |
<link rel="stylesheet" href="//cdn.jsdelivr.net/bootstrap/3/css/bootstrap.min.css"> | |
</head><body class="container text-center"> | |
<h2><code><% if $Result %>$Word<% else %>$Rack<% end_if %></code></h2> | |
<div class="progress"><div class="progress-bar" style="width: $Misses%;"></div></div> | |
<div class="btn-toolbar" style="display:inline-block"><% if $Result %> | |
<p class="lead">You $Result!</p><% else %> | |
<div class="btn-group"><% loop $AllLetters %> | |
<a href="$Link" class="btn btn-primary $Status">$Uppercase</a><% end_loop %> | |
</div><% end_if %> | |
<div class="btn-group"><a href="." class="btn btn-danger">Reset</a></div> | |
</div> | |
</body></html>' | |
)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment