connect-four.js 12 KB

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