Codeigniter hangman API using json and jQuery

A simple and old codeigniter API using json and jQuery to play (session based) Hangman.

Using GET requests the API returns a json with current game details. This version appears to have session problems between the levels and with starting, resending the request(press the letter again) "solves" this. Feeling lucky? Try to complete all levels jQuery client example:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
	
    
    $('.button').click(function(){
        

        $.getJSON("/game/run/"+$(this).attr("value"), function(result){
            
            $.each(result, function(i, field){
                if(i == "word"){
					$("#word").html(field);
				}
				else if(i == "level"){
					$("#level").html("level: " + field);
				
						
					
				}else if(i == "tries_left"){
					$("#tries").html("tries left:" + field);
				}
			
				
                //$("#result").prepend(i + field + "<br >");	
            });
            
             
        });
    });
    
  
});
</script>

<style>
.result
    {
        height: 400px;
        overflow: auto;
        text-align: center;
    }
    
.guessed 
    {
		font-size: 40px;
		text-align: center;   
    }    
    
.debug
	{
		font-size: 8px;
		font-color: red;
	}
    
    
.buttons
	{
		text-align: center;
	}	

.button
	{
		height: 50px;
		width: 50px;
	}
	
	
</style>


	<div class="container">
		
		

		<div class="guessed">
			<div class="word" id="word">please guess a letter below</div>
		</div>
		
		<br >
		
		<div class="tries" id="tries">tries left</div>
		<div class="level" id="level">level</div>
		<br >
	
		<div id="progressbar">
		
		</div>
	
		
		<div class="buttons">
			{letters}	
				<button class="button" id="button" value="{letter}">{letter}</button>
			{/letters}
			<button href="#" class="button" id="button" value="reset">reset</button>
		</div>
	</div>


Controller example:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Game extends CI_Controller {

	/**
	 * Hangman API
	 * 
	 */
	
	 
	public function __construct(){
		parent::__construct();				// load the constructor from the parent class
		$this->load->library('session');	// codeigniter session lib
		$this->load->library('hangman');	// hangman lib
		$this->load->library('logger');		// load the parser

	}
	 	
		 
	public function run($letter = NULL){
		
		switch($this->hangman->checkstatus($letter)){
			case 'startgame': 
				try{
					echo $this->hangman->startgame();
				}catch (Exception $e) {
					echo 'Caught exception: ',  $e->getMessage(), "\n";
				}
				break;
				
			case 'continuegame':
				try{
					echo $this->hangman->continuegame($letter);
				}catch (Exception $e) {
					echo 'Caught exception: ',  $e->getMessage(), "\n";
				}
				break;
				
			case 'endgame':
				$this->hangman->endgame("fail");
				break;	
				
			default:
				$this->hangman->startgame();
				break;
		}
		
		$arrayforjson = $this->session->userdata;
		unset ($arrayforjson['__ci_last_regenerate']);			//remove id from response
		unset ($arrayforjson['sollution']);						//remove sollution from response
		

		echo json_encode($arrayforjson);						//print json format
		
	}
}

CI lib example:


<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Hangman {

    /* hangman lib containing the game logic
	 * 
	 */
	
	private $maxattempts = 11;		
	private $session;
	private $word;
	private $levels = array("1"		=>	"easy",
							"2"		=>	"easy",
							"3" 	=>	"easy",
							"4"		=>	"medium",
							"5"		=>	"medium",
							"6" 	=>	"medium",
							"7"		=>	"hard",
							"8"		=>	"hard",
							"9" 	=>	"hard");
 
 
	public function __construct(){
		$CI =& get_instance();
		$CI->load->library('session');									//CI sessions
		$CI->load->library('wordgenerator');							//custom hangman wordgenerator
		$this->session = $CI->session;
		$this->word = $CI->wordgenerator;
		
	}
	
	 	
	/* check current game status
	 * @param = letter used for optional reset
	 * @return = current game status 
	 */ 
	public function checkstatus($letter){
		if(!isset($this->session) or $letter == "reset" or $this->session->userdata('status') == "succes" or $this->session->userdata('status') == "fail"){
			return $this->status = "startgame";							//new session, start the game
		}elseif($this->session->userdata('tries_left') <=  0){
			return $this->status = "endgame";							//no tries left, end the game
		}	
		return $this->status = "continuegame";							//tries left, continue the game
	}
	
	
	
	/* start new game, set session
	 * @param 
	 * @return = new session with userdata as array
	 */
	public function startgame(){
		$sollution 		= "";
		$level = 1;
		if(isset($this->session->userdata['level'])){
			$level = $this->session->userdata('level');
		}
		$sollution 		= $this->word->randomwordfromlist($this->levels[$level]);
		$wordlength		= count(str_split($sollution)); 
		$word 			= "";
		for ($x = 1; $x <= $wordlength; $x++) {
			$word.="*";
		}
		
		$newdata = array(
					   'sollution'  	=> $sollution,
					   'level'			=> $level,
					   'word'			=> $word,
					   'tries_left'     => $this->maxattempts,
					   'status'			=> 'busy'
						);
		//$this->session->sess_destroy();
		$this->session->set_userdata($newdata);
		if(isset($this->session)){
			return $this->status = "started";
		}
		throw new Exception('Error creating the session');
	}
	
	
	
	/* continue existing game, check for (guessed) input
	 * 
	 */
	public function continuegame($letter){
		//check if letter is found
		if($letter !== NULL){
			if (!ctype_alpha($letter)) {													
				throw new Exception('Incorrect input received, please use a tm. z');
			}
			$wordArray 	= str_split($this->session->userdata('sollution'));						
			$wordLength = count($wordArray);
			$count 		= 0;
			$found 		= FALSE;
			$guessed 	= str_split($this->session->userdata('word'));
			
			//compare received letter with the word
			foreach($wordArray as $orgletter){
				if(empty($guessed[$count])){
					$guessed[$count]="*";
				}
				if($orgletter == $letter){
					$guessed[$count]=$letter;
					$found = TRUE;
				}
				$count++;
			}
			$result = implode($guessed);
			
			if($result == $this->session->userdata('sollution')){
				$this->endgame("succes");
			}
			
			//if the guess was incorrect, reduce the tries_left by 1
			if($found == FALSE){
				$newdata['tries_left'] = $this->session->userdata('tries_left')-1;
			}
			$newdata['word']	= $result;
			$this->session->set_userdata($newdata);
			
			return ;
		}
		return ;
	}
	
	
	
	/* end game, adjust game level
	 * 
	 */
	public function endgame($status){
		if($status == "succes"){
			if($this->session->userdata('level') < 9){
				$newdata['level'] = $this->session->userdata('level')+1;
			}
		}elseif($status == "fail"){
			if($this->session->userdata('level') > 1){
				$newdata['level'] = $this->session->userdata('level')-1;
			}
		}
		$newdata['word'] 	= "";
		$newdata['status'] 	= $status;
		$this->session->set_userdata($newdata);
		
		return ;
	}	
}

why-guy add:

Last Tweets: