Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. export const createTable = (rowNum: number, cellNum: number): number[][] => {
  2. const row: number[] = Array(rowNum).fill(0);
  3. const table: number[][] = Array(cellNum)
  4. .fill(row)
  5. .map((row: number[]) => [...row]);
  6.  
  7. return table;
  8. };
  9.  
  10. export const recalculateTable = (table: number[][], index: number, value: number): number[][] => {
  11. return table.map((row: number[], i: number) => {
  12. if (index === i) {
  13. let emptyCell: number = row.indexOf(0);
  14.  
  15. row[emptyCell] = value;
  16. }
  17.  
  18. return [...row];
  19. });
  20. };
  21.  
  22. const checkVertical = (table: number[][]) => {
  23. for (let r = 3; r < 7; r++) {
  24. for (let c = 0; c < 6; c++) {
  25. if (table[r][c]) {
  26. if (
  27. table[r][c] === table[r - 1][c] &&
  28. table[r][c] === table[r - 2][c] &&
  29. table[r][c] === table[r - 3][c]
  30. ) {
  31. return table[r][c];
  32. }
  33. }
  34. }
  35. }
  36. };
  37.  
  38. const checkHorizontal = (table: number[][]) => {
  39. for (let r = 0; r < 7; r++) {
  40. for (let c = 0; c < 4; c++) {
  41. if (table[r][c]) {
  42. if (
  43. table[r][c] === table[r][c + 1] &&
  44. table[r][c] === table[r][c + 2] &&
  45. table[r][c] === table[r][c + 3]
  46. ) {
  47. return table[r][c];
  48. }
  49. }
  50. }
  51. }
  52. };
  53.  
  54. const checkDiagonalRight = (table: number[][]) => {
  55. for (let r = 3; r < 7; r++) {
  56. for (let c = 0; c < 5; c++) {
  57. if (table[r][c]) {
  58. if (
  59. table[r][c] === table[r - 1][c + 1] &&
  60. table[r][c] === table[r - 2][c + 2] &&
  61. table[r][c] === table[r - 3][c + 3]
  62. ) {
  63. return table[r][c];
  64. }
  65. }
  66. }
  67. }
  68. };
  69.  
  70. const checkDiagonalLeft = (table: number[][]) => {
  71. for (let r = 3; r < 6; r++) {
  72. for (let c = 3; c < 7; c++) {
  73. if (table[r][c]) {
  74. if (
  75. table[r][c] === table[r - 1][c - 1] &&
  76. table[r][c] === table[r - 2][c - 2] &&
  77. table[r][c] === table[r - 3][c - 3]
  78. ) {
  79. return table[r][c];
  80. }
  81. }
  82. }
  83. }
  84. };
  85.  
  86. const checkDraw = (table: number[][]) => {
  87. for (let r = 0; r < 6; r++) {
  88. for (let c = 0; c < 7; c++) {
  89. if (table[r][c] === 0) {
  90. return 0;
  91. }
  92. }
  93. }
  94.  
  95. return 'draw';
  96. };
  97.  
  98. export const checkWinner = (table: number[][]) => {
  99. return (
  100. checkVertical(table) ||
  101. checkDiagonalRight(table) ||
  102. checkDiagonalLeft(table) ||
  103. checkHorizontal(table) ||
  104. checkDraw(table)
  105. );
  106. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement