- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我在这篇文章的底部写了小蛇游戏。
现在我想通过 block 之间的一点点(黑色)空间将每个蛇体 block 分开,以便绿色 block 彼此明显分开。
类似于[s] [s] [s] [s]
。 [s]
现在是一个绿色的蛇身 block ,但我不知道如何在它们之间添加 空间。
我对 JS 很满意,但 CSS 的这些细节对我来说仍然是个谜。我什至不确定我是否首先使用正确的方法来“绘制”蛇。
let _game;
var gameLoopHandle;
var pollingHandle;
let Snake = function(forGame,startingDirection, startingBody){
this.going = startingDirection || "RIGHT";
this.go = function(direction){
let snakeHead = {x:this.getHead().x,y:this.getHead().y};
switch(direction.toLowerCase()){
case "left":
snakeHead.y--;
this.going = "LEFT";
break;
case "right":
snakeHead.y++;
this.going = "RIGHT";
break;
case "up":
snakeHead.x--;
this.going = "UP";
break;
case "down":
snakeHead.x++;
this.going = "DOWN";
break;
}
let newBlock =
generateBlock(snakeHead.x,snakeHead.y,
this.gameInstance.boardSizeX,this.gameInstance.boardSizeY);
if (this.posIsApple(newBlock)) {
this.gameInstance.score++;
this.gameInstance.genApple = true;
} else {
this.removeBockTailFromSnake();
}
if (this.posIsTail(newBlock)){
this.gameInstance.ended = true;
}
this.addBlockHeadToSnake(newBlock);
};
this.body = startingBody || [
{x:9,y:8},
{x:9,y:9},
{x:9,y:10},
{x:9,y:11}
];
this.gameInstance = forGame;
this.getHead = function(){
return this.body[this.body.length-1];
};
this.posIsTail = function(pos){
for (let i = 0; i<this.body.length;i++){
if (pos.x === this.body[i].x && pos.y === this.body[i].y) {
return true;
}
}
return false;
};
this.posIsApple = function(pos){
return pos.x === this.gameInstance.apple.x && pos.y === this.gameInstance.apple.y;
};
this.addBlockHeadToSnake = function(block){
this.body.push(block);
}
this.removeBockTailFromSnake = function(){
this.body.shift();
}
}
let serverListener = function(keyEvents){
console.log(keyEvents);
for (let i = 0; i<keyEvents.length;i++) {
var event = new Event('keydown');
event.key="Arrow" + capitalizeFirstLetter(keyEvents[i].toLowerCase());
document.dispatchEvent(event);
}
}
let SnakeGame = function(){
this.board = [];
this.snake = {};
this.apple = {};
this.score = 0;
this.speed = 500;
this.ended = false;
this.genApple = true;
this.boardSizeX = 20;
this.boardSizeY = 20;
this.manager = {};
}
SnakeGame.prototype.init = function(options){
options = options || {};
this.boardSizeX = options.boardSizeX || 20;
this.boardSizeY = options.boardSizeY || 20;
this.snake = options.snake || new Snake(this);
}
SnakeGame.prototype.setSnake = function(){
// sets snake to provided params
}
SnakeGame.prototype.generateBoard = function(){
this.board = [];
for (let i=0;i<this.boardSizeX;i++){
let boardRow=[];
for (let j = 0; j < this.boardSizeY; j++) {
let havePixel = false;
for (let k = 0; k<this.snake.body.length;k++){
if (this.snake.body[k].x === i && this.snake.body[k].y === j ){
havePixel = true;
}
}
if (havePixel) {
boardRow.push(1);
} else {
boardRow.push(0);
}
}
this.board.push(boardRow);
}
}
SnakeGame.prototype.setSpeed = function(speed){
this.speed = speed;
}
SnakeGame.prototype.setScore = function(score){
this.score = score;
}
let generateBlock = function(x,y,limitX,limitY){
let block = {};
if (x===limitX) {
block.x = 0;
} else if (x == -1) {
block.x = limitX-1;
} else {
block.x = x;
}
if (y===limitY) {
block.y = 0;
} else if (y == -1) {
block.y = limitY-1;
} else {
block.y = y;
}
return block;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
let genericDiv = function(color){
let returnDiv = document.createElement("div");
returnDiv.style.height = "10px";
returnDiv.style.width = "10px";
returnDiv.style.background = color;
return returnDiv;
}
let snakeDiv = function(){
return genericDiv("lime");
}
let emptyDiv = function(){
return genericDiv("black");
}
let appleDiv = function(){
return genericDiv("red");
}
function updateDOM(game) {
var el = document.getElementById("gameboard");
el.innerHTML = "";
el.style.position = "relative";
var scoreEl = document.getElementById("score");
scoreEl.innerText = game.score;
if (game.genApple) {
generateAppleNoCollision(game);
}
for (let i =0;i<game.board.length;i++){
let snakeRowDiv = document.createElement("div");
//snakeRowDiv.style.position = "absolute";
for (let j=0;j<game.board[i].length;j++){
let whichDiv = null;
if (game.board[i][j]){
whichDiv = snakeDiv();
} else if (i==game.apple.x && j == game.apple.y){
whichDiv = appleDiv();
}
if (whichDiv == null){
whichDiv = emptyDiv();
}
whichDiv.style.position = "absolute";
whichDiv.style.left = j * (parseInt(whichDiv.style.width)) + "px";
whichDiv.style.top = (i * (parseInt(whichDiv.style.height)) + 100) + "px";
snakeRowDiv.appendChild(whichDiv);
}
el.appendChild(snakeRowDiv);
}
}
function generateDomListener(game){
return function(event){
switch (event.key) {
case "ArrowUp":
if (game.snake.going != "DOWN"){
game.snake.going = "UP";
}
break;
case "ArrowDown":
if (game.snake.going != "UP"){
game.snake.going = "DOWN";
}
break;
case "ArrowLeft":
if (game.snake.going != "RIGHT") {
game.snake.going = "LEFT";
}
break;
case "ArrowRight":
if (game.snake.going != "LEFT") {
game.snake.going = "RIGHT";
}
break;
}
}
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function decreaseDifficulty(game){
if (game.speed <= 900) {
game.speed += 50;
}
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function restart(game){
game.ended = false;
game.genApple = true;
game.score = 0;
game.speed = 500;
game.apple = {x:null,y:null}
game.snake.body = [
{x:9,y:8},
{x:9,y:9},
{x:9,y:10},
{x:9,y:11},
]
game.snake.going = "RIGHT";
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function generateAppleNoCollision(game){
while(true){
game.apple.x = getRandomInt(0,game.board.length-1);
game.apple.y = getRandomInt(0,game.board.length-1);
let hasCollision = false;
for (let i = 0; i<game.snake.body.length;i++){
if(game.apple.x === game.snake.body[i].x &&
game.apple.y === game.snake.body[i].y) {
hasCollision = true;
}
}
if (!hasCollision) {
console.log("no collision, continuing with this apple")
break;
}
console.error("found collision, searching once more")
}
game.genApple = false;
}
function increaseDifficulty(game){
if (game.speed >= 100) {
game.speed -= 50;
}
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function gameLoop(game){
return function(){
if (!game.ended) {
game.snake.go(game.snake.going);
game.generateBoard();
updateDOM(game);
} else {
clearInterval(gameLoopHandle);
alert ("GAME OVER");
}
}
}
function polling(game){
return function(){
var scriptsDiv = document.getElementById("scripts");
var script = document.createElement('script');
script.src="http://172.168.1.22/snake_relay/?command=get&callbackname=serverListener";
if (game.scripts) {
if (game.scripts.length == 100){
let msg = "too many scripts, clearing the div";
scriptsDiv.innerHTML = ""
}
game.scripts.push(script);
} else {
game.scripts = [script];
}
scriptsDiv.appendChild(script);
}
}
document.addEventListener("DOMContentLoaded", function(event) {
var game = new SnakeGame();
_game =game;
game.init();
game.generateBoard()
updateDOM(game);
document.addEventListener("keydown", generateDomListener(game));
//pollingHandle = setInterval(polling(game), 100);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
})
<div id="gameboard"></div>
<div>
<h1>Score: <span id="score">0</span></h1>
<button onclick="increaseDifficulty(_game)">Increase difficulty</button>
<button onclick="decreaseDifficulty(_game)">Decrease difficulty</button>
<button onclick="restart(_game)">Restart</button>
</div>
<div id="scripts"></div>
最佳答案
您可以在 genericDiv
中设置边框,并将必要的值传递给 snakeDiv
。
let snakeDiv = function(){
return genericDiv("lime", "1px solid #000000");
}
您可以将边框大小设置为您需要的任何大小。
let _game;
var gameLoopHandle;
var pollingHandle;
let Snake = function(forGame,startingDirection, startingBody){
this.going = startingDirection || "RIGHT";
this.go = function(direction){
let snakeHead = {x:this.getHead().x,y:this.getHead().y};
switch(direction.toLowerCase()){
case "left":
snakeHead.y--;
this.going = "LEFT";
break;
case "right":
snakeHead.y++;
this.going = "RIGHT";
break;
case "up":
snakeHead.x--;
this.going = "UP";
break;
case "down":
snakeHead.x++;
this.going = "DOWN";
break;
}
let newBlock =
generateBlock(snakeHead.x,snakeHead.y,
this.gameInstance.boardSizeX,this.gameInstance.boardSizeY);
if (this.posIsApple(newBlock)) {
this.gameInstance.score++;
this.gameInstance.genApple = true;
} else {
this.removeBockTailFromSnake();
}
if (this.posIsTail(newBlock)){
this.gameInstance.ended = true;
}
this.addBlockHeadToSnake(newBlock);
};
this.body = startingBody || [
{x:9,y:8},
{x:9,y:9},
{x:9,y:10},
{x:9,y:11}
];
this.gameInstance = forGame;
this.getHead = function(){
return this.body[this.body.length-1];
};
this.posIsTail = function(pos){
for (let i = 0; i<this.body.length;i++){
if (pos.x === this.body[i].x && pos.y === this.body[i].y) {
return true;
}
}
return false;
};
this.posIsApple = function(pos){
return pos.x === this.gameInstance.apple.x && pos.y === this.gameInstance.apple.y;
};
this.addBlockHeadToSnake = function(block){
this.body.push(block);
}
this.removeBockTailFromSnake = function(){
this.body.shift();
}
}
let serverListener = function(keyEvents){
console.log(keyEvents);
for (let i = 0; i<keyEvents.length;i++) {
var event = new Event('keydown');
event.key="Arrow" + capitalizeFirstLetter(keyEvents[i].toLowerCase());
document.dispatchEvent(event);
}
}
let SnakeGame = function(){
this.board = [];
this.snake = {};
this.apple = {};
this.score = 0;
this.speed = 500;
this.ended = false;
this.genApple = true;
this.boardSizeX = 20;
this.boardSizeY = 20;
this.manager = {};
}
SnakeGame.prototype.init = function(options){
options = options || {};
this.boardSizeX = options.boardSizeX || 20;
this.boardSizeY = options.boardSizeY || 20;
this.snake = options.snake || new Snake(this);
}
SnakeGame.prototype.setSnake = function(){
// sets snake to provided params
}
SnakeGame.prototype.generateBoard = function(){
this.board = [];
for (let i=0;i<this.boardSizeX;i++){
let boardRow=[];
for (let j = 0; j < this.boardSizeY; j++) {
let havePixel = false;
for (let k = 0; k<this.snake.body.length;k++){
if (this.snake.body[k].x === i && this.snake.body[k].y === j ){
havePixel = true;
}
}
if (havePixel) {
boardRow.push(1);
} else {
boardRow.push(0);
}
}
this.board.push(boardRow);
}
}
SnakeGame.prototype.setSpeed = function(speed){
this.speed = speed;
}
SnakeGame.prototype.setScore = function(score){
this.score = score;
}
let generateBlock = function(x,y,limitX,limitY){
let block = {};
if (x===limitX) {
block.x = 0;
} else if (x == -1) {
block.x = limitX-1;
} else {
block.x = x;
}
if (y===limitY) {
block.y = 0;
} else if (y == -1) {
block.y = limitY-1;
} else {
block.y = y;
}
return block;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
let genericDiv = function(color, border){
let returnDiv = document.createElement("div");
returnDiv.style.height = "10px";
returnDiv.style.width = "10px";
returnDiv.style.background = color;
returnDiv.style.border = border;
return returnDiv;
}
let snakeDiv = function(){
return genericDiv("lime", "1px solid #000000");
}
let emptyDiv = function(){
return genericDiv("black");
}
let appleDiv = function(){
return genericDiv("red");
}
function updateDOM(game) {
var el = document.getElementById("gameboard");
el.innerHTML = "";
el.style.position = "relative";
var scoreEl = document.getElementById("score");
scoreEl.innerText = game.score;
if (game.genApple) {
generateAppleNoCollision(game);
}
for (let i =0;i<game.board.length;i++){
let snakeRowDiv = document.createElement("div");
//snakeRowDiv.style.position = "absolute";
for (let j=0;j<game.board[i].length;j++){
let whichDiv = null;
if (game.board[i][j]){
whichDiv = snakeDiv();
} else if (i==game.apple.x && j == game.apple.y){
whichDiv = appleDiv();
}
if (whichDiv == null){
whichDiv = emptyDiv();
}
whichDiv.style.position = "absolute";
whichDiv.style.left = j * (parseInt(whichDiv.style.width)) + "px";
whichDiv.style.top = (i * (parseInt(whichDiv.style.height)) + 100) + "px";
snakeRowDiv.appendChild(whichDiv);
}
el.appendChild(snakeRowDiv);
}
}
function generateDomListener(game){
return function(event){
switch (event.key) {
case "ArrowUp":
if (game.snake.going != "DOWN"){
game.snake.going = "UP";
}
break;
case "ArrowDown":
if (game.snake.going != "UP"){
game.snake.going = "DOWN";
}
break;
case "ArrowLeft":
if (game.snake.going != "RIGHT") {
game.snake.going = "LEFT";
}
break;
case "ArrowRight":
if (game.snake.going != "LEFT") {
game.snake.going = "RIGHT";
}
break;
}
}
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function decreaseDifficulty(game){
if (game.speed <= 900) {
game.speed += 50;
}
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function restart(game){
game.ended = false;
game.genApple = true;
game.score = 0;
game.speed = 500;
game.apple = {x:null,y:null}
game.snake.body = [
{x:9,y:8},
{x:9,y:9},
{x:9,y:10},
{x:9,y:11},
]
game.snake.going = "RIGHT";
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function generateAppleNoCollision(game){
while(true){
game.apple.x = getRandomInt(0,game.board.length-1);
game.apple.y = getRandomInt(0,game.board.length-1);
let hasCollision = false;
for (let i = 0; i<game.snake.body.length;i++){
if(game.apple.x === game.snake.body[i].x &&
game.apple.y === game.snake.body[i].y) {
hasCollision = true;
}
}
if (!hasCollision) {
console.log("no collision, continuing with this apple")
break;
}
console.error("found collision, searching once more")
}
game.genApple = false;
}
function increaseDifficulty(game){
if (game.speed >= 100) {
game.speed -= 50;
}
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function gameLoop(game){
return function(){
if (!game.ended) {
game.snake.go(game.snake.going);
game.generateBoard();
updateDOM(game);
} else {
clearInterval(gameLoopHandle);
alert ("GAME OVER");
}
}
}
function polling(game){
return function(){
var scriptsDiv = document.getElementById("scripts");
var script = document.createElement('script');
script.src="http://172.168.1.22/snake_relay/?command=get&callbackname=serverListener";
if (game.scripts) {
if (game.scripts.length == 100){
let msg = "too many scripts, clearing the div";
scriptsDiv.innerHTML = ""
}
game.scripts.push(script);
} else {
game.scripts = [script];
}
scriptsDiv.appendChild(script);
}
}
document.addEventListener("DOMContentLoaded", function(event) {
var game = new SnakeGame();
_game =game;
game.init();
game.generateBoard()
updateDOM(game);
document.addEventListener("keydown", generateDomListener(game));
//pollingHandle = setInterval(polling(game), 100);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
})
<div id="gameboard"></div>
<div>
<h1>Score: <span id="score">0</span></h1>
<button onclick="increaseDifficulty(_game)">Increase difficulty</button>
<button onclick="decreaseDifficulty(_game)">Decrease difficulty</button>
<button onclick="restart(_game)">Restart</button>
</div>
<div id="scripts"></div>
关于javascript - 无法弄清楚如何在 block 之间添加一点空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50286441/
我通过 spring ioc 编写了一些 Rest 应用程序。但我无法解决这个问题。这是我的异常(exception): org.springframework.beans.factory.BeanC
我对 TestNG、Spring 框架等完全陌生,我正在尝试使用注释 @Value通过 @Configuration 访问配置文件注释。 我在这里想要实现的目标是让控制台从配置文件中写出“hi”,通过
为此工作了几个小时。我完全被难住了。 这是 CS113 的实验室。 如果用户在程序(二进制计算器)结束时选择继续,我们需要使用 goto 语句来到达程序的顶部。 但是,我们还需要释放所有分配的内存。
我正在尝试使用 ffmpeg 库构建一个小的 C 程序。但是我什至无法使用 avformat_open_input() 打开音频文件设置检查错误代码的函数后,我得到以下输出: Error code:
使用 Spring Initializer 创建一个简单的 Spring boot。我只在可用选项下选择 DevTools。 创建项目后,无需对其进行任何更改,即可正常运行程序。 现在,当我尝试在项目
所以我只是在 Mac OS X 中通过 brew 安装了 qt。但是它无法链接它。当我尝试运行 brew link qt 或 brew link --overwrite qt 我得到以下信息: ton
我在提交和 pull 时遇到了问题:在提交的 IDE 中,我看到: warning not all local changes may be shown due to an error: unable
我跑 man gcc | grep "-L" 我明白了 Usage: grep [OPTION]... PATTERN [FILE]... Try `grep --help' for more inf
我有一段代码,旨在接收任何 URL 并将其从网络上撕下来。到目前为止,它运行良好,直到有人给了它这个 URL: http://www.aspensurgical.com/static/images/a
在过去的 5 个小时里,我一直在尝试在我的服务器上设置 WireGuard,但在完成所有设置后,我无法 ping IP 或解析域。 下面是服务器配置 [Interface] Address = 10.
我正在尝试在 GitLab 中 fork 我的一个私有(private)项目,但是当我按下 fork 按钮时,我会收到以下信息: No available namespaces to fork the
我这里遇到了一些问题。我是 node.js 和 Rest API 的新手,但我正在尝试自学。我制作了 REST API,使用 MongoDB 与我的数据库进行通信,我使用 Postman 来测试我的路
下面的代码在控制台中给出以下消息: Uncaught DOMException: Failed to execute 'appendChild' on 'Node': The new child el
我正在尝试调用一个新端点来显示数据,我意识到在上一组有效的数据中,它在数据周围用一对额外的“[]”括号进行控制台,我认为这就是问题是,而新端点不会以我使用数据的方式产生它! 这是 NgFor 失败的原
我正在尝试将我的 Symfony2 应用程序部署到我的 Azure Web 应用程序,但遇到了一些麻烦。 推送到远程时,我在终端中收到以下消息 remote: Updating branch 'mas
Minikube已启动并正在运行,没有任何错误,但是我无法 curl IP。我在这里遵循:https://docs.traefik.io/user-guide/kubernetes/,似乎没有提到关闭
每当我尝试docker组成任何项目时,都会出现以下错误。 我尝试过有和没有sudo 我在这台机器上只有这个问题。我可以在Mac和Amazon WorkSpace上运行相同的容器。 (myslabs)
我正在尝试 pip install stanza 并收到此消息: ERROR: No matching distribution found for torch>=1.3.0 (from stanza
DNS 解析看起来不错,但我无法 ping 我的服务。可能是什么原因? 来自集群中的另一个 Pod: $ ping backend PING backend.default.svc.cluster.l
我正在使用Hibernate 4 + Spring MVC 4当我开始 Apache Tomcat Server 8我收到此错误: Error creating bean with name 'wel
我是一名优秀的程序员,十分优秀!