fetch('https://example.com/data')
.then(response => {
if (response.ok) {
return response.text();
} else {
throw new Error('Network response was not ok');
}
})
.then(data => console.log(data))
.catch(error => console.error(error));
貪食蛇遊戲
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const CELL_SIZE = 20;
const ROWS = canvas.height / CELL_SIZE;
const COLS = canvas.width / CELL_SIZE;
let gameBoard = [];
for (let i = 0; i < ROWS; i++) {
let row = [];
for (let j = 0; j < COLS; j++) {
row.push(0);
}
gameBoard.push(row);
}
function drawBoard() {
for (let i = 0; i < ROWS; i++) {
for (let j = 0; j < COLS; j++) {
if (gameBoard[i][j] === 0) {
ctx.fillStyle = "white";
} else {
ctx.fillStyle = "green";
}
ctx.fillRect(j * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE);
}
}
}
drawBoard();
let snake = {
body: [{x: 5, y: 5}, {x: 5, y: 6}, {x: 5, y: 7}],
direction: "right"
};
function drawSnake() {
for (let i = 0; i < snake.body.length; i++) {
let snakeCell = document.createElement("div"); // 創建一個div元素
snakeCell.classList.add("snake"); // 給該元素添加"snake" CSS類
snakeCell.style.gridRowStart = snake.body[i].y; // 設置該元素的行起始位置
snakeCell.style.gridColumnStart = snake.body[i].x; // 設置該元素的列起始位置
gameBoard.appendChild(snakeCell); // 在遊戲棋盤上添加該元素
let snakeCell = document.createElement("div"); // 創建一個div元素
snakeCell.classList.add("snake"); // 給該元素添加"snake" CSS類
snakeCell.style.gridRowStart = snake.body[i].y; // 設置該元素的行起始位置
snakeCell.style.gridColumnStart = snake.body[i].x; // 設置該元素的列起始位置
gameBoard.appendChild(snakeCell); // 在遊戲棋盤上添加該元素