贪吃蛇
package 贪吃蛇;
import java.awt.*;
public class Food {
private int x,y;
public Food(){
this.x = (int)(Math.random()*20)*20;
//System.out.println(x);
this.y = (int)(Math.random()*20)*20;
//System.out.println(y);
}
public void isEat(){
this.x = (int)(Math.random()*20)*20;
this.y = (int)(Math.random()*20)*20;
}
public void paint(Graphics g){
Color c = g.getColor();
g.setColor(Color.yellow);
g.fillOval(this.x,this.y,20,20);
g.setColor(c);
}
public void setY(int y) {
this.y = y;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public int getX() {
return x;
}
}
package 贪吃蛇;
import java.awt.*;
public class Map {
public void paint(Graphics g){
for(int i = 0;i < 21;i++){
g.drawLine(0,20*i,400,20*i);
g.drawLine(20*i,0,20*i,400);
}
}
}
package 贪吃蛇;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Main extends JPanel {
private Map map;
private Snake snake;
private Food food;
private int score;
private boolean stop_or_move;
public Main(){
stop_or_move = false;
this.setPreferredSize(new Dimension(400,400));
this.restart();
this.setBackground(Color.cyan);
//this.repaint();
}
public void restart(){
this.score = 0;
map = new Map();
snake = new Snake();
food = new Food();
}
public void eat(){
if(snake.getSnake_head().getX() == food.getX() && snake.getSnake_head().getY() == food.getY()){
food.isEat();
snake.body_add();
this.score += 3;
//snake.setBody_length(snake.getBody_length()+1);
}
}
//判断食物是否与蛇重叠
public boolean food_ins_snake(){
if(snake.getSnake_head().getX() == food.getX() && snake.getSnake_head().getY() == food.getY()){
System.out.println("食物与蛇头重叠!");
return true;
}
for(int i = 0;i < snake.getArrayList().size();i++){
if(snake.getArrayList().get(i).getX() == food.getX() && snake.getArrayList().get(i).getY() == food.getY()){
System.out.println("食物与身体重叠!");
return true;
}
}
return false;
}
public void paint(Graphics g)