Guest User

Untitled

a guest
Jun 24th, 2023
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.04 KB | None | 0 0
  1. // 2048 game
  2. const {
  3. SlashCommandBuilder,
  4. ActionRowBuilder,
  5. ButtonBuilder,
  6. ButtonStyle,
  7. EmbedBuilder,
  8. AttachmentBuilder,
  9. } = require("discord.js");
  10. const { createCanvas, loadImage } = require("canvas");
  11. const mysql = require('../../modules/mysql');
  12.  
  13. async function Embed(gameboard, score) {
  14. const embed = new EmbedBuilder()
  15. .setTitle("2048")
  16. .setDescription(
  17. "Welcome to 2048! Use the arrow buttons to play the game. Press the red button to give up."
  18. )
  19. .setImage("attachment://Buffer.png")
  20. .setColor(process.env.color)
  21. .addFields({ name: "Score", value: score.toString() });
  22. return embed;
  23. }
  24.  
  25. const cellColors = {
  26. 0: "#cccccc", // Gray for empty cells
  27. 2: "#eee4da", // Light beige for cells with value 2
  28. 4: "#ede0c8", // Beige for cells with value 4
  29. 8: "#f2b179", // Light orange for cells with value 8
  30. 16: "#f59563", // Orange for cells with value 16
  31. 32: "#f67c5f", // Dark orange for cells with value 32
  32. 64: "#f65e3b", // Reddish orange for cells with value 64
  33. 128: "#edcf72", // Light yellow for cells with value 128
  34. 256: "#edcc61", // Yellow for cells with value 256
  35. 512: "#edc850", // Dark yellow for cells with value 512
  36. 1024: "#edc53f", // Golden yellow for cells with value 1024
  37. };
  38.  
  39. async function generateGameboardImage(gameboard) {
  40. const canvasSize = 360; // Adjust this value to match the size of the gameboard
  41. const cellSize = 80;
  42. const borderWidth = 10; // Adjust this value to control the border size
  43.  
  44. const canvas = createCanvas(canvasSize, canvasSize);
  45. const ctx = canvas.getContext("2d");
  46.  
  47. // Draw the background color for each cell
  48. ctx.font = "20px Arial";
  49. ctx.textAlign = "center";
  50. ctx.textBaseline = "middle";
  51. for (let i = 0; i < gameboard.length; i++) {
  52. for (let j = 0; j < gameboard[i].length; j++) {
  53. const cellValue = gameboard[i][j];
  54. const x = j * (cellSize + borderWidth);
  55. const y = i * (cellSize + borderWidth);
  56.  
  57. // Get the background color based on the cell value
  58. const backgroundColor = cellColors[cellValue] || "#000000"; // Default color for unknown values
  59.  
  60. // Draw the background color rectangle
  61. ctx.fillStyle = backgroundColor;
  62. ctx.fillRect(x, y, cellSize, cellSize);
  63.  
  64. // Draw the cell value
  65. if (cellValue !== 0) {
  66. ctx.fillStyle = "#000000"; // Black text color for non-zero values
  67. } else {
  68. ctx.fillStyle = "#cccccc"; // Light gray text color for zero values
  69. }
  70. ctx.fillText(cellValue.toString(), x + cellSize / 2, y + cellSize / 2);
  71. }
  72. }
  73.  
  74. // Convert the canvas to a buffer
  75. const buffer = canvas.toBuffer("image/png");
  76. const image = new AttachmentBuilder(buffer, { name: "Buffer.png" });
  77. return image;
  78. }
  79.  
  80. function moveLeft(gameboard) {
  81. for (let row of gameboard) {
  82. let nonZeros = row.filter((element) => element !== 0);
  83. let zeros = Array(row.length - nonZeros.length).fill(0);
  84. row.length = 0;
  85. Array.prototype.push.apply(row, nonZeros.concat(zeros));
  86.  
  87. for (let i = 0; i < row.length - 1; i++) {
  88. if (row[i] === row[i + 1]) {
  89. row[i] *= 2;
  90. row[i + 1] = 0;
  91. }
  92. }
  93.  
  94. nonZeros = row.filter((element) => element !== 0);
  95. zeros = Array(row.length - nonZeros.length).fill(0);
  96. row.length = 0;
  97. Array.prototype.push.apply(row, nonZeros.concat(zeros));
  98. }
  99. }
  100.  
  101. function moveRight(gameboard) {
  102. for (let row of gameboard) {
  103. row.reverse();
  104. }
  105. moveLeft(gameboard);
  106. for (let row of gameboard) {
  107. row.reverse();
  108. }
  109. }
  110.  
  111. function moveUp(gameboard) {
  112. transposeGameboard(gameboard);
  113. moveLeft(gameboard);
  114. transposeGameboard(gameboard);
  115. }
  116.  
  117. function moveDown(gameboard) {
  118. transposeGameboard(gameboard);
  119. moveRight(gameboard);
  120. transposeGameboard(gameboard);
  121. }
  122.  
  123. function transposeGameboard(gameboard) {
  124. const transposedGameboard = gameboard[0].map((_, i) =>
  125. gameboard.map((row) => row[i])
  126. );
  127. gameboard.length = 0;
  128. Array.prototype.push.apply(gameboard, transposedGameboard);
  129. }
  130.  
  131. async function placeRandomNumber(gameboard) {
  132. let emptySpots = [];
  133.  
  134. // Find empty spots
  135. for (let i = 0; i < gameboard.length; i++) {
  136. for (let j = 0; j < gameboard[i].length; j++) {
  137. if (gameboard[i][j] === 0) {
  138. emptySpots.push({ row: i, col: j });
  139. }
  140. }
  141. }
  142.  
  143. if (emptySpots.length === 0) {
  144. return true;
  145. } else {
  146. const randomSpot =
  147. emptySpots[Math.floor(Math.random() * emptySpots.length)];
  148. const newValue = Math.random() < 0.9 ? 2 : 4;
  149. gameboard[randomSpot.row][randomSpot.col] = newValue;
  150. return false;
  151. }
  152. }
  153.  
  154. function calculateScore(gameboard) {
  155. let score = 0;
  156. for (let i = 0; i < gameboard.length; i++) {
  157. for (let j = 0; j < gameboard[i].length; j++) {
  158. const cellValue = gameboard[i][j];
  159. score += cellValue * cellValue; // Use a weighted score based on the square of the cell value
  160. }
  161. }
  162. return score;
  163. }
  164.  
  165. module.exports = {
  166. data: new SlashCommandBuilder()
  167. .setName("2048")
  168. .setDescription("Play a game of 2048"),
  169. async execute(interaction, client) {
  170. let gameboard = [
  171. [0, 0, 0, 0],
  172. [0, 0, 0, 0],
  173. [0, 0, 0, 0],
  174. [0, 0, 0, 0],
  175. ];
  176. let score = 0;
  177. placeRandomNumber(gameboard);
  178. placeRandomNumber(gameboard);
  179. const buttons = new ActionRowBuilder().addComponents(
  180. new ButtonBuilder()
  181. .setCustomId("up")
  182. .setLabel("🔼")
  183. .setStyle(ButtonStyle.Primary),
  184. new ButtonBuilder()
  185. .setCustomId("down")
  186. .setLabel("🔽")
  187. .setStyle(ButtonStyle.Primary),
  188. new ButtonBuilder()
  189. .setCustomId("left")
  190. .setLabel("◀️")
  191. .setStyle(ButtonStyle.Primary),
  192. new ButtonBuilder()
  193. .setCustomId("right")
  194. .setLabel("▶️")
  195. .setStyle(ButtonStyle.Primary),
  196. new ButtonBuilder()
  197. .setCustomId("giveUp")
  198. .setLabel("🔴")
  199. .setStyle(ButtonStyle.Danger)
  200. );
  201.  
  202. const embed = await Embed(gameboard, score);
  203. const gameboardImage = await generateGameboardImage(gameboard);
  204. const message = await interaction.reply({
  205. components: [buttons],
  206. embeds: [embed],
  207. files: [gameboardImage],
  208. });
  209. const collector = message.createMessageComponentCollector({});
  210. collector.on("collect", async (i) => {
  211. if (i.member.id == interaction.member.id) {
  212. if (i.customId == "left") {
  213. i.deferUpdate();
  214. moveLeft(gameboard);
  215. let won = await placeRandomNumber(gameboard);
  216. if (won) {
  217. collector.stop();
  218. } else {
  219. score = calculateScore(gameboard);
  220. const embed = await Embed(gameboard, score);
  221. const gameboardImage = await generateGameboardImage(gameboard);
  222. message.edit({ embeds: [embed], files: [gameboardImage] });
  223. }
  224. } else if (i.customId == "right") {
  225. i.deferUpdate();
  226. moveRight(gameboard);
  227. let won = await placeRandomNumber(gameboard);
  228. if (won) {
  229. collector.stop();
  230. } else {
  231. score = calculateScore(gameboard);
  232. const embed = await Embed(gameboard, score);
  233. const gameboardImage = await generateGameboardImage(gameboard);
  234. message.edit({ embeds: [embed], files: [gameboardImage] });
  235. }
  236. } else if (i.customId == "up") {
  237. i.deferUpdate();
  238. moveUp(gameboard);
  239. let won = await placeRandomNumber(gameboard);
  240. if (won) {
  241. collector.stop();
  242. } else {
  243. score = calculateScore(gameboard);
  244. const embed = await Embed(gameboard, score);
  245. const gameboardImage = await generateGameboardImage(gameboard);
  246. message.edit({ embeds: [embed], files: [gameboardImage] });
  247. }
  248. } else if (i.customId == "down") {
  249. i.deferUpdate();
  250. moveDown(gameboard);
  251. let won = await placeRandomNumber(gameboard);
  252. if (won) {
  253. collector.stop();
  254. } else {
  255. score = calculateScore(gameboard);
  256. const embed = await Embed(gameboard, score);
  257. const gameboardImage = await generateGameboardImage(gameboard);
  258. message.edit({ embeds: [embed], files: [gameboardImage] });
  259. }
  260. } else if (i.customId == "giveUp") {
  261. i.deferUpdate();
  262. collector.stop();
  263. }
  264. }
  265. });
  266. collector.on("end", async () => {
  267. const buttons = new ActionRowBuilder().addComponents(
  268. new ButtonBuilder()
  269. .setCustomId("up")
  270. .setLabel("🔼")
  271. .setStyle(ButtonStyle.Primary)
  272. .setDisabled(true),
  273. new ButtonBuilder()
  274. .setCustomId("down")
  275. .setLabel("🔽")
  276. .setStyle(ButtonStyle.Primary)
  277. .setDisabled(true),
  278. new ButtonBuilder()
  279. .setCustomId("left")
  280. .setLabel("◀️")
  281. .setStyle(ButtonStyle.Primary)
  282. .setDisabled(true),
  283. new ButtonBuilder()
  284. .setCustomId("right")
  285. .setLabel("▶️")
  286. .setStyle(ButtonStyle.Primary)
  287. .setDisabled(true),
  288. new ButtonBuilder()
  289. .setCustomId("giveUp")
  290. .setLabel("🔴")
  291. .setStyle(ButtonStyle.Danger)
  292. .setDisabled(true)
  293. );
  294. await message.edit({ components: [buttons] });
  295. let result = await mysql.select({
  296. table: "games",
  297. data: `WHERE id = ${interaction.user.id} LIMIT 1`,
  298. });
  299. if (result[0].numberGame < score) {
  300. if (result.length >= 1) {
  301. mysql.update({
  302. table: "games",
  303. column: ["numberGame"],
  304. data: [score],
  305. additionalData: `WHERE id = ${interaction.user.id}`,
  306. });
  307. } else {
  308. await mysql.insert({
  309. table: "games",
  310. columns: ["id", "2048"],
  311. data: [interaction.user.id, score],
  312. });
  313. }
  314. }
  315. });
  316. },
  317. };
  318.  
Advertisement
Add Comment
Please, Sign In to add comment