GameMachine.js 10 KB

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