connect-four.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. //Javascript Connect 4 Game
  2. function start_game() {
  3. "use strict";
  4. document.body.innerHTML = '';
  5. const DELAY_COMP = 0.5;
  6. const GRID_CIRCLE = 0.7;
  7. const GRID_COLS = 7;
  8. const GRID_ROWS = 6;
  9. const MARGIN = 0.02;
  10. const COLOR_BACKGROUND = "mintcream";
  11. const COLOR_COMP = "yellow";
  12. const COLOR_COMP_DRK = "olive";
  13. const COLOR_FRAME = "dodgerblue";
  14. const COLOR_FRAME_BUTT = "royalblue";
  15. const COLOR_PLAY = "red";
  16. const COLOR_PLAY_DRK = "darkred";
  17. const COLOR_TIE = "darkgrey";
  18. const COLOR_TIE_DRK = "black";
  19. const COLOR_WIN = "black";
  20. const TEXT_COMP = "Computer";
  21. const TEXT_PLAY = "YOU";
  22. const TEXT_TIE = "DRAW";
  23. const TEXT_WIN = "WON!";
  24. class Cell {
  25. constructor(left, top, w, h, row, col) {
  26. this.bot = top + h;
  27. this.left = left;
  28. this.right = left + w;
  29. this.top = top;
  30. this.w = w;
  31. this.h = h;
  32. this.row = row;
  33. this.col = col;
  34. this.cx = left + w / 2;
  35. this.cy = top + h / 2;
  36. this.r = w * GRID_CIRCLE / 2;
  37. this.highlight = null;
  38. this.owner = null;
  39. this.winner = false;
  40. }
  41. contains(x, y) {
  42. return x > this.left && x < this.right && y > this.top && y < this.bot;
  43. }
  44. draw(/** @type {CanvasRenderingContext2D} */ ctx) {
  45. let color = this.owner == null ? COLOR_BACKGROUND : this.owner ? COLOR_PLAY : COLOR_COMP;
  46. ctx.fillStyle = color;
  47. ctx.beginPath();
  48. ctx.arc(this.cx, this.cy, this.r, 0, Math.PI * 2);
  49. ctx.fill();
  50. if (this.winner || this.highlight != null) {
  51. color = this.winner ? COLOR_WIN : this.highlight ? COLOR_PLAY : COLOR_COMP;
  52. ctx.lineWidth = this.r / 4;
  53. ctx.strokeStyle = color;
  54. ctx.beginPath();
  55. ctx.arc(this.cx, this.cy, this.r, 0, Math.PI * 2);
  56. ctx.stroke();
  57. }
  58. }
  59. }
  60. var canv = document.createElement("canvas");
  61. document.body.appendChild(canv);
  62. var ctx = canv.getContext("2d");
  63. var gameOver, gameTied, grid = [], playersTurn, timeComp;
  64. var height, width, margin;
  65. setDimensions();
  66. canv.addEventListener("click", click);
  67. canv.addEventListener("mousemove", highlightGrid);
  68. window.addEventListener("resize", setDimensions);
  69. var timeDelta, timeLast;
  70. requestAnimationFrame(loop);
  71. function loop(timeNow) {
  72. if (!timeLast) {
  73. timeLast = timeNow;
  74. }
  75. timeDelta = (timeNow - timeLast) / 1000; // seconds
  76. timeLast = timeNow;
  77. goComputer(timeDelta);
  78. drawBackground();
  79. drawGrid();
  80. drawText();
  81. requestAnimationFrame(loop);
  82. }
  83. function checkWin(row, col) {
  84. let diagL = [], diagR = [], horiz = [], vert = [];
  85. for (let i = 0; i < GRID_ROWS; i++) {
  86. for (let j = 0; j < GRID_COLS; j++) {
  87. if (i == row) {
  88. horiz.push(grid[i][j]);
  89. }
  90. if (j == col) {
  91. vert.push(grid[i][j]);
  92. }
  93. if (i - j == row - col) {
  94. diagL.push(grid[i][j]);
  95. }
  96. if (i + j == row + col) {
  97. diagR.push(grid[i][j]);
  98. }
  99. }
  100. }
  101. return connect4(diagL) || connect4(diagR) || connect4(horiz) || connect4(vert);
  102. }
  103. function connect4(cells = []) {
  104. let count = 0, lastOwner = null;
  105. let winningCells = [];
  106. for (let i = 0; i < cells.length; i++) {
  107. if (cells[i].owner == null) {
  108. count = 0;
  109. winningCells = [];
  110. }
  111. else if (cells[i].owner == lastOwner) {
  112. count++;
  113. winningCells.push(cells[i]);
  114. }
  115. else {
  116. count = 1;
  117. winningCells = [];
  118. winningCells.push(cells[i]);
  119. }
  120. lastOwner = cells[i].owner;
  121. if (count == 4) {
  122. for (let cell of winningCells) {
  123. cell.winner = true;
  124. }
  125. return true;
  126. }
  127. }
  128. return false;
  129. }
  130. function click(ev) {
  131. if (gameOver) {
  132. newGame();
  133. return;
  134. }
  135. if (!playersTurn) {
  136. return;
  137. }
  138. selectCell();
  139. }
  140. function createGrid() {
  141. grid = [];
  142. let cell, marginX, marginY;
  143. if ((width - margin * 2) * GRID_ROWS / GRID_COLS < height - margin * 2) {
  144. cell = (width - margin * 2) / GRID_COLS;
  145. marginX = margin;
  146. marginY = (height - cell * GRID_ROWS) / 2;
  147. }
  148. else {
  149. cell = (height - margin * 2) / GRID_ROWS;
  150. marginX = (width - cell * GRID_COLS) / 2;
  151. marginY = margin;
  152. }
  153. for (let i = 0; i < GRID_ROWS; i++) {
  154. grid[i] = [];
  155. for (let j = 0; j < GRID_COLS; j++) {
  156. let left = marginX + j * cell;
  157. let top = marginY + i * cell;
  158. grid[i][j] = new Cell(left, top, cell, cell, i, j);
  159. }
  160. }
  161. }
  162. function drawBackground() {
  163. ctx.fillStyle = COLOR_BACKGROUND;
  164. ctx.fillRect(0, 0, width, height);
  165. }
  166. function drawGrid() {
  167. let cell = grid[0][0];
  168. let fh = cell.h * GRID_ROWS;
  169. let fw = cell.w * GRID_COLS;
  170. ctx.fillStyle = COLOR_FRAME;
  171. ctx.fillRect(cell.left, cell.top, fw, fh);
  172. ctx.fillStyle = COLOR_FRAME_BUTT;
  173. ctx.fillRect(cell.left - margin / 2, cell.top + fh - margin / 2, fw + margin, margin);
  174. for (let row of grid) {
  175. for (let cell of row) {
  176. cell.draw(ctx);
  177. }
  178. }
  179. }
  180. function drawText() {
  181. if (!gameOver) {
  182. return;
  183. }
  184. let size = grid[0][0].h;
  185. ctx.fillStyle = gameTied ? COLOR_TIE : playersTurn ? COLOR_PLAY : COLOR_COMP;
  186. ctx.font = size + "px dejavu sans mono";
  187. ctx.lineJoin = "round";
  188. ctx.lineWidth = size / 10;
  189. ctx.strokeStyle = gameTied ? COLOR_TIE_DRK : playersTurn ? COLOR_PLAY_DRK : COLOR_COMP_DRK;
  190. ctx.textAlign = "center";
  191. ctx.textBaseline = "middle";
  192. let offset = size * 0.55;
  193. let text = gameTied ? TEXT_TIE : playersTurn ? TEXT_PLAY : TEXT_COMP;
  194. if (gameTied) {
  195. ctx.strokeText(text, width / 2, height / 2);
  196. ctx.fillText(text, width / 2, height / 2);
  197. } else {
  198. ctx.strokeText(text, width / 2, height / 2 - offset);
  199. ctx.fillText(text, width / 2, height / 2 - offset);
  200. ctx.strokeText(TEXT_WIN, width / 2, height / 2 + offset);
  201. ctx.fillText(TEXT_WIN, width / 2, height / 2 + offset);
  202. }
  203. }
  204. function goComputer(delta) {
  205. if (playersTurn || gameOver) {
  206. return;
  207. }
  208. if (timeComp > 0) {
  209. timeComp -= delta;
  210. if (timeComp <= 0) {
  211. selectCell();
  212. }
  213. return;
  214. }
  215. let options = [];
  216. options[0] = [];
  217. options[1] = [];
  218. options[2] = [];
  219. options[3] = [];
  220. let cell;
  221. for (let i = 0; i < GRID_COLS; i++) {
  222. cell = highlightCell(grid[0][i].cx, grid[0][i].cy);
  223. if (cell == null) {
  224. continue;
  225. }
  226. cell.owner = playersTurn;
  227. if (checkWin(cell.row, cell.col)) {
  228. options[0].push(i);
  229. } else {
  230. cell.owner = !playersTurn;
  231. if (checkWin(cell.row, cell.col)) {
  232. options[1].push(i);
  233. } else {
  234. cell.owner = playersTurn;
  235. if (cell.row > 0) {
  236. grid[cell.row - 1][cell.col].owner = !playersTurn;
  237. if (checkWin(cell.row - 1, cell.col)) {
  238. options[3].push(i);
  239. }
  240. else {
  241. options[2].push(i);
  242. }
  243. grid[cell.row - 1][cell.col].owner = null;
  244. }
  245. else {
  246. options[2].push(i);
  247. }
  248. }
  249. }
  250. cell.highlight = null;
  251. cell.owner = null;
  252. }
  253. for (let row of grid) {
  254. for (let cell of row) {
  255. cell.winner = false;
  256. }
  257. }
  258. let col;
  259. if (options[0].length > 0) {
  260. col = options[0][Math.floor(Math.random() * options[0].length)];
  261. } else if (options[1].length > 0) {
  262. col = options[1][Math.floor(Math.random() * options[1].length)];
  263. } else if (options[2].length > 0) {
  264. col = options[2][Math.floor(Math.random() * options[2].length)];
  265. } else if (options[3].length > 0) {
  266. col = options[3][Math.floor(Math.random() * options[3].length)];
  267. }
  268. highlightCell(grid[0][col].cx, grid[0][col].cy);
  269. timeComp = DELAY_COMP;
  270. }
  271. function highlightCell(x, y) {
  272. let col = null;
  273. for (let row of grid) {
  274. for (let cell of row) {
  275. cell.highlight = null;
  276. if (cell.contains(x, y)) {
  277. col = cell.col;
  278. }
  279. }
  280. }
  281. if (col == null) {
  282. return;
  283. }
  284. for (let i = GRID_ROWS - 1; i >= 0; i--) {
  285. if (grid[i][col].owner == null) {
  286. grid[i][col].highlight = playersTurn;
  287. return grid[i][col];
  288. }
  289. }
  290. return null;
  291. }
  292. function highlightGrid(/** @type {MouseEvent} */ ev) {
  293. if (!playersTurn || gameOver) {
  294. return;
  295. }
  296. highlightCell(ev.clientX, ev.clientY);
  297. }
  298. function newGame() {
  299. playersTurn = Math.random() < 0.5;
  300. gameOver = false;
  301. gameTied = false;
  302. createGrid();
  303. }
  304. function selectCell() {
  305. let highlighting = false;
  306. OUTER: for (let row of grid) {
  307. for (let cell of row) {
  308. if (cell.highlight != null) {
  309. highlighting = true;
  310. cell.highlight = null;
  311. cell.owner = playersTurn;
  312. if (checkWin(cell.row, cell.col)) {
  313. gameOver = true;
  314. }
  315. break OUTER;
  316. }
  317. }
  318. }
  319. if (!highlighting) {
  320. return;
  321. }
  322. if (!gameOver) {
  323. gameTied = true;
  324. OUTER: for (let row of grid) {
  325. for (let cell of row) {
  326. if (cell.owner == null) {
  327. gameTied = false;
  328. break OUTER;
  329. }
  330. }
  331. }
  332. if (gameTied) {
  333. gameOver = true;
  334. }
  335. }
  336. if (!gameOver) {
  337. playersTurn = !playersTurn;
  338. }
  339. }
  340. function setDimensions() {
  341. height = window.innerHeight;
  342. width = window.innerWidth;
  343. canv.height = height;
  344. canv.width = width;
  345. margin = MARGIN * Math.min(height, width);
  346. newGame();
  347. }
  348. }