In this Snake game, I need the buttons to control the snake just like the arrow keys do. This will allow the game to be played on a mobile device. You can see i have code in there for the buttons, but they are not working properly and not controlling the movement of the snake.
Any advice to make the buttons work would be greatly appreciated! thanks!
HTML
JavaScript
x
60
60
1
<section class="game" id="share">
2
3
<div class="container">
4
5
<div class="columns twelve borders center">
6
7
<div class="game-container">
8
9
<div class="container">
10
11
<div class="SplashScreen">
12
<h1>
13
Snake
14
</h1>
15
<h2>
16
Click To Start.
17
</h2>
18
<input class="StartButton" type="button" value="Start" />
19
</div>
20
21
<div class="FinishScreen" style="display:none">
22
<h1>
23
Game Over
24
</h1>
25
<p>
26
Your score was: <span id="score"></span>
27
</p>
28
<input class="StartButton" type="button" value="Restart" />
29
</div>
30
31
<canvas id="canvasArea" height="300" width="300" style="display:none;"></canvas>
32
33
</div>
34
35
<div class="button-pad">
36
<div class="btn-up">
37
<input type="image" src="http://aaronblomberg.com/sites/ez/images/btn-up.png" alt="Up" class="button up-btn" />
38
</div>
39
40
<div class="btn-right">
41
<input type="image" src="http://aaronblomberg.com/sites/ez/images/btn-right.png" alt="Right" class="button right-btn" />
42
</div>
43
44
<div class="btn-down">
45
<input type="image" src="http://aaronblomberg.com/sites/ez/images/btn-down.png" alt="Down" class="button down-btn" />
46
</div>
47
48
<div class="btn-left">
49
<input type="image" src="http://aaronblomberg.com/sites/ez/images/btn-left.png" alt="Left" class="button left-btn" />
50
</div>
51
</div>
52
53
</div>
54
55
</div>
56
57
</div>
58
59
</section>
60
JAVASCRIPT
JavaScript
1
235
235
1
( function( $ ) {
2
3
$( function() {
4
5
$(document).ready(function () {
6
7
$(".StartButton").click(function () {
8
$(".SplashScreen").hide();
9
$(".FinishScreen").hide();
10
$("#canvasArea").show();
11
init();
12
});
13
14
//Canvas stuff
15
var canvas = $("#canvasArea")[0];
16
var ctx = canvas.getContext("2d");
17
var w = $("#canvasArea").width();
18
var h = $("#canvasArea").height();
19
20
//Lets save the cell width in a variable for easy control
21
var sw = 10;
22
var direction;
23
var nd;
24
var food;
25
var score;
26
27
//Lets create the snake now
28
var snake_array; //an array of cells to make up the snake
29
30
function endGame() {
31
$("#canvasArea").hide();
32
$("#score").text(score);
33
$(".FinishScreen").show();
34
}
35
36
function init() {
37
direction = "right"; //default direction
38
nd = [];
39
create_snake();
40
create_food(); //Now we can see the food particle
41
//finally lets display the score
42
score = 0;
43
44
//Lets move the snake now using a timer which will trigger the paint function
45
//every 60ms
46
if (typeof game_loop != "undefined") clearInterval(game_loop);
47
game_loop = setInterval(paint, 60);
48
}
49
50
function create_snake() {
51
var length = 5; //Length of the snake
52
snake_array = []; //Empty array to start with
53
for (var i = length - 1; i >= 0; i--) {
54
//This will create a horizontal snake starting from the top left
55
snake_array.push({
56
x: i,
57
y: 0
58
});
59
}
60
}
61
62
//Lets create the food now
63
function create_food() {
64
food = {
65
x: Math.round(Math.random() * (w - sw) / sw),
66
y: Math.round(Math.random() * (h - sw) / sw),
67
68
69
};
70
//This will create a cell with x/y between 0-44
71
//Because there are 45(450/10) positions accross the rows and columns
72
73
}
74
75
//Lets paint the snake now
76
function paint() {
77
if (nd.length) {
78
direction = nd.shift();
79
}
80
81
//To avoid the snake trail we need to paint the BG on every frame
82
//Lets paint the canvas now
83
ctx.fillStyle = "#0056a0";
84
ctx.fillRect(0, 0, w, h);
85
ctx.strokeStyle = "#ffffff";
86
ctx.strokeRect(0, 0, w, h);
87
88
//The movement code for the snake to come here.
89
//The logic is simple
90
//Pop out the tail cell and place it infront of the head cell
91
var nx = snake_array[0].x;
92
var ny = snake_array[0].y;
93
94
//These were the position of the head cell.
95
//We will increment it to get the new head position
96
//Lets add proper direction based movement now
97
if (direction == "right") nx++;
98
else if (direction == "left") nx--;
99
else if (direction == "up") ny--;
100
else if (direction == "down") ny++;
101
102
//Lets add the game over clauses now
103
//This will restart the game if the snake hits the wall
104
//Lets add the code for body collision
105
//Now if the head of the snake bumps into its body, the game will restart
106
if (nx == -1 || nx == w / sw || ny == -1 || ny == h / sw || check_collision(nx, ny, snake_array)) {
107
//end game
108
return endGame();
109
}
110
111
//Lets write the code to make the snake eat the food
112
//The logic is simple
113
//If the new head position matches with that of the food,
114
//Create a new head instead of moving the tail
115
if (nx == food.x && ny == food.y) {
116
var tail = {
117
x: nx,
118
y: ny
119
};
120
score++;
121
122
//Create new food
123
create_food();
124
} else
125
126
{
127
var tail = snake_array.pop(); //pops out the last cell
128
tail.x = nx;
129
tail.y = ny;
130
}
131
132
//The snake can now eat the food.
133
snake_array.unshift(tail); //puts back the tail as the first cell
134
135
for (var i = 0; i < snake_array.length; i++) {
136
var c = snake_array[i];
137
138
//Lets paint 10px wide cells
139
paint_cell(c.x, c.y);
140
}
141
142
//Lets paint the food
143
paint_cell(food.x, food.y);
144
145
//Lets paint the score
146
var score_text = "Score: " + score;
147
ctx.fillStyle = "#ffffff";
148
ctx.fillText(score_text, 5, h - 5);
149
150
//Set the font and font size
151
ctx.font = '12px Arial';
152
153
//position of the fill text counter
154
ctx.fillText(itemCounter, 10, 10);
155
156
}
157
158
//Lets first create a generic function to paint cells
159
function paint_cell(x, y) {
160
ctx.fillStyle = "#d8d8d8";
161
ctx.fillRect(x * sw, y * sw, sw, sw);
162
}
163
164
function check_collision(x, y, array) {
165
//This function will check if the provided x/y coordinates exist
166
//in an array of cells or not
167
for (var i = 0; i < array.length; i++) {
168
if (array[i].x == x && array[i].y == y) return true;
169
}
170
171
return false;
172
}
173
174
// Lets prevent the default browser action with arrow key usage
175
var keys = {};
176
window.addEventListener("keydown",
177
function(e){
178
keys[e.keyCode] = true;
179
switch(e.keyCode){
180
case 37: case 39: case 38: case 40: // Arrow keys
181
case 32: e.preventDefault(); break; // Space
182
default: break; // do not block other keys
183
}
184
},
185
false);
186
window.addEventListener('keyup',
187
function(e){
188
keys[e.keyCode] = false;
189
},
190
false);
191
192
//Lets add the keyboard controls now
193
$(document).keydown(function (e) {
194
var key = e.which;
195
var td;
196
if (nd.length) {
197
var td = nd[nd.length - 1];
198
199
} else {
200
td = direction;
201
}
202
203
//We will add another clause to prevent reverse gear
204
if (key == "37" && td != "right") nd.push("left");
205
else if (key == "38" && td != "down") nd.push("up");
206
else if (key == "39" && td != "left") nd.push("right");
207
else if (key == "40" && td != "up") nd.push("down");
208
209
//The snake is now keyboard controllable
210
211
});
212
213
});
214
215
216
$(document).on('click', '.button-pad > button', function(e) {
217
if ($(this).hasClass('left-btn')) {
218
e = 37;
219
}
220
else if ($(this).hasClass('up-btn')) {
221
e = 38;
222
}
223
else if ($(this).hasClass('right-btn')) {
224
e = 39;
225
}
226
else if ($(this).hasClass('down-btn')) {
227
e = 40;
228
}
229
$.Event("keydown", {keyCode: e});
230
});
231
232
});
233
234
})( jQuery );
235
Advertisement
Answer
AND TIME
So basically you have some errors going on. Your first one is your styling. You really need to make your styles more flexible, but this will solve the right button problem I was having.
JavaScript
1
5
1
.button-pad > div {
2
z-index: 9999;
3
width: 50px;
4
}
5
http://jsfiddle.net/34oeacnm/8/
JavaScript
1
17
17
1
$(document).on('click', '.button-pad .button', function(e) {
2
var e = jQuery.Event("keydown");
3
if ($(this).hasClass('left-btn')) {
4
e.which = 37;
5
}
6
else if ($(this).hasClass('up-btn')) {
7
e.which = 38;
8
}
9
else if ($(this).hasClass('right-btn')) {
10
e.which = 39;
11
}
12
else if ($(this).hasClass('down-btn')) {
13
e.which = 40;
14
}
15
$(document).trigger(e);
16
});
17
You had some of your selectors off. And I stole some information on how to trigger from Definitive way to trigger keypress events with jQuery.