GameMachine.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. // var Card = require('./Card.js');
  2. const SHA256 = require('crypto-js/sha256');
  3. // TO-DO
  4. // Need to create an initialization move or something to get verified!
  5. // Players can have their names placed on state.players on init, showing turns and colors
  6. class GameMachine {
  7. constructor() {
  8. this.state = {
  9. board: new Board(),
  10. players: [],
  11. hash: '0123456789',
  12. stack: []
  13. };
  14. }
  15. flush() {
  16. console.log(this.state);
  17. }
  18. setState(state) {
  19. this.state = { ...this.state, ...state};
  20. }
  21. setBoard(board) {
  22. this.state = { ...this.state, board};
  23. }
  24. save() {
  25. return {...this.state, board: this.state.board.save()};
  26. }
  27. load(state) {
  28. this.state.board.load(state.board);
  29. this.state = { ...state, board: this.state.board };
  30. }
  31. setPlayers(players) {
  32. this.state = { ...this.state, players};
  33. }
  34. getPlayerNumber(player) {
  35. return this.state.players[0] === player ? 0 : 1;
  36. // return this.state.players[0] === UserService.getUsername() ? 0 : 1;
  37. }
  38. getPositionTeam(x) {
  39. return this.state.players.indexOf(this.state.board.owners[x]);
  40. }
  41. hasFinished() {
  42. return this.state.stack.length >= 10;
  43. }
  44. getWinner() {
  45. const score1 = this.state.board.getScore(this.state.players[0]);
  46. const score2 = this.state.board.getScore(this.state.players[1]) + 1;
  47. return score1 === score2 ? -1
  48. : (
  49. score1 > score2
  50. ? this.state.players[0]
  51. : this.state.players[1]
  52. );
  53. }
  54. isMyTurn(player) {
  55. let moves = this.state.stack.length;
  56. return this.getPlayerNumber(player) === moves % 2 && moves < 10;
  57. }
  58. needFinalization() {
  59. return this.state.stack.length === 9;
  60. }
  61. runMove(move) {
  62. const spray = SHA256(JSON.stringify(move)).toString();
  63. if (this.state.stack.includes(spray)) {
  64. console.log('This move has been processed already');
  65. return;
  66. }
  67. try {
  68. move.verify(this.state);
  69. move.performMove(this.state.board);
  70. this.state.stack.push(spray);
  71. } catch (e) {
  72. throw e;
  73. }
  74. }
  75. ownerOf(x) {
  76. return this.state.board.owners[x];
  77. }
  78. validateMatch(stack) {
  79. this.setPlayers()
  80. for (let i = 0; i < 9; i++) {
  81. this.runMove(stack[i]);
  82. }
  83. }
  84. }
  85. class Board {
  86. constructor() {
  87. this.data = [];
  88. this.owners = [];
  89. // These 2 to be updated after every move
  90. this.triggerPaths = []; // like attackVectors
  91. this.plusPaths = []; // like attackVectors
  92. for (let i=0; i < 9; i += 1) {
  93. this.triggerPaths[i] = [];
  94. this.plusPaths[i] = {
  95. winners: [],
  96. sums: []
  97. };
  98. }
  99. }
  100. getScore(player) {
  101. return this.owners.reduce((a,b) => b === player ? a + 1 : a, 0);
  102. }
  103. debug() {
  104. console.log('BOARD');
  105. console.log('---------------------------');
  106. console.log('Cards :');
  107. let s = '';
  108. for(let i=0,j=0;i<9;i+=1) {
  109. s += `P${this.owners[i]}:${(this.data[i] ? this.data[i].attack.reduce((a,b) => a + b + '|', '|') : 'Empty')}\t`;
  110. j += 1;
  111. if(j%3===0)s += '\n';
  112. }
  113. console.log(s);
  114. console.log('---------------------------');
  115. console.log('Triggers');
  116. console.log('---------------------------');
  117. s = '';
  118. for(let i=0,j=0;i<9;i+=1) {
  119. s += `[${this.triggerPaths[i]}]\t\t`;
  120. j += 1;
  121. if(j%3===0)s += '\n';
  122. }
  123. console.log(s);
  124. console.log('---------------------------');
  125. console.log('Pluspaths');
  126. console.log('---------------------------');
  127. s = '';
  128. for(let i=0,j=0;i<9;i+=1) {
  129. s += `[${(this.plusPaths[i].winners.reduce((a,b) => a + b + '|', '|'))}]\t\t`;
  130. j += 1;
  131. if(j%3===0)s += '\n';
  132. }
  133. console.log(s);
  134. console.log('---------------------------');
  135. }
  136. putCard(card, position, player) { // position = 0-9
  137. this.data[ position ] = card;
  138. this.owners[position] = player;
  139. this._calculatePlusAndTriggers(position);
  140. this._analyze(position);
  141. }
  142. _calculatePlusAndTriggers(position) {
  143. const attacker = this.data[position];
  144. for (let j = 0; j < 4; j += 1) {
  145. if ( Board.ATTACK_VECTORS[position][j] === 0 ) continue;
  146. const dx = this._getDisplacement(j);
  147. const attackedCard = this.data[position + dx];
  148. const defendJ = ( j + 2 ) % 4;
  149. if (attackedCard) {
  150. const sum = attacker.attack[j] + attackedCard.attack[defendJ];
  151. this.plusPaths[ position ].sums[j] = sum;
  152. this.plusPaths[ position + dx].sums[defendJ] = sum;
  153. this.triggerPaths[ position ][j] = attacker.attack[j] - attackedCard.attack[defendJ];
  154. this.triggerPaths[position + dx][defendJ] = -this.triggerPaths[position][j]; // opposite to the above
  155. }
  156. }
  157. }
  158. _getDisplacement(j) {
  159. switch(j) {
  160. case 0: return 1; //return {x: 1, y:0};
  161. case 1: return -3; //return {x: 0, y:1};
  162. case 2: return -1; //return {x: -1, y:0};
  163. case 3: return 3; //return {x: 0, y:-1};
  164. default: throw Error ('Cannot _getDisplacement of this value: ' + j);
  165. }
  166. }
  167. _flipCard(position, combo, owner) {
  168. // change owner!
  169. let isFlipping = owner !== this.owners[position];
  170. this.owners[position] = owner;
  171. if(combo && isFlipping) this._analyze(position, combo);
  172. }
  173. _analyze(position, combo) {
  174. // check rules!
  175. if( this._checkSameRule(position) && !combo ) {
  176. // Apply Same Rule
  177. this._applySameRule(position);
  178. }
  179. if ( this._checkPlusRule(position) && !combo ) {
  180. // Apply Plus Rule
  181. this._applyPlusRule(position);
  182. }
  183. this._applyAttackRule(position, combo);
  184. }
  185. _applyAttackRule(position, combo = false) { //seems ok
  186. if ( !this.triggerPaths[position] ) return;
  187. for (let j = 0; j < 4; j += 1) {
  188. if ( Board.ATTACK_VECTORS[position][j] === 0 ) continue;
  189. const dx = this._getDisplacement(j);
  190. if ( this.triggerPaths[position][j] > 0 ) {
  191. this._flipCard(position + dx, combo, this.owners[position]);
  192. }
  193. }
  194. }
  195. _applySameRule(position) {
  196. for (let j = 0; j < 4; j += 1) {
  197. if ( Board.ATTACK_VECTORS[position][j] === 0 ) continue;
  198. const dx = this._getDisplacement(j);
  199. if ( this.triggerPaths[position][j] === 0 ) {
  200. this._flipCard(position + dx, true, this.owners[position]);
  201. }
  202. }
  203. }
  204. _applyPlusRule(position) {
  205. for (let j = 0; j < 4; j += 1) { // this for loop can be fixed seems obsolete & slow
  206. if ( Board.ATTACK_VECTORS[position][j] === 0 ) continue;
  207. const dx = this._getDisplacement(j);
  208. if ( this.plusPaths[position].winners.includes(this.plusPaths[position].sums[j]) ) {
  209. this._flipCard(position + dx, true, this.owners[position]);
  210. }
  211. }
  212. }
  213. _checkSameRule(position) {
  214. let sames = 0;
  215. for (let j = 0; j < 4; j += 1) {
  216. if ( Board.ATTACK_VECTORS[position][j] === 0 ) continue;
  217. if (this.triggerPaths[position] &&
  218. this.triggerPaths[position][j] === 0) {
  219. sames += 1;
  220. }
  221. }
  222. return sames > 1;
  223. }
  224. _checkPlusRule(position) { // refactor plz // need fix (problem double plus a.k.a. four side attack)
  225. let pluses = {};
  226. for (let j = 0; j < 4; j += 1) {
  227. if ( Board.ATTACK_VECTORS[position][j] === 0 ) continue;
  228. let sum = this.plusPaths[position].sums[j];
  229. if ( sum ) {
  230. pluses[sum] = (pluses[sum] || 0) + 1;
  231. }
  232. }
  233. for (let i in pluses) {
  234. if (pluses[i] > 1) {
  235. this.plusPaths[position].winners.push(parseInt(i, 10));
  236. }
  237. }
  238. return this.plusPaths[position].winners.length > 0;
  239. }
  240. isEmpty(position) {
  241. return !this.data[position];
  242. }
  243. save() {
  244. return {
  245. data: this.data,
  246. owners: this.owners
  247. };
  248. }
  249. load(state) {
  250. this.data = state.data;
  251. this.owners = state.owners;
  252. }
  253. }
  254. // START From top left goin row row
  255. Board.ATTACK_VECTORS = [
  256. // [R, U, L, D] // right up left down
  257. [1, 0, 0, 1],
  258. [1, 0, 1, 1],
  259. [0, 0, 1, 1],
  260. [1, 1, 0, 1],
  261. [1, 1, 1, 1],
  262. [0, 1, 1, 1],
  263. [1, 1, 0, 0],
  264. [1, 1, 1, 0],
  265. [0, 1, 1, 0]
  266. ];
  267. module.exports = GameMachine;