Sfoglia il codice sorgente

snake moving control

Dima Mironov 10 anni fa
parent
commit
0fe51dc90c
3 ha cambiato i file con 61 aggiunte e 9 eliminazioni
  1. 51 2
      controller.js
  2. 0 7
      models/session.js
  3. 10 0
      models/snake.js

+ 51 - 2
controller.js

@@ -1,7 +1,56 @@
 var Controller = function(){
-	
+	this.grid_size = {x: 20, y: 20};
+	this.initial_length = 3;
+	this.time_step = 400;
+	this.collectibles = [];
+	this.snake = new Snake(this.initial_length);
 }
 
 Controller.prototype.start_game = function(){
-	
+	this.session = new Session();
+	this.bind_events();
+}
+
+Controller.prototype.bind_events = function(){
+	window.onkeydown = function(e){
+		var direction = null;
+		switch (e.keyCode){
+			case 37:
+				direction = {x: -1, y: 0};
+				break;
+			case 38:
+				direction = {x: 0, y: 1};
+				break;
+			case 39:
+				direction = {x: 1, y: 0};
+				break;
+			case 40:
+				direction = {x: 0, y: -1};
+				break;
+
+		}
+		if (direction){
+			this.turn_snake(direction);
+		}
+	}
+}
+
+Controller.prototype.turn_snake = function(direction){
+	this.snake.physicsts[0].direction = direction;
+}
+
+Controller.prototype.step = function(){
+	this.snake.move(next_cell);
+}
+
+Controller.prototype.get_next_cell_position = function(){
+	var ph0 = this.snake.physicsts[0];
+	var next_cell = ph0.position;
+	next_cell.x += ph0.direction.x;
+	next_cell.y += ph0.direction.y;
+	if (next_cell.x < 0) next_cell.x = grid_size.x - 1;
+	if (next_cell.y < 0) next_cell.y = grid_size.y - 1;
+	if (next_cell.x = grid_size.x) next_cell.x = 0;
+	if (next_cell.y = grid_size.y) next_cell.y = 0;
+	return next_cell;
 }

+ 0 - 7
models/session.js

@@ -1,7 +0,0 @@
-var Session  = function(){
-	this.size = {x: 20, y: 20}; 
-	this.time_step = 400;
-	this.collectibles = [];
-	this.snakes = [];
-}
-

+ 10 - 0
models/snake.js

@@ -18,3 +18,13 @@ Snake.prototype.add_bonus = function(bonus){
 
 Snake.prototype.remove_physicist = function(index){	
 }
+
+
+Snake.prototype.move = function(next_cell){
+	this.physicist[0].position = next_cell;
+	for(var i = 1; i < this.physicist.length; i++){
+		this.physicists[i].position  = this.physicists[i-1].position;
+		this.physicists[i].direction = this.physicists[i-1].direction;
+	}
+
+}