我已经为大学项目开始了一个Snake游戏,我目前遇到的问题是,存储在数组中的主体的第一段与头部位于同一位置。我不太清楚如何抵消身体第一段的位置,因此它与头部的位置不同。
当我在身体和头部之间创建碰撞检测时我注意到了这一点,并且由于第一段与头部位于同一位置而无法正常工作。
的 MainApp.java
import processing.core.*;
import java.awt.*;
/**
* Created by Wills on 25/05/2018.
*/
public class MainApp extends PApplet{
Snake snake;
Food food;
public static void main(String[] args){
PApplet.main("MainApp", args);
}
int screenSize = 800;
int scale = 20;
public void settings(){
size(screenSize,screenSize);
snake = new Snake(width/2, height/2, 0, 1, scale, screenSize );
food = new Food(screenSize, scale);
}
public void setup(){
frameRate(10);
rect(food.getX(), food.getY(), scale, scale);
}
public void draw() {
background(0);
snake.update();
fill(255);
rect(snake.getX(), snake.getY(), snake.getScale(), snake.getScale());
if(snake.getX() == food.getX() && snake.getY() == food.getY()){
snake.eat();
}
for(Point p: snake.getBody()){
if(food.getX() == p.getX() && food.getY() == p.getY()){
food.rePos();
}
rect((float)p.getX(), (float)p.getY(), snake.getScale(), snake.getScale());
}
fill(255,0,0);
rect(food.getX(), food.getY(), scale, scale);
}
public void mouseClicked(){
snake.eat();
snake.eat();
snake.eat();
snake.eat();
}
public void keyPressed(){
if(key == 'a'){
snake.setDirection(-1, 0);
}
if(key == 'd'){
snake.setDirection(1, 0);
}
if(key == 'w'){
snake.setDirection(0, -1);
}
if(key == 's'){
snake.setDirection(0, 1);
}
}
}
的 Snake.java
import processing.core.PApplet;
import java.awt.*;
import java.util.ArrayList;
/**
* Created by Wills on 25/05/2018.
*/
public class Snake extends PApplet{
int x, y, yspeed, xspeed, scale;
int score;
int screenSize;
ArrayList<Point> body;
public Snake(int x, int y, int xspeed, int yspeed, int scale, int screenSize){
body = new ArrayList<Point>();
this.x = x;
this.y = y;
this.xspeed = xspeed;
this.yspeed = yspeed;
this.scale = scale;
this.screenSize = screenSize;
}
public int getX(){
return x;
}
public int getY() {
return y;
}
public void setDirection(int x, int y){
this.xspeed = x;
this.yspeed = y;
}
public float getScale(){
return scale;
}
void update(){
x = constrain(x + xspeed * scale,0, screenSize - scale);
y =constrain(y + yspeed * scale,0, screenSize - scale);
body.add(0, new Point(x, y));
body.remove(score);
}
void eat(){
body.add(new Point(x,y));
score ++;
System.out.println(score);
}
void kill(){
score = 0;
x = screenSize/2;
y = screenSize/2;
}
ArrayList<Point> getBody(){
return body;
}
}
的 Food.java
import processing.core.PApplet;
import java.awt.*;
import java.util.ArrayList;
/**
* Created by Wills on 25/05/2018.
*/
public class Food extends PApplet{
float screenSize;
int scale, x, y;
Food(int screenSize, int scale){
this.scale = scale;
this.screenSize = screenSize;
generate();
}
float getX(){
return x;
}
float getY(){
return y;
}
public void rePos() {
generate();
}
private void generate(){
x = floor(random(0, scale));
y = floor(random(0, scale));
x = (int) map(x, 0, scale, 0, screenSize);
y = (int) map(y, 0, scale, 0, screenSize);
}
}
非常感谢任何帮助!