connect-four.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. //Javascript Connect 4 Game
  2. function start_game() {
  3. "use strict";
  4. let button = document.getElementById("button");
  5. let h1 = document.getElementById("h1");
  6. let h3 = document.getElementById('h3');
  7. h3.remove()
  8. h1.remove();
  9. button.remove();
  10. // game parameters
  11. const DELAY_COMP = 0.5; // seconds for the computer to take its turn
  12. const GRID_CIRCLE = 0.7; // circle size as a fraction of cell size
  13. const GRID_COLS = 7; // number of game columns
  14. const GRID_ROWS = 6; // number of game rows
  15. const MARGIN = 0.02; // margin as a fraction of the shortest screen dimension
  16. // colour variables
  17. const COLOR_BACKGROUND = "mintcream";
  18. const COLOR_COMP = "yellow";
  19. const COLOR_COMP_DRK = "olive";
  20. const COLOR_FRAME = "dodgerblue";
  21. const COLOR_FRAME_BUTT = "royalblue";
  22. const COLOR_PLAY = "red";
  23. const COLOR_PLAY_DRK = "darkred";
  24. const COLOR_TIE = "darkgrey";
  25. const COLOR_TIE_DRK = "black";
  26. const COLOR_WIN = "black";
  27. // text variables
  28. const TEXT_COMP = "Computer";
  29. const TEXT_PLAY = "YOU";
  30. const TEXT_TIE = "DRAW";
  31. const TEXT_WIN = "WON!";
  32. // cell class
  33. class Cell {
  34. constructor(left, top, w, h, row, col) {
  35. this.bot = top + h;
  36. this.left = left;
  37. this.right = left + w;
  38. this.top = top;
  39. this.w = w;
  40. this.h = h;
  41. this.row = row;
  42. this.col = col;
  43. this.cx = left + w / 2;
  44. this.cy = top + h / 2;
  45. this.r = w * GRID_CIRCLE / 2;
  46. this.highlight = null;
  47. this.owner = null;
  48. this.winner = false;
  49. }
  50. contains(x, y) {
  51. return x > this.left && x < this.right && y > this.top && y < this.bot;
  52. }
  53. // draw the circle or hole
  54. draw(/** @type {CanvasRenderingContext2D} */ ctx) {
  55. // owner colour
  56. let color = this.owner == null ? COLOR_BACKGROUND : this.owner ? COLOR_PLAY : COLOR_COMP;
  57. // draw the circle
  58. ctx.fillStyle = color;
  59. ctx.beginPath();
  60. ctx.arc(this.cx, this.cy, this.r, 0, Math.PI * 2);
  61. ctx.fill();
  62. // draw highlighting
  63. if (this.winner || this.highlight != null) {
  64. // colour
  65. color = this.winner ? COLOR_WIN : this.highlight ? COLOR_PLAY : COLOR_COMP;
  66. // draw a circle around the perimeter
  67. ctx.lineWidth = this.r / 4;
  68. ctx.strokeStyle = color;
  69. ctx.beginPath();
  70. ctx.arc(this.cx, this.cy, this.r, 0, Math.PI * 2);
  71. ctx.stroke();
  72. }
  73. }
  74. }
  75. // set up the canvas and context
  76. var canv = document.createElement("canvas");
  77. document.body.appendChild(canv);
  78. var ctx = canv.getContext("2d");
  79. // game variables
  80. var gameOver, gameTied, grid = [], playersTurn, timeComp;
  81. // dimensions
  82. var height, width, margin;
  83. setDimensions();
  84. // event listeners
  85. canv.addEventListener("click", click);
  86. canv.addEventListener("mousemove", highlightGrid);
  87. window.addEventListener("resize", setDimensions);
  88. // game loop
  89. var timeDelta, timeLast;
  90. requestAnimationFrame(loop);
  91. function loop(timeNow) {
  92. // initialise timeLast
  93. if (!timeLast) {
  94. timeLast = timeNow;
  95. }
  96. // calculate the time difference
  97. timeDelta = (timeNow - timeLast) / 1000; // seconds
  98. timeLast = timeNow;
  99. // update
  100. goComputer(timeDelta);
  101. // draw
  102. drawBackground();
  103. drawGrid();
  104. drawText();
  105. // call the next frame
  106. requestAnimationFrame(loop);
  107. }
  108. function checkWin(row, col) {
  109. // get all the cells from each direction
  110. let diagL = [], diagR = [], horiz = [], vert = [];
  111. for (let i = 0; i < GRID_ROWS; i++) {
  112. for (let j = 0; j < GRID_COLS; j++) {
  113. // horizontal cells
  114. if (i == row) {
  115. horiz.push(grid[i][j]);
  116. }
  117. // vertical cells
  118. if (j == col) {
  119. vert.push(grid[i][j]);
  120. }
  121. // top left to bottom right
  122. if (i - j == row - col) {
  123. diagL.push(grid[i][j]);
  124. }
  125. // top right to bottom left
  126. if (i + j == row + col) {
  127. diagR.push(grid[i][j]);
  128. }
  129. }
  130. }
  131. // if any have four in a row, return a win!
  132. return connect4(diagL) || connect4(diagR) || connect4(horiz) || connect4(vert);
  133. }
  134. function connect4(cells = []) {
  135. let count = 0, lastOwner = null;
  136. let winningCells = [];
  137. for (let i = 0; i < cells.length; i++) {
  138. // no owner, reset the count
  139. if (cells[i].owner == null) {
  140. count = 0;
  141. winningCells = [];
  142. }
  143. // same owner, add to the count
  144. else if (cells[i].owner == lastOwner) {
  145. count++;
  146. winningCells.push(cells[i]);
  147. }
  148. // new owner, new count
  149. else {
  150. count = 1;
  151. winningCells = [];
  152. winningCells.push(cells[i]);
  153. }
  154. // set the lastOwner
  155. lastOwner = cells[i].owner;
  156. // four in a row is a win
  157. if (count == 4) {
  158. for (let cell of winningCells) {
  159. cell.winner = true;
  160. }
  161. return true;
  162. }
  163. }
  164. return false;
  165. }
  166. function click(ev) {
  167. if (gameOver) {
  168. newGame();
  169. return;
  170. }
  171. if (!playersTurn) {
  172. return;
  173. }
  174. selectCell();
  175. }
  176. function createGrid() {
  177. grid = [];
  178. // set up cell size and margins
  179. let cell, marginX, marginY;
  180. // portrait
  181. if ((width - margin * 2) * GRID_ROWS / GRID_COLS < height - margin * 2) {
  182. cell = (width - margin * 2) / GRID_COLS;
  183. marginX = margin;
  184. marginY = (height - cell * GRID_ROWS) / 2;
  185. }
  186. // landscape
  187. else {
  188. cell = (height - margin * 2) / GRID_ROWS;
  189. marginX = (width - cell * GRID_COLS) / 2;
  190. marginY = margin;
  191. }
  192. // populate the grid
  193. for (let i = 0; i < GRID_ROWS; i++) {
  194. grid[i] = [];
  195. for (let j = 0; j < GRID_COLS; j++) {
  196. let left = marginX + j * cell;
  197. let top = marginY + i * cell;
  198. grid[i][j] = new Cell(left, top, cell, cell, i, j);
  199. }
  200. }
  201. }
  202. function drawBackground() {
  203. ctx.fillStyle = COLOR_BACKGROUND;
  204. ctx.fillRect(0, 0, width, height);
  205. }
  206. function drawGrid() {
  207. // frame and butt
  208. let cell = grid[0][0];
  209. let fh = cell.h * GRID_ROWS;
  210. let fw = cell.w * GRID_COLS;
  211. ctx.fillStyle = COLOR_FRAME;
  212. ctx.fillRect(cell.left, cell.top, fw, fh);
  213. ctx.fillStyle = COLOR_FRAME_BUTT;
  214. ctx.fillRect(cell.left - margin / 2, cell.top + fh - margin / 2, fw + margin, margin);
  215. // cells
  216. for (let row of grid) {
  217. for (let cell of row) {
  218. cell.draw(ctx);
  219. }
  220. }
  221. }
  222. function drawText() {
  223. if (!gameOver) {
  224. return;
  225. }
  226. // set up text parameters
  227. let size = grid[0][0].h;
  228. ctx.fillStyle = gameTied ? COLOR_TIE : playersTurn ? COLOR_PLAY : COLOR_COMP;
  229. ctx.font = size + "px dejavu sans mono";
  230. ctx.lineJoin = "round";
  231. ctx.lineWidth = size / 10;
  232. ctx.strokeStyle = gameTied ? COLOR_TIE_DRK : playersTurn ? COLOR_PLAY_DRK : COLOR_COMP_DRK;
  233. ctx.textAlign = "center";
  234. ctx.textBaseline = "middle";
  235. // draw the text
  236. let offset = size * 0.55;
  237. let text = gameTied ? TEXT_TIE : playersTurn ? TEXT_PLAY : TEXT_COMP;
  238. if (gameTied) {
  239. ctx.strokeText(text, width / 2, height / 2);
  240. ctx.fillText(text, width / 2, height / 2);
  241. } else {
  242. ctx.strokeText(text, width / 2, height / 2 - offset);
  243. ctx.fillText(text, width / 2, height / 2 - offset);
  244. ctx.strokeText(TEXT_WIN, width / 2, height / 2 + offset);
  245. ctx.fillText(TEXT_WIN, width / 2, height / 2 + offset);
  246. }
  247. }
  248. function goComputer(delta) {
  249. if (playersTurn || gameOver) {
  250. return;
  251. }
  252. // count down till the computer makes its selection
  253. if (timeComp > 0) {
  254. timeComp -= delta;
  255. if (timeComp <= 0) {
  256. selectCell();
  257. }
  258. return;
  259. }
  260. // set up the options array
  261. let options = [];
  262. options[0] = []; // computer wins
  263. options[1] = []; // block the player from winning
  264. options[2] = []; // no significance
  265. options[3] = []; // give away a win
  266. // loop through each column
  267. let cell;
  268. for (let i = 0; i < GRID_COLS; i++) {
  269. cell = highlightCell(grid[0][i].cx, grid[0][i].cy);
  270. // column full, go to the next column
  271. if (cell == null) {
  272. continue;
  273. }
  274. // first priority, computer wins
  275. cell.owner = playersTurn;
  276. if (checkWin(cell.row, cell.col)) {
  277. options[0].push(i);
  278. } else {
  279. // second priority, block the player
  280. cell.owner = !playersTurn;
  281. if (checkWin(cell.row, cell.col)) {
  282. options[1].push(i);
  283. } else {
  284. cell.owner = playersTurn;
  285. // check the cell above
  286. if (cell.row > 0) {
  287. grid[cell.row - 1][cell.col].owner = !playersTurn;
  288. // last priority, let player win
  289. if (checkWin(cell.row - 1, cell.col)) {
  290. options[3].push(i);
  291. }
  292. // third priority, no significance
  293. else {
  294. options[2].push(i);
  295. }
  296. // deselect cell above
  297. grid[cell.row - 1][cell.col].owner = null;
  298. }
  299. // no row above, third priority, no significance
  300. else {
  301. options[2].push(i);
  302. }
  303. }
  304. }
  305. // cancel highlight and selection
  306. cell.highlight = null;
  307. cell.owner = null;
  308. }
  309. // clear the winning cells
  310. for (let row of grid) {
  311. for (let cell of row) {
  312. cell.winner = false;
  313. }
  314. }
  315. // randomly select a column in priority order
  316. let col;
  317. if (options[0].length > 0) {
  318. col = options[0][Math.floor(Math.random() * options[0].length)];
  319. } else if (options[1].length > 0) {
  320. col = options[1][Math.floor(Math.random() * options[1].length)];
  321. } else if (options[2].length > 0) {
  322. col = options[2][Math.floor(Math.random() * options[2].length)];
  323. } else if (options[3].length > 0) {
  324. col = options[3][Math.floor(Math.random() * options[3].length)];
  325. }
  326. // highlight the selected cell
  327. highlightCell(grid[0][col].cx, grid[0][col].cy);
  328. // set the delay
  329. timeComp = DELAY_COMP;
  330. }
  331. function highlightCell(x, y) {
  332. let col = null;
  333. for (let row of grid) {
  334. for (let cell of row) {
  335. // clear existing highlighting
  336. cell.highlight = null;
  337. // get the column
  338. if (cell.contains(x, y)) {
  339. col = cell.col;
  340. }
  341. }
  342. }
  343. if (col == null) {
  344. return;
  345. }
  346. // highlight the first unoccupied cell
  347. for (let i = GRID_ROWS - 1; i >= 0; i--) {
  348. if (grid[i][col].owner == null) {
  349. grid[i][col].highlight = playersTurn;
  350. return grid[i][col];
  351. }
  352. }
  353. return null;
  354. }
  355. function highlightGrid(/** @type {MouseEvent} */ ev) {
  356. if (!playersTurn || gameOver) {
  357. return;
  358. }
  359. highlightCell(ev.clientX, ev.clientY);
  360. }
  361. function newGame() {
  362. playersTurn = Math.random() < 0.5;
  363. gameOver = false;
  364. gameTied = false;
  365. createGrid();
  366. }
  367. function selectCell() {
  368. let highlighting = false;
  369. OUTER: for (let row of grid) {
  370. for (let cell of row) {
  371. if (cell.highlight != null) {
  372. highlighting = true;
  373. cell.highlight = null;
  374. cell.owner = playersTurn;
  375. if (checkWin(cell.row, cell.col)) {
  376. gameOver = true;
  377. }
  378. break OUTER;
  379. }
  380. }
  381. }
  382. // don't allow selection if no highlighting
  383. if (!highlighting) {
  384. return;
  385. }
  386. // check for a tied game
  387. if (!gameOver) {
  388. gameTied = true;
  389. OUTER: for (let row of grid) {
  390. for (let cell of row) {
  391. if (cell.owner == null) {
  392. gameTied = false;
  393. break OUTER;
  394. }
  395. }
  396. }
  397. // set game over
  398. if (gameTied) {
  399. gameOver = true;
  400. }
  401. }
  402. // switch the player if no game over
  403. if (!gameOver) {
  404. playersTurn = !playersTurn;
  405. }
  406. }
  407. function setDimensions() {
  408. height = window.innerHeight;
  409. width = window.innerWidth;
  410. canv.height = height;
  411. canv.width = width;
  412. margin = MARGIN * Math.min(height, width);
  413. newGame();
  414. }
  415. }