Advertisement
Guest User

Untitled

a guest
Dec 14th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.01 KB | None | 0 0
  1. /*
  2. * General overview of all the methods and variables
  3. * var pieces[] - used to store pieces
  4. * var tiles[] - used to store pieces
  5. * var gameBoard - a 2d array used to store the information about the board
  6. *
  7. * function distance() - used to calculate distance between two cells
  8. * function Piece(element, position) - an object - stores all the information about the piece
  9. * INSIDE PIECE: this.makeKing() - make an element a king - simply assigns the picture to it.
  10. * INSIDE PIECE: this.move = function(tile) - removes the checker from the board cell;
  11. * updates the board, assigns a new cell for that piece;
  12. * toggles animation and changes the turn
  13. *
  14. */
  15. //Script is fired when the entire page loads, including its content
  16.  
  17.  
  18. /////////////////////////////////////////////////////////////////////
  19.  
  20.  
  21.  
  22. /////////////////////////////////////////////////////////////////////////////////////////////////////////
  23. //Board object - controls logistics of game
  24.  
  25.  
  26.  
  27. //////////////////////////////////////////////////////////////////////////////////////
  28.  
  29. function gameState(socket){
  30. this.player1PieceNum = 12;
  31. this.player2PieceNum = 12;
  32. this.playerType = null;
  33.  
  34. this.getPlayerType = function () {
  35. return this.playerType;
  36. };
  37.  
  38. this.setPlayerType = function (p) {
  39. console.assert(typeof p == "string", "%s: Expecting a string, got a %s", arguments.callee.name, typeof p);
  40. this.playerType = p;
  41. };
  42.  
  43. this.whoWon = function(){
  44. if (this.player1PieceNum==0){
  45. return 2;
  46. }
  47. if (this.player2PieceNum==0){
  48. return 1;
  49. }
  50. return null;
  51. }
  52. //Initial setup of Game Board
  53. var gameBoard = [
  54. [ 0, 1, 0, 1, 0, 1, 0, 1 ],
  55. [ 1, 0, 1, 0, 1, 0, 1, 0 ],
  56. [ 0, 1, 0, 1, 0, 1, 0, 1 ],
  57. [ 0, 0, 0, 0, 0, 0, 0, 0 ],
  58. [ 0, 0, 0, 0, 0, 0, 0, 0 ],
  59. [ 2, 0, 2, 0, 2, 0, 2, 0 ],
  60. [ 0, 2, 0, 2, 0, 2, 0, 2 ],
  61. [ 2, 0, 2, 0, 2, 0, 2, 0 ]
  62. ];
  63.  
  64. //arrays to store the instances
  65. var pieces = [];
  66. var tiles = [];
  67.  
  68. //Distance formula
  69. var dist = function (x1, y1, x2, y2) {
  70. return Math.sqrt(Math.pow((x1-x2),2)+Math.pow((y1-y2),2));
  71. }
  72. function Piece (element, position) {
  73. //linked DOM element
  74. this.element = element;
  75. //positions on gameBoard array in format row, column
  76. this.position = position;
  77. //which player's piece is it
  78. this.player = '';
  79. //figure out player by piece id
  80. if(this.element.attr("id") < 12)
  81. this.player = 1;
  82. else
  83. this.player = 2;
  84.  
  85. //makes object a king
  86. this.king = false;
  87. this.makeKing = function () {
  88. this.element.css("backgroundImage", "url('king.png')");
  89. this.king = true;
  90. }
  91.  
  92. //moves the piece
  93. this.move = function (tile) {
  94. this.element.removeClass('selected');
  95. if(!Board.isValidPlacetoMove(tile.position[0], tile.position[1])) return false;
  96. //make sure piece doesn't go backwards if it's not a king
  97. if(this.player == 1 && this.king == false) {
  98. if(tile.position[0] < this.position[0]) return false;
  99. } else if (this.player == 2 && this.king == false) {
  100. if(tile.position[0] > this.position[0]) return false;
  101. }
  102. //remove the mark from Board.board and put it in the new spot
  103. Board.board[this.position[0]][this.position[1]] = 0;
  104. Board.board[tile.position[0]][tile.position[1]] = this.player;
  105. this.position = [tile.position[0], tile.position[1]];
  106. //change the css using board's dictionary
  107. this.element.css('top', Board.dictionary[this.position[0]]);
  108. this.element.css('left', Board.dictionary[this.position[1]]);
  109. //if piece reaches the end of the row on opposite side crown it a king (can move all directions)
  110. if(!this.king && (this.position[0] == 0 || this.position[0] == 7 ))
  111. this.makeKing();
  112. Board.changePlayerTurn();
  113. return true;
  114. };
  115.  
  116. //tests if piece can jump anywhere
  117. this.canJumpAny = function(){
  118. if(this.canOpponentJump([this.position[0]+2, this.position[1]+2]) ||
  119. this.canOpponentJump([this.position[0]+2, this.position[1]-2]) ||
  120. this.canOpponentJump([this.position[0]-2, this.position[1]+2]) ||
  121. this.canOpponentJump([this.position[0]-2, this.position[1]-2])) {
  122. return true;
  123. } return false;
  124. };
  125.  
  126. //tests if an opponent jump can be made to a specific place
  127. this.canOpponentJump = function(newPosition) {
  128. //find what the displacement is
  129. var dx = newPosition[1] - this.position[1];
  130. var dy = newPosition[0] - this.position[0];
  131. //make sure object doesn't go backwards if not a king
  132. if(this.player == 1 && this.king == false) {
  133. if(newPosition[0] < this.position[0]) return false;
  134. } else if (this.player == 2 && this.king == false) {
  135. if(newPosition[0] > this.position[0]) return false;
  136. }
  137. //must be in bounds
  138. if(newPosition[0] > 7 || newPosition[1] > 7 || newPosition[0] < 0 || newPosition[1] < 0) return false;
  139. //middle tile where the piece to be conquered sits
  140. var tileToCheckx = this.position[1] + dx/2;
  141. var tileToChecky = this.position[0] + dy/2;
  142. //if there is a piece there and there is no piece in the space after that
  143. if(!Board.isValidPlacetoMove(tileToChecky, tileToCheckx) && Board.isValidPlacetoMove(newPosition[0], newPosition[1])) {
  144. //find which object instance is sitting there
  145. for(pieceIndex in pieces) {
  146. if(pieces[pieceIndex].position[0] == tileToChecky && pieces[pieceIndex].position[1] == tileToCheckx) {
  147. if(this.player != pieces[pieceIndex].player) {
  148. //return the piece sitting there
  149. return pieces[pieceIndex];
  150. }
  151. }
  152. }
  153. }
  154. return false;
  155. };
  156.  
  157. this.opponentJump = function (tile) {
  158. var pieceToRemove = this.canOpponentJump(tile.position);
  159. //if there is a piece to be removed, remove it
  160. if(pieceToRemove) {
  161. pieces[pieceIndex].remove();
  162. return true;
  163. }
  164. return false;
  165. };
  166.  
  167. this.remove = function () {
  168. //remove it and delete it from the gameboard
  169. this.element.css("display", "none");
  170. if(this.player == 1) {
  171. $('#player2').append("<div class='capturedPiece'></div>");
  172. this.player2PieceNum--;
  173. }
  174. if(this.player == 2){
  175. $('#player1').append("<div class='capturedPiece'></div>");
  176. this.player1PieceNum--;
  177. }
  178. Board.board[this.position[0]][this.position[1]] = 0;
  179. //reset position so it doesn't get picked up by the for loop in the canOpponentJump method
  180. this.position = [];
  181. }
  182. }
  183. function Tile (element, position) {
  184. //linked DOM element
  185. this.element = element;
  186. //position in gameboard
  187. this.position = position;
  188. //if tile is in range from the piece
  189. this.inRange = function(piece) {
  190. if(dist(this.position[0], this.position[1], piece.position[0], piece.position[1]) == Math.sqrt(2)) {
  191. //regular move
  192. return 'regular';
  193. } else if(dist(this.position[0], this.position[1], piece.position[0], piece.position[1]) == 2*Math.sqrt(2)) {
  194. //jump move
  195. return 'jump';
  196. }
  197. };
  198. }
  199. let Board = {
  200. board: gameBoard,
  201. playerTurn: 1,
  202. tilesElement: $('div.tiles'),
  203. //dictionary to convert position in Board.board to the viewport units
  204. dictionary: ["0vmin", "10vmin", "20vmin", "30vmin", "40vmin", "50vmin", "60vmin", "70vmin", "80vmin", "90vmin"],
  205. //initialize the 8x8 board
  206. initialize: function () {
  207. var countPieces = 0;
  208. var countTiles = 0;
  209. for (row in this.board) { //row is the index
  210. for (column in this.board[row]) { //column is the index
  211. //whole set of if statements control where the tiles and pieces should be placed on the board
  212. if(row%2 == 1) {
  213. if(column%2 == 0) {
  214. this.tilesElement.append("<div class='tile' id='tile"+countTiles+"' style='top:"+this.dictionary[row]+";left:"+this.dictionary[column]+";'></div>");
  215. tiles[countTiles] = new Tile($("#tile"+countTiles), [parseInt(row), parseInt(column)]);
  216. countTiles += 1;
  217. }
  218. } else {
  219. if(column%2 == 1) {
  220. this.tilesElement.append("<div class='tile' id='tile"+countTiles+"' style='top:"+this.dictionary[row]+";left:"+this.dictionary[column]+";'></div>");
  221. tiles[countTiles] = new Tile($("#tile"+countTiles), [parseInt(row), parseInt(column)]);
  222. countTiles += 1;
  223. }
  224. }
  225. if(this.board[row][column] == 1) {
  226. $('.player1pieces').append("<div class='piece' id='"+countPieces+"' style='top:"+this.dictionary[row]+";left:"+this.dictionary[column]+";'></div>");
  227. pieces[countPieces] = new Piece($("#"+countPieces), [parseInt(row), parseInt(column)]);
  228. countPieces += 1;
  229. } else if(this.board[row][column] == 2) {
  230. $('.player2pieces').append("<div class='piece' id='"+countPieces+"' style='top:"+this.dictionary[row]+";left:"+this.dictionary[column]+";'></div>");
  231. pieces[countPieces] = new Piece($("#"+countPieces), [parseInt(row), parseInt(column)]);
  232. countPieces += 1;
  233. }
  234. }
  235. }
  236. },
  237. //check if the location has an object
  238. isValidPlacetoMove: function (row, column) {
  239. console.log(row); console.log(column); console.log(this.board);
  240. if(this.board[row][column] == 0) {
  241. return true;
  242. } return false;
  243. },
  244. //change the active player - also changes div.turn's CSS
  245. changePlayerTurn: function () {
  246. if(this.playerTurn == 1) {
  247. this.playerTurn = 2;
  248. $('.turn').css("background", "linear-gradient(to right, transparent 50%, #BEEE62 50%)");
  249. return;
  250. }
  251. if(this.playerTurn == 2) {
  252. this.playerTurn = 1;
  253. $('.turn').css("background", "linear-gradient(to right, #BEEE62 50%, transparent 50%)");
  254. }
  255. },
  256. //reset the game
  257. clear: function () {
  258. location.reload();
  259. }
  260. }
  261. //Piece object - there are 24 instances of them in a checkers game
  262.  
  263.  
  264. if (this.playerType == "A" && this.gameBoard.playerTurn == 1 || this.playerType == "B" && this.gameBoard.playerTurn == 2){
  265. $('.piece').on("click", function () {
  266. var selected;
  267. var isPlayersTurn = ($(this).parent().attr("class").split(' ')[0] == "player"+Board.playerTurn+"pieces");
  268. if(isPlayersTurn) {
  269. if($(this).hasClass('selected')) selected = true;
  270. $('.piece').each(function(index) {$('.piece').eq(index).removeClass('selected')});
  271. if(!selected) {
  272. $(this).addClass('selected');
  273. }
  274. }
  275. });
  276. $('.tile').on("click", function () {
  277. //make sure a piece is selected
  278. if($('.selected').length != 0) {
  279. //find the tile object being clicked
  280. var tileID = $(this).attr("id").replace(/tile/, '');
  281. var tile = tiles[tileID];
  282. //find the piece being selected
  283. var piece = pieces[$('.selected').attr("id")];
  284. //check if the tile is in range from the object
  285. var inRange = tile.inRange(piece);
  286. if(inRange) {
  287. //if the move needed is jump, then move it but also check if another move can be made (double and triple jumps)
  288. if(inRange == 'jump') {
  289. if(piece.opponentJump(tile)) {
  290. piece.move(tile);
  291. if(piece.canJumpAny()) {
  292. Board.changePlayerTurn(); //change back to original since another turn can be made
  293. piece.element.addClass('selected');
  294. }
  295. }
  296. //if it's regular then move it if no jumping is available
  297. } else if(inRange == 'regular') {
  298. if(!piece.canJumpAny()) {
  299. piece.move(tile);
  300. if (getPlayerType() == "A"){
  301. var outgoingMsg = messages.O_MOVE_TO_A;
  302. outgoingMsg.pieceEl = piece.element;
  303. outgoingMsg.piecePos = piece.position;
  304. outgoingMsg.tileEl = tile.element;
  305. outgoingMsg.tilePos = tile.position;
  306. socket.send(JSON.stringify(outgoingMsg));
  307. }
  308. else {
  309. if (getPlayerType() == "B"){
  310. var outgoingMsg = messages.O_MOVE_TO_B;
  311. outgoingMsg.pieceEl = piece.element;
  312. outgoingMsg.piecePos = piece.position;
  313. outgoingMsg.tileEl = tile.element;
  314. outgoingMsg.tilePos = tile.position;
  315. socket.send(JSON.stringify(outgoingMsg));
  316. }
  317. }
  318. } else {
  319. alert("You must jump when possible!");
  320. }
  321. }
  322. }
  323. }
  324. });
  325. }
  326. }
  327.  
  328.  
  329. (function setup(){
  330. console.log("setting up..");
  331. var socket = new WebSocket("ws://localhost:3000");
  332. var gs = new gameState(socket);
  333. console.log(typeof gs.Board.initialize);
  334. // gs.Board.initialize();
  335. //initialize the board
  336. socket.onmessage = function (event) {
  337. let incomingMsg = JSON.parse(event.data);
  338. if (incomingMsg.type == Messages.T_PLAYER_TYPE){
  339. gs.setPlayerType( incomingMsg.data );
  340. }
  341. if (incomingMsg.type == Messages.T_MOVE_TO_A && gs.getPlayerType() == "B"){
  342. var tile = new Tile(incomingMsg.tileEl, incomingMsg.tilePos);
  343. var piece = new Piece(incomingMsg.pieceEl, incomingMsg.piecePos);
  344. piece.move(tile);
  345. }
  346. else {
  347. if (incomingMsg.type == Messages.T_MOVE_TO_B && gs.getPlayerType() == "A"){
  348. var tile = new Tile(incomingMsg.tileEl, incomingMsg.tilePos);
  349. var piece = new Piece(incomingMsg.pieceEl, incomingMsg.piecePos);
  350. piece.move(tile);
  351. }
  352. }
  353.  
  354. }
  355. socket.onopen = function(){
  356. socket.send("{}");
  357. };
  358. socket.onerror = function(){
  359. };
  360. }());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement