canvas塔防小游戏代码
代码语言:html
所属分类:游戏
代码描述:canvas塔防小游戏代码,可随意点击设置攻击位置,还可以选择攻击参数,不能让敌人过右边的红线。
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
<!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8"> <style> html, body, main { width: 100%; height: 100%; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; align-items: center; justify-content: center; } canvas { outline: solid 20px black; background: black; border-radius: 10px; } </style> </head> <body > <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/p5.1.6.0.js"></script> <script > "use strict"; console.clear(); function setup() { canvas = createCanvas(800, 600); colorMode(HSL); restart(); } let canvas; let scene; let mouseVector; function restart() { mouseVector = null; scene = new Scene({ health: 100, gameOver: false, canAddTurretAtMouse: false, canvas }); scene.add(new Turret(createVector(2 * width / 3, height / 2))); loop(); } function spawnEnemy() { scene.add(new Enemy()); } function tryAddTurretAtMouse() { if (!scene.data.gameOver && scene.data.canAddTurretAtMouse) { scene.add(new Turret(mouseVector)); } } function checkForGameOver() { if (scene.data.health <= 0) { scene.data.gameOver = true; } return scene.data.gameOver; } /** * ============== * P5 Lifecycle * ============== */ function keyPressed() { if (key === "r") { restart(); } } function mousePressed() { tryAddTurretAtMouse(); scene.executeListeners("mousepressed"); } function draw() { background(11); mouseVector = createVector(mouseX, mouseY); if (checkForGameOver()) { drawGameOver(); return; } scene.update(); if (frameCount % 30 === 0) { spawnEnemy(); } // Draw hover turret scene.data.canAddTurretAtMouse = false; let hoverTurret; const turretNearMouse = scene.closest(mouseVector, "turret", 100); if (inBounds(mouseVector) && !turretNearMouse) { hoverTurret = new Turret(mouseVector); scene.data.canAddTurretAtMouse = true; } /** * Draw start */ if (hoverTurret) hoverTurret.predraw(); scene.draw(); if (hoverTurret) hoverTurret.draw(); // Draw health bar push(); const healthHeight = map(scene.data.health, 0, 100, 0, height); rectMode(CENTER); noStroke(); fill("red"); rect(width - 4, height / 2, 8, healthHeight); pop(); } function drawGameOver() { scene.draw(); // Draw GAME OVER text push(); const NUM_LABELS = 5; const MAX_OFFSET = 4; const LABEL_OFFSET_X = map(mouseX, 0, width, MAX_OFFSET * 2, MAX_OFFSET); const LABEL_OFFSET_Y = map(mouseY, 0, height, MAX_OFFSET * 2, MAX_OFFSET); translate(-LABEL_OFFSET_X * NUM_LABELS, -LABEL_OFFSET_Y * NUM_LABELS); for (let i = 0; i < NUM_LABELS; i++) { translate(LABEL_OFFSET_X, LABEL_OFFSET_Y); const textColor = map(i, -1, NUM_LABELS - 1, 11, 100, true); noStroke(); fill(textColor); textAlign(CENTER, CENTER); textSize(120); text("GAME OVER", width / 2, height / 2); } pop(); } function drawDebugValue(value, title) { const valueStr = title ? `[${title}: ${value}]` : `[${value}]`; noStroke(); fill("lime"); .........完整代码请登录后点击上方下载按钮下载查看
网友评论0