本文主要是介绍互动应用开发p5.js——网页小游戏——贪吃蛇,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
贪吃蛇
一、实验内容:
基于课件改进贪吃蛇或者太空大战的小游戏,可以加入新的视觉效果,比如区分蛇头和蛇身;为食物增加特效;分数排行榜;行进改成可以循环等等;
尽可能丰富游戏的玩法。
评分标准:
-
游戏界面及功能 (70分)
-
用户体验 (10分)
-
代码规范(20分)
二、实验说明:
所有实验是通过 Visual Studio Code引入p5.js包编写,所以首先要去p5.js官网下载相关包,或是在联网状态下把html中引入包的代码改成例如<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.js"></script>等。
三、实验代码:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><title>贪吃蛇</title><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.js"></script></head><body><script src="sketch.js"></script>
</body></html>
var s;
var scl = 20;//大小
var food;
var scoreElem;function setup() {scoreElem = createDiv('Score = 0');scoreElem.position(20, 20);scoreElem.id = 'score';scoreElem.style('color', 'white');createCanvas(500, 500);s = new Snake();//创建一个蛇frameRate(10);pickLocation();//放置食物的位置
}
//控制食物流向
function pickLocation() {var cols = floor(width / scl);var rows = floor(height / scl);food = createVector(floor(random(cols)), floor(random(rows)));food.mult(scl);
}function draw() {background(51);//判断食物是否被吃,为食物选择另一个位置if (s.eat(food)) {pickLocation();}s.death();s.update();s.show();fill(255, 0, 100);//食物颜色rect(food.x, food.y, scl, scl);
}function Snake() {this.x = 0;this.y = 0;this.xspeed = 1;this.yspeed = 0;this.total = 0;//蛇方块的数量this.tail = [];this.dir = function (x, y) {this.xspeed = x;this.yspeed = y;}//控制吃食物时的情况this.eat = function (pos) {var d = dist(this.x, this.y, pos.x, pos.y);if (d < 1) {this.total++;return true;} else {return false;}}//控制死亡情况this.death = function () {for (var i = 0; i < this.tail.length; i++) {var pos = this.tail[i];var d = dist(this.x, this.y, pos.x, pos.y);scoreElem.html('Score = '+this.total);if (d < 1) {this.total = 0;this.tail = [];scoreElem.html('Game ended!');}}}this.update = function () {for (var i = 0; i < this.tail.length - 1; i++) {this.tail[i] = this.tail[i + 1];}if (this.total >= 1) {this.tail[this.total - 1] = createVector(this.x, this.y);}this.x = this.x + this.xspeed * scl;this.y = this.y + this.yspeed * scl;this.x = constrain(this.x, 0, width - scl);this.y = constrain(this.y, 0, height - scl);}this.show = function () {fill(255);for (var i = 0; i < this.tail.length; i++) {rect(this.tail[i].x, this.tail[i].y, scl, scl);}rect(this.x, this.y, scl, scl);}
}function keyPressed() {if (keyCode === UP_ARROW) {s.dir(0, -1);} else if (keyCode === DOWN_ARROW) {s.dir(0, 1);} else if (keyCode === RIGHT_ARROW) {s.dir(1, 0);} else if (keyCode === LEFT_ARROW) {s.dir(-1, 0);}
}
四、实验结果:
这篇关于互动应用开发p5.js——网页小游戏——贪吃蛇的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!