Việc tích hợp trò chơi Snake Game trong website WordPress giúp tăng sự tương tác với người dùng và cải thiện thời gian truy cập trên trang. Bên cạnh đó, bạn có thể tăng cường trải nghiệm khách hàng bằng việc tạo mã giảm giá dựa trên điểm số của người chơi, tích hợp với WooCommerce.

Dưới đây là hướng dẫn chi tiết cách viết game con rắn và tạo mã giảm giá trong WordPress.
1. Cài Đặt và Tích Hợp Trò Chơi Con Rắn Trong WordPress
1.1. Chuẩn Bị
- WordPress: Đảm bảo trang web của bạn đang sử dụng WordPress.
- WooCommerce: Bạn cần cài đặt plugin WooCommerce để quản lý mã giảm giá.
Bạn có thể thích: Hướng dẫn viết game “Đào vàng” trong WordPress
1.2. Bước 1: Tạo Game Con Rắn
Bắt đầu bằng việc thêm mã Javascript cho trò chơi con rắn. Bạn cần viết các lớp Snake
, Food
, PowerUp
, và Obstacle
để điều khiển chuyển động của rắn, tạo thức ăn, tăng cường sức mạnh (power-up) và các chướng ngại vật. Sử dụng p5.js để hỗ trợ vẽ và cập nhật trò chơi.
Cấu Hình Mã Game:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | function snake_game_enqueue_scripts() { ?> <style> #snake-game-container { display: flex; justify-content: center; align-items: center; min-height: 100vh; background-color: #f0f0f0; } /* Các kiểu CSS khác */ </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.js"></script> <script> const GRID_SIZE = 30; const WIDTH = 600; const HEIGHT = 600; let snake, food, powerUp, obstacle, score = 0, level = 1; let snakeSpeed = 15; let gameTime = 60; class Snake { /* Code của lớp Snake */ } class Food { /* Code của lớp Food */ } class PowerUp { /* Code của lớp PowerUp */ } class Obstacle { /* Code của lớp Obstacle */ } function setup() { /* Thiết lập canvas và bắt đầu game */ } function draw() { /* Vẽ và cập nhật game */ } function newGame() { /* Khởi tạo game mới */ } function endGame() { /* Kết thúc game khi hết giờ hoặc rắn chết */ } function generateCoupon() { /* Tạo mã giảm giá khi đạt đủ điểm */ } </script> <?php } add_action('wp_footer', 'snake_game_enqueue_scripts'); |
1.3. Bước 2: Tạo Shortcode Hiển Thị Game
Để trò chơi có thể hiển thị trên trang bất kỳ trong WordPress, bạn có thể tạo một shortcode.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function display_snake_game() { return ' <div id="snake-game-container"> <div class="game-info"> <span id="score">Điểm: 0</span><br> <span id="level">Cấp độ: 1</span><br> <span id="timer">Thời gian: 60 giây</span> </div> <div id="coupon" class="coupon"></div> <div class="game-buttons"> <button id="startButton" onclick="newGame()">Bắt đầu chơi</button> <button id="replayButton" onclick="newGame()">Chơi lại</button> </div> </div> '; } add_shortcode('snake_game', 'display_snake_game'); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function display_snake_game() { return ' <div id="snake-game-container"> <div class="game-info"> <span id="score">Điểm: 0</span><br> <span id="level">Cấp độ: 1</span><br> <span id="timer">Thời gian: 60 giây</span> </div> <div id="coupon" class="coupon"></div> <div class="game-buttons"> <button id="startButton" onclick="newGame()">Bắt đầu chơi</button> <button id="replayButton" onclick="newGame()">Chơi lại</button> </div> </div> '; } add_shortcode('snake_game', 'display_snake_game'); |
Sau khi tạo shortcode, bạn có thể thêm [snake_game]
vào bất kỳ trang nào để hiển thị trò chơi.
2. Tạo Mã Giảm Giá Dựa Trên Điểm Số
2.1. Bước 3: Tích Hợp WooCommerce Để Tạo Mã Giảm Giá
Sau khi người chơi đạt được điểm số nhất định (ví dụ: từ 10.000 điểm trở lên), trò chơi sẽ tự động tạo một mã giảm giá. Để thực hiện, chúng ta cần sử dụng REST API trong WordPress để xử lý và tạo mã giảm giá WooCommerce.
Cấu Hình Endpoint REST API:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | function generate_coupon_code_rest($data) { $score = intval($data['score']); $discount_amount = min($score, 100000); $coupon_code = 'DISCOUNT-' . strtoupper(wp_generate_password(8, false)); // Tạo mã giảm giá trong WooCommerce $coupon = array( 'post_title' => $coupon_code, 'post_status' => 'publish', 'post_type' => 'shop_coupon' ); $new_coupon_id = wp_insert_post($coupon); update_post_meta($new_coupon_id, 'discount_type', 'fixed_cart'); update_post_meta($new_coupon_id, 'coupon_amount', $discount_amount); update_post_meta($new_coupon_id, 'usage_limit', '1'); update_post_meta($new_coupon_id, 'expiry_date', date('Y-m-d', strtotime('+7 days'))); return array('coupon_code' => $coupon_code); } add_action('rest_api_init', function () { register_rest_route('game', '/coupon', array( 'methods' => 'POST', 'callback' => 'generate_coupon_code_rest', 'args' => array( 'score' => array( 'required' => true, 'validate_callback' => function($param) { return is_numeric($param); } ), ), )); }); |
2.2. Bước 4: Tạo Mã Giảm Giá Khi Người Chơi Đạt Điểm
Trong trò chơi, khi người chơi đạt điểm số đủ để tạo mã giảm giá, bạn có thể gọi hàm generateCoupon() để gửi yêu cầu tạo mã giảm giá qua API.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | function generateCoupon() { fetch('/wp-json/game/coupon', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ score: score }), }) .then(response => response.json()) .then(data => { if (data.coupon_code) { document.getElementById('coupon').innerHTML = 'Mã giảm giá của bạn là: ' + data.coupon_code; } }) .catch((error) => { console.error('Error:', error); }); } |
Với hướng dẫn chi tiết trên, bạn có thể dễ dàng tích hợp trò chơi con rắn vào trang WordPress của mình, đồng thời tạo mã giảm giá dựa trên điểm số của người chơi để tăng sự tương tác và trải nghiệm người dùng. Việc này không chỉ giúp website của bạn thêm phần thú vị mà còn thúc đẩy việc mua hàng với các mã giảm giá hấp dẫn. Dưới đây là code hoàn chỉnh bạn chỉ cần bỏ vào funtion.php là được nhé
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 | // Thêm các hằng số của trò chơi (config.js) và tạo mã giảm giá function snake_game_enqueue_scripts() { ?> <style> #snake-game-container { display: flex; justify-content: center; align-items: center; flex-direction: column; min-height: 100vh; background-color: #f0f0f0; } #snakeGame { background-color: #111; border: 3px solid #4CAF50; box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.5); } .game-info { font-size: 18px; color: #4CAF50; margin-bottom: 20px; } .game-buttons { margin-top: 20px; } .game-buttons button { padding: 10px 20px; margin: 5px; background-color: #4CAF50; color: white; border: none; cursor: pointer; font-size: 16px; border-radius: 5px; } .game-buttons button:hover { background-color: #45a049; } .game-buttons #replayButton { display: none; } .game-buttons #startButton { display: block; } .coupon { color: #FF5722; font-size: 24px; font-weight: bold; margin-top: 20px; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.js"></script> <script> const GRID_SIZE = 30; const WIDTH = 600; const HEIGHT = 600; let snake; let food; let powerUp; let obstacle; let score = 0; let level = 1; let gameStarted = false; let couponGenerated = false; let snakeSpeed = 15; // Tốc độ ban đầu của rắn let gameTime = 60; // Thời gian chơi let timerInterval; // Bộ đếm thời gian let isSpeedBoosted = false; // Để theo dõi tình trạng tăng tốc của rắn // Class Snake (snake.js) class Snake { constructor() { this.head = createVector(0, 0); this.vel = createVector(1, 0); this.body = []; this.length = 1; this.isDead = false; } update() { this.body.push(createVector(this.head.x, this.head.y)); this.head.x += this.vel.x * GRID_SIZE; this.head.y += this.vel.y * GRID_SIZE; // Keep snake on screen by wrapping around this.head.x = (this.head.x + WIDTH) % WIDTH; this.head.y = (this.head.y + HEIGHT) % HEIGHT; // Remove tail when the snake has more segments than its length if (this.body.length > this.length) { this.body.shift(); } // Check collision with itself for (let vector of this.body) { if (vector.x === this.head.x && vector.y === this.head.y) { this.isDead = true; } } } show() { noStroke(); fill(255); rect(this.head.x, this.head.y, GRID_SIZE, GRID_SIZE); fill(155); for (let vector of this.body) { rect(vector.x, vector.y, GRID_SIZE, GRID_SIZE); } } } // Class Food (food.js) class Food { constructor() { this.newFood(); } newFood() { this.x = Math.floor(random(width)); this.y = Math.floor(random(height)); this.x = Math.floor(this.x / GRID_SIZE) * GRID_SIZE; this.y = Math.floor(this.y / GRID_SIZE) * GRID_SIZE; this.points = Math.floor(random(1030, 23001)); // Random từ 100 đến 2000 điểm } show() { fill(255, 40, 0); rect(this.x, this.y, GRID_SIZE, GRID_SIZE); } } // Class PowerUp (power-up.js) class PowerUp { constructor() { this.isActive = false; this.newPowerUp(); } newPowerUp() { this.x = Math.floor(random(width)); this.y = Math.floor(random(height)); this.x = Math.floor(this.x / GRID_SIZE) * GRID_SIZE; this.y = Math.floor(this.y / GRID_SIZE) * GRID_SIZE; // Loại power-up có thể là tăng tốc hoặc giảm tốc this.type = random(['speed_30', 'speed_40', 'slow_5', 'slow_10']); this.isActive = true; } applyEffect() { this.isActive = false; if (this.type === 'speed_30') { snakeSpeed = Math.max(5, snakeSpeed - Math.floor(snakeSpeed * 0.3)); // Tăng tốc 30% } else if (this.type === 'speed_40') { snakeSpeed = Math.max(5, snakeSpeed - Math.floor(snakeSpeed * 0.4)); // Tăng tốc 40% } else if (this.type === 'slow_5') { snakeSpeed += Math.floor(snakeSpeed * 0.05); // Giảm tốc 5% } else if (this.type === 'slow_10') { snakeSpeed += Math.floor(snakeSpeed * 0.1); // Giảm tốc 10% } frameRate(snakeSpeed); // Cập nhật tốc độ mới // Đặt lại tốc độ sau 5 giây setTimeout(() => { snakeSpeed = 15; frameRate(snakeSpeed); }, 5000); } show() { if (this.isActive) { fill(this.type.includes('speed') ? 'green' : 'blue'); // Power-up tăng tốc màu xanh lá, giảm tốc màu xanh dương rect(this.x, this.y, GRID_SIZE, GRID_SIZE); } } } // Class Obstacle (chướng ngại vật) class Obstacle { constructor() { this.obstacles = []; // Tạo ra 5 chướng ngại vật trên màn hình for (let i = 0; i < 5; i++) { this.obstacles.push({ x: Math.floor(random(1, width / GRID_SIZE)) * GRID_SIZE, y: Math.floor(random(1, height / GRID_SIZE)) * GRID_SIZE }); } } show() { fill(128, 128, 128); // Màu xám cho chướng ngại vật for (let obstacle of this.obstacles) { rect(obstacle.x, obstacle.y, GRID_SIZE, GRID_SIZE); } } isCollision(x, y) { for (let obstacle of this.obstacles) { if (obstacle.x === x && obstacle.y === y) { return true; // Có va chạm với chướng ngại vật } } return false; } } function setup() { let canvas = createCanvas(WIDTH, HEIGHT); canvas.parent('snake-game-container'); frameRate(snakeSpeed); // Tốc độ khung hình obstacle = new Obstacle(); // Khởi tạo chướng ngại vật powerUp = new PowerUp(); // Khởi tạo power-up } function newGame() { snake = new Snake(); food = new Food(); score = 0; level = 1; couponGenerated = false; snakeSpeed = 15; // Đặt lại tốc độ ban đầu gameTime = 60; // Khởi tạo lại thời gian 60 giây gameStarted = true; document.getElementById('startButton').style.display = 'none'; document.getElementById('replayButton').style.display = 'none'; document.getElementById('coupon').innerHTML = ''; startTimer(); // Bắt đầu đếm thời gian } function startTimer() { clearInterval(timerInterval); // Đảm bảo không có bộ đếm thời gian cũ timerInterval = setInterval(() => { gameTime--; document.getElementById('timer').innerText = 'Thời gian: ' + gameTime + ' giây'; if (gameTime <= 0) { clearInterval(timerInterval); // Dừng đếm khi hết giờ endGame(); // Gọi hàm kết thúc game } }, 1000); // Cập nhật mỗi giây } function draw() { if (gameStarted) { background(0); obstacle.show(); // Hiển thị chướng ngại vật if (!snake.isDead) { drawSnake(); } else { endGame(); // Kết thúc trò chơi khi rắn chết } // Hiển thị power-up nếu có powerUp.show(); // Kiểm tra va chạm với power-up if (powerUp.isActive && snake.head.x === powerUp.x && snake.head.y === powerUp.y) { powerUp.applyEffect(); // Áp dụng hiệu ứng của power-up powerUp.newPowerUp(); // Tạo power-up mới sau khi ăn } } } function drawSnake() { if (frameCount % snakeSpeed == 0) { snake.update(); } snake.show(); food.show(); // Kiểm tra va chạm với thức ăn if (snake.head.x === food.x && snake.head.y === food.y) { eatFood(); } // Kiểm tra va chạm với chướng ngại vật if (obstacle.isCollision(snake.head.x, snake.head.y)) { snake.isDead = true; } // Hiển thị điểm số và cấp độ document.getElementById('score').innerText = 'Điểm: ' + score; document.getElementById('level').innerText = 'Cấp độ: ' + level; // Tăng cấp độ khi đạt số điểm nhất định và tăng tốc độ rắn if (score >= level * 2000) { level++; snakeSpeed = Math.max(5, snakeSpeed - 2); // Tăng tốc độ rắn frameRate(snakeSpeed); // Cập nhật tốc độ rắn } // Kiểm tra khi rắn chết if (snake.isDead) { endGame(); } } function eatFood() { snake.length++; score += food.points; // Cộng thêm điểm từ thức ăn food.newFood(); // Tạo thức ăn mới } // Kết thúc trò chơi (khi hết giờ hoặc rắn chết) function endGame() { clearInterval(timerInterval); // Dừng đếm thời gian gameStarted = false; document.getElementById('replayButton').style.display = 'block'; // Tạo mã giảm giá nếu đạt từ 10.000 điểm trở lên if (score >= 10000 && !couponGenerated) { generateCoupon(); couponGenerated = true; } } // Điều khiển bằng bàn phím function keyPressed() { if (keyCode === UP_ARROW && snake.vel.y !== 1) { snake.vel.y = -1; snake.vel.x = 0; } else if (keyCode === DOWN_ARROW && snake.vel.y !== -1) { snake.vel.y = 1; snake.vel.x = 0; } else if (keyCode === LEFT_ARROW && snake.vel.x !== 1) { snake.vel.y = 0; snake.vel.x = -1; } else if (keyCode === RIGHT_ARROW && snake.vel.x !== -1) { snake.vel.y = 0; snake.vel.x = 1; } } // Tạo mã giảm giá khi đạt đủ điểm function generateCoupon() { fetch('/wp-json/game/coupon', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ score: score }), }) .then(response => response.json()) .then(data => { if (data.coupon_code) { document.getElementById('coupon').innerHTML = 'Mã giảm giá của bạn là: ' + data.coupon_code; } }) .catch((error) => { console.error('Error:', error); }); } </script> <?php } add_action('wp_footer', 'snake_game_enqueue_scripts'); // Tạo shortcode để hiển thị game trên bất kỳ trang nào function display_snake_game() { return ' <div id="snake-game-container"> <div class="game-info"> <span id="score">Điểm: 0</span><br> <span id="level">Cấp độ: 1</span><br> <span id="timer">Thời gian: 60 giây</span> </div> <div id="coupon" class="coupon"></div> <div class="game-buttons"> <button id="startButton" onclick="newGame()">Bắt đầu chơi</button> <button id="replayButton" onclick="newGame()">Chơi lại</button> </div> </div> '; } add_shortcode('snake_game', 'display_snake_game'); // Hàm tạo mã giảm giá dựa trên điểm số function generate_coupon_code_rest($data) { $score = intval($data['score']); // Lấy điểm số từ dữ liệu gửi lên $discount_amount = min($score, 100000); // Số tiền giảm giá tương ứng với số điểm (tối đa là 100.000) $coupon_code = 'DISCOUNT-' . strtoupper(wp_generate_password(8, false)); // Tạo mã giảm giá ngẫu nhiên // Tạo mã giảm giá trong WooCommerce $coupon = array( 'post_title' => $coupon_code, 'post_content' => '', 'post_status' => 'publish', 'post_author' => 1, 'post_type' => 'shop_coupon' ); $new_coupon_id = wp_insert_post($coupon); // Thêm thông tin cho mã giảm giá update_post_meta($new_coupon_id, 'discount_type', 'fixed_cart'); // Kiểu giảm giá là cố định theo giỏ hàng update_post_meta($new_coupon_id, 'coupon_amount', $discount_amount); // Số tiền giảm giá tương đương với điểm số update_post_meta($new_coupon_id, 'individual_use', 'yes'); // Chỉ sử dụng riêng lẻ, không kết hợp với mã khác update_post_meta($new_coupon_id, 'usage_limit', '1'); // Mã chỉ sử dụng được 1 lần update_post_meta($new_coupon_id, 'expiry_date', date('Y-m-d', strtotime('+7 days'))); // Hạn sử dụng mã là 7 ngày return array('coupon_code' => $coupon_code); // Trả về mã giảm giá } // Tạo endpoint REST API để trả về mã giảm giá dựa trên điểm số add_action('rest_api_init', function () { register_rest_route('game', '/coupon', array( 'methods' => 'POST', 'callback' => 'generate_coupon_code_rest', 'args' => array( 'score' => array( 'required' => true, 'validate_callback' => function($param, $request, $key) { return is_numeric($param); // Xác nhận điểm số là một số hợp lệ } ), ), )); }); |
Nếu bạn thấy bài viết hữu ích, có thể ủng hộ ad qua MB BANK 0766734539 LE TRUNG HOANG nhé, cảm ơn các bạn độc giả nhiều. Hãy theo dõi để nhận thêm nhiều bài viết hay từ MuaThemeWPgiare nhé.
- Hướng Dẫn Tự Code Tạo Chức Năng “Vòng Quay May Mắn” WordPress
- Cách Thêm Cột Hiển Thị ID Danh Mục Sản Phẩm Trong WooCommerce – Hướng Dẫn Chi Tiết
- Giới Thiệu Về Mua Theme WordPress Giá Rẻ Và Plugin Flash Sale
- Có nên mua giao diện có sẵn hay không? Top 10 chỗ mua uy tín?
- Hướng dẫn chi tiết cách triển khai hệ thống tích điểm và đổi quà trên WordPress