-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
118 lines (96 loc) · 2.67 KB
/
main.js
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
$.position_x = 100
$.position_y = 100
$.step = 15
$.speed = 0.5
function main()
{
var scene = xc.getCurrentScene();
var snake = new Array()
var food = null
createSnakePoint();
direction = 'right'
scene.schedule(moveByDirection, 0.3);
scene.schedule(checkCollision, 0.3);
scene.schedule(createFood, 6);
scene.schedule(checkGameEnd, 0.1);
//scene.schedule(speedUp, 2);
scene.keyDown = function(key){
switch (key.key) {
case 39:
direction = 'right'
break;
case 37:
direction = 'left'
break;
case 38:
direction = 'up'
break;
case 40:
direction = 'down'
break;
}
};
xc.addEventListener('keyDown', scene);
function moveByDirection(){
moveSnakeBody()
switch (direction) {
case "right":
snakeHead().moveBy($.step,0)
break;
case "left":
snakeHead().moveBy(-$.step,0)
break;
case "up":
snakeHead().moveBy(0,-$.step)
break;
case "down":
snakeHead().moveBy(0,$.step)
break;
}
}
function speedUp(){
$.step += 10
}
function checkGameEnd(){
if ((snakeHead().X() < 0) || (snakeHead().Y() < 0) || (snakeHead().X() > 480) || (snakeHead().Y() > 480))
{
scene.pause();
alert('You lose')
}
}
function createSnakePoint(){
new_snake_point = new XCSpriteNode('snake_point.png')
snake[snake.length] = new_snake_point;
scene.addChild(new_snake_point);
}
function createFood(){
if (food == null){
food = new XCSpriteNode('snake_point.png');
food.moveTo(randomNumber(), randomNumber())
scene.addChild(food);
}
}
function randomNumber(){
return Math.floor(Math.random()*11)*30
}
function checkCollision(){
if ((food != null) && ( snakeHead().X() == food.X() && snakeHead().Y() == food.Y() )){
scene.removeChild(food);
food = null;
createSnakePoint();
}
}
function snakeHead(){
return snake[0];
}
function moveSnakeBody(){
var index=snake.length-1;
for (index=snake.length-1;index>=0;index--)
{
if (index > 0) {
previous_snake_point = snake[index-1];
snake[index].moveTo(previous_snake_point.X(), previous_snake_point.Y())
}
}
}
}