Rắn ăn mồi tựa game đã từng hot trên những chiếc điện thoại đen trắng. Nay blog hướng dẫn bạn viết code game này trên nền tảng web. Ngôn ngữ code dùng chính là HTML Canvas để thiết kế game.
Đầu tiên các bạn tạo 1 file HTML và nhập đoạn code sau:
>
<!DOCTYPEhtml><html><head><title></title><style>html, body {height: 100%;margin: 0;}body {background: black;display: flex;align-items: center;justify-content: center;}canvas {border: 1px solid white;}</style></head><body><canvaswidth="400"height="400"id="game"></canvas><script>//Ở đây ta tạo ra bộ khung chứa gamevar canvas = document.getElementById('game');var context = canvas.getContext('2d');var grid = 16;// khởi tạo đối tượng rắn là 1 ô vuôngvar snake = {x: 160, //vị trí của snake theo hướng x,yy: 160,dx: grid, //hướng di chuyển theo phương x hoặc y,ở đây khi start game//snake sẽ di chuyển theo x direction với value = 16dy: 0,cells: [],maxCells: 4};var count = 0;var apple = {x: 320,y: 320};function getRandomInt(min, max) {return Math.floor(Math.random() * (max - min)) + min;}// game loopfunction loop() {//hàm này giống như setTimeout, sẽ gọi lại hàm loop khi loop thực thi xongrequestAnimationFrame(loop);// slow game loop to 15 fps instead of 60 - 60/15 = 4if (++count <4) {return;}count=0;context.clearRect(0,0,canvas.width,canvas.height);snake.x += snake.dx; // mỗi loop rắn sẽ di chuyển thêm 1dx đơn vịsnake.y += snake.dy;// khi snake đụng tường sẽ chạy lại từ edge đối diệnif (snake.x < 0) {snake.x=canvas.width - grid;}else if (snake.x >= canvas.width) {snake.x = 0;}if (snake.y <0) {snake.y=canvas.height - grid;}else if (snake.y >= canvas.height) {snake.y = 0;}// Phương thức unshift sẽ thêm một hoặc nhiều phần tử vào đầu mảngsnake.cells.unshift({x: snake.x, y: snake.y});// thêm 1 ô vuông phía trc thì phải remove 1 cái phía sau để snake move dc.if (snake.cells.length > snake.maxCells) {snake.cells.pop();}// draw applecontext.fillStyle = 'red';context.fillRect(apple.x, apple.y, grid-1, grid-1);// draw snakecontext.fillStyle = 'green';snake.cells.forEach(function(cell, index) {context.fillRect(cell.x, cell.y, grid-1, grid-1);// snake ate appleif (cell.x === apple.x && cell.y === apple.y) {snake.maxCells++;apple.x = getRandomInt(0, 25) * grid;apple.y = getRandomInt(0, 25) * grid;}// check va chạm khi rắn đụng đuôifor (var i = index + 1; i <snake.cells.length; i++) {// va chạm thì reset gameif (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y) {snake.x=160;snake.y=160;snake.cells = [];snake.maxCells=4;snake.dx=grid;snake.dy=0;apple.x=getRandomInt(0, 25) * grid;apple.y=getRandomInt(0, 25) * grid;}}});}//bắt sự kiện bàn phím ấn xuốngdocument.addEventListener('keydown', function(e) {// lọc sự kiện keydown để rắn không di ngược lạiif (e.which === 37 && snake.dx === 0) {snake.dx = -grid;snake.dy=0;}else if (e.which === 38 && snake.dy === 0) {snake.dy = -grid;snake.dx=0;}else if (e.which === 39 && snake.dx === 0) {snake.dx=grid;snake.dy=0;}else if (e.which === 40 && snake.dy === 0) {snake.dy=grid;snake.dx=0;}});requestAnimationFrame(loop);</script></body></html>
Lưu code lại và test!


EmoticonEmoticon