2D斜角地圖是一款基于HTML5技術的游戲,它的源代碼為:
let canvas = document.getElementById("canvas"); let ctx = canvas.getContext("2d"); let tileWidth = 64; let tileHeight = 32; let mapWidth = 20; let mapHeight = 10; let map = [ [1,0,1,1,1,1,0,0,0,0,1,1,1,1,1,0,0,1,1,1], [0,0,0,1,1,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1], [0,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,1], [0,0,0,0,0,1,1,0,0,0,1,1,1,0,0,0,1,1,1,0], [0,0,0,0,0,1,1,0,0,0,1,1,1,1,0,0,0,1,1,0], [0,0,0,0,0,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1], [0,0,0,0,0,1,1,0,0,0,1,1,0,0,0,0,1,1,0,0], [0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,1,1,1,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0], [0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0], ]; function drawRhombus(x,y,color) { ctx.beginPath(); ctx.moveTo(x + tileWidth / 2, y); ctx.lineTo(x, y + tileHeight / 2); ctx.lineTo(x + tileWidth / 2, y + tileHeight); ctx.lineTo(x + tileWidth, y + tileHeight / 2); ctx.closePath(); ctx.fillStyle = color; ctx.fill(); } function drawMap() { for (let i = 0; i< mapHeight; i++) { for (let j = 0; j< mapWidth; j++) { let value = map[i][j]; let x = (j - i) * tileWidth / 2 + canvas.width / 2; let y = (i + j) * tileHeight / 2; if (value === 1) { drawRhombus(x,y,"#ccc"); } } } } drawMap();
本游戲使用HTML5的Canvas標簽作為游戲畫布,通過JavaScript語言控制畫布繪制地圖。其中,變量tileWidth和tileHeight表示地圖瓦片的寬高,mapWidth和mapHeight表示地圖的大小,map是一個二維數組,代表地圖中每個位置的狀況。
本游戲采用斜向的瓦片地圖,實現起來比普通的正方形瓦片地圖更加有趣。drawRhombus函數用于繪制一個斜向的菱形瓦片,通過計算每個瓦片的坐標,可以將整個地圖繪制出來。最終調用drawMap函數,實現地圖繪制。
2D斜角地圖游戲簡單而又有趣,適合初學者學習HTML5 Canvas繪圖基礎知識。