summaryrefslogtreecommitdiff
path: root/demos/quickstart/protected/pages/Fundamentals/Samples/Hangman/Home.php
blob: 70d91d5d77a8f584111fafd901f9eef5b6cbe3ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<?php
class Home extends TPage
{
	public function onLoad($param)
	{
		if (!$this->IsPostBack)
			$this->GameMultiView->ActiveView=$this->IntroView;
	}

	public function selectLevel($sender,$param)
	{
		if(($selection=$this->LevelSelection->SelectedValue)==='')
		{
			$this->LevelError->Visible=true;
			return;
		}
		else
			$this->Level=TPropertyValue::ensureInteger($selection);
		$this->Word=$this->generateWord();
		$this->GuessWord=str_repeat('_',strlen($this->Word));
		$this->Misses=0;
		$this->GameMultiView->ActiveView=$this->GuessView;
	}

	public function guessWord($sender,$param)
	{
		$sender->Enabled=false;
		$letter=$sender->Text;
		$word=$this->Word;
		$guessWord=$this->GuessWord;
		$pos=0;
		$success=false;
		while(($pos=strpos($word,$letter,$pos))!==false)
		{
			$guessWord[$pos]=$letter;
			$success=true;
			$pos++;
		}
		if($success)
		{
			$this->GuessWord=$guessWord;
			if($guessWord===$word)
				$this->GameMultiView->ActiveView=$this->WinView;
		}
		else
		{
			$this->Misses++;
			if($this->Misses>=$this->Level)
				$this->giveUp(null,null);
		}
	}

	public function giveUp($sender,$param)
	{
		$this->GameMultiView->ActiveView=$this->LoseView;
	}

	public function startAgain($sender,$param)
	{
		$this->GameMultiView->ActiveView=$this->IntroView;
		$this->LevelError->Visible=false;
		for($letter=65;$letter<=90;++$letter)
		{
			$guessLetter='Guess'.chr($letter);
			$this->$guessLetter->Enabled=true;
		}
	}

	protected function generateWord()
	{
		$wordFile=dirname(__FILE__).'/words.txt';
		$words=preg_split("/[\s,]+/",file_get_contents($wordFile));
		do
		{
			$i=rand(0,count($words)-1);
			$word=$words[$i];
		} while(strlen($word)<5 || !preg_match('/^[a-z]*$/i',$word));
		return strtoupper($word);
	}

	public function setLevel($value)
	{
		$this->setViewState('Level',$value,0);
	}

	public function getLevel()
	{
		return $this->getViewState('Level',0);
	}

	public function setWord($value)
	{
		$this->setViewState('Word',$value,'');
	}

	public function getWord()
	{
		return $this->getViewState('Word','');
	}

	public function getGuessWord()
	{
		return $this->getViewState('GuessWord','');
	}

	public function setGuessWord($value)
	{
		$this->setViewState('GuessWord',$value,'');
	}

	public function setMisses($value)
	{
		$this->setViewState('Misses',$value,0);
	}

	public function getMisses()
	{
		return $this->getViewState('Misses',0);
	}
}