-
Notifications
You must be signed in to change notification settings - Fork 0
/
Game.php
126 lines (119 loc) · 2.25 KB
/
Game.php
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
121
122
123
124
125
126
<?php
/**
* @author Valera
* @copyright 2017
*/
function GenerateMap($height, $width)
{
$arr=array();
for($i=0;$i<$height;$i++)
{
$arr[$i]=array();
for($j=0;$j<$width;$j++)
{
if(rand(0,5)==0)
{
$arr[$i][$j]="0";
continue;
}
$arr[$i][$j]="*";
}
}
return $arr;
}
function Screen($arr, $x, $y)
{
for($i=0; $i<count($arr); $i++)
{
for($j=0;$j<count($arr[$i]);$j++)
{
if($i==$y && $j==$x)
{
print("#");
continue;
}
print($arr[$i][$j]);
}
print("<br>");
}
print("<br><br><br>");
}
function GetUserInput()
{
$rand=rand(0,3);
switch($rand)
{
case 0: return "UP";
case 1: return "DOWN";
case 2: return "LEFT";
case 3: return "RIGHT";
default: return "";
}
}
function PlayerInit($w, $h, &$x, &$y)
{
$x = rand(0, $w-1);
$y = rand(0, $h-1);
}
function IsWalkable($str)
{
switch($str)
{
case "0":
return false;
default: return true;
}
}
function IsCanMove($command, &$x, &$y, $map)
{
//bounds
if($y==0 && $command=="UP") return false;
if($y==9 && $command=="DOWN")return false;
if($x==0 && $command=="LEFT") return false;
if($x==9 && $command=="RIGHT") return false;
//walkable
$X=$x;
$Y=$y;
Move($command, $X, $Y);
if(!IsWalkable($map[$Y][$X])) return false;
//all ok
return true;
}
function Move($command, &$x, &$y)
{
switch($command)
{
case "UP":
$y--;
break;
case "DOWN":
$y++;
break;
case "LEFT":
$x--;
break;
case "RIGHT":
$x++;
break;
}
}
function Main()
{
$W = 10;
$H = 10;
$map = GenerateMap($W,$H);
PlayerInit($W, $H, $X, $Y);
$totalTime = 45;
Screen($map, $X, $Y);
for($t =0; $t<$totalTime; $t++)
{
$userInput = GetUserInput();
if(IsCanMove($userInput, $X, $Y, $map))
{
Move($userInput, $X, $Y);
}
Screen($map, $X, $Y);
}
}
Main();
?>