-
Notifications
You must be signed in to change notification settings - Fork 0
/
Piece.js
104 lines (82 loc) · 2.82 KB
/
Piece.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
"use strict";
blocks.Piece = function () {
//set the type of the piece
this.type = blocks.types[Math.floor(Math.random() * blocks.types.length)];
this.map = blocks.maps[this.type];
this.position = {top: 0, left: 1};
this.set_direction();
this.dim = this.map[this.direction].length; //will never change as long as type doesn't change
};
blocks.Piece.prototype.set_direction = function (direction) {
this.direction = direction ||
blocks.directions[Math.floor(Math.random() * blocks.directions.length)];
};
blocks.Piece.prototype.set_position = function (top, left) {
this.position.top = top;
this.position.left = left;
};
blocks.Piece.prototype.leftmost = function (direction) {
var maxLeft = 0, i, j;
for (i = 0; i < this.dim; i++) {
for (j = 0; j < this.dim; j++) {
if (j > maxLeft && this.map[direction || this.direction][i][j]) {
maxLeft = j;
}
}
}
return this.dim - 1 - maxLeft;
};
blocks.Piece.prototype.rightmost = function (direction) {
var maxRight = this.dim - 1, i, j;
for (i = 0; i < this.dim; i++) {
for (j = 0; j < this.dim; j++) {
if (j < maxRight && this.map[direction || this.direction][i][j]) {
maxRight = j;
}
}
}
return this.dim - 1 - maxRight;
};
blocks.Piece.prototype.topmost = function (direction) {
var i, j;
for (i = 0; i < this.dim; i++) {
for (j = 0; j < this.dim; j++) {
if (this.map[direction || this.direction][i][j]) {
return i;
}
}
}
};
blocks.Piece.prototype.bottommost = function (direction) {
var i, j;
for (i = this.dim - 1; i >= 0; i--) {
for (j = 0; j < this.dim; j++) {
if (this.map[direction || this.direction][i][j]) {
return i;
}
}
}
};
blocks.Piece.prototype.rotate_valid = function () {
var next = blocks.next_direction(this.direction);
return this.position.left + this.leftmost(next) >= 0 &&
this.position.left + this.rightmost(next) < blocks.BOARD_WIDTH;
};
//returns whether it hit bottom
blocks.Piece.prototype.down_valid = function () {
return this.position.top + this.bottommost() + 1 - 2 < blocks.BOARD_HEIGHT;
};
blocks.Piece.prototype.left_valid = function () {
//the 2 is a kludge
return this.position.left + this.leftmost() - 1 - 2 >= 0;
};
blocks.Piece.prototype.right_valid = function () {
//the 2 is a kludge
return this.position.left + this.rightmost() + 1 - 2 < blocks.BOARD_WIDTH;
};
//blocks.Piece.prototype.snap_right = function () { while(!this.move_right()); };
//blocks.Piece.prototype.snap_left = function () { while(!this.move_left()); };
/*blocks.Piece.prototype.snap_down = function () {
while(!this.move_down());
return true;
};*/