贪食蛇小项目,新手求助!!

老鸦 2015-10-15 10:58:56
先描述下我遇到的问题吧,在程序中定义了一个实现了Runnable接口的PaintThread类,在里面定义了run方法如下:
public void run() {
while(running){
if(pause) continue;
else repaint();
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}

当蛇死亡时会调用PaintThread中的pause()方法,把pause的值设为true,这样run函数就不能执行repaint(),我想要用一个方法当我按键F2时,可以重新开始游戏。
我在PaintThread类中定义了一个reStart()函数:

public void reStart(){
s=new Snake(Yard.this);
this.pause=false;
gameOver=false;
}
PaintThread类是Yard的内部类,gameOver参数是用来控制调用pause()函数的。

以下是程序中的Paint()函数:
public void paint(Graphics g) {
// TODO Auto-generated method stub
Color c=g.getColor();
g.setColor(Color.gray);
g.fillRect(0, 0, COLS*BLOCK_SIZE, ROWS*BLOCK_SIZE);
g.setColor(Color.darkGray);
//画出横线
for(int i=1;i<ROWS;i++){
g.drawLine(0, BLOCK_SIZE*i,COLS*BLOCK_SIZE , BLOCK_SIZE*i);
}
//画出竖线
for(int i=1;i<COLS;i++){
g.drawLine(BLOCK_SIZE*i, 0, BLOCK_SIZE*i, BLOCK_SIZE*ROWS);
}
g.setColor(Color.yellow);
g.drawString("score:"+score, 10, 60);

if(gameOver){
g.setFont(new Font("宋体",Font.BOLD,50));
g.drawString("游戏结束", 120, 180);
paintThread.pause();
}

g.setColor(c);
s.eat(e);
e.draw(g);
s.draw(g);
}
其中s是Snake类的对象,e是Egg类的对象,本人初学Java,这是第一个想要实现的小程序,希望各位大大指教一二。

...全文
262 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
I_am_a_Beginner 2015-10-15
  • 打赏
  • 举报
回复
  • 打赏
  • 举报
回复
在snake类中定义个初始化方法,控制类中定义一个boolean变量,按下F2的时候会设置这个变量,在游戏的时候判断这个变量,将snake初始化。
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.LinkedList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class SnakeTest {
	public static void main(String[] args) {
		start();
	}

	public static void start() {
		Snake snake = new Snake();
		Food food = new Food();
		GamePanel gamePanel = new GamePanel(snake, food);
		MyControl control = new MyControl(snake, food, gamePanel);
		gamePanel.setFocusable(true);
		snake.addTouchListener(control);
		gamePanel.addKeyListener(control);
		JFrame gameFrame = new JFrame();
		gameFrame.setSize(300, 300);
		gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		gameFrame.setResizable(false);
		gameFrame.setLocationRelativeTo(null);
		gameFrame.add(gamePanel);
		control.startGame();
		gameFrame.setVisible(true);
	}
}
/**
 * 食物类
 * @author Administrator
 *
 */
class Food {
	private Point p;
	private int x;
	private int y;
	public Food(){
		x = new Random().nextInt(MyGrid.GRID_X -1);
		y = new Random().nextInt(MyGrid.GRID_Y - 1);
		p = new Point(x, y);
	}
    /**
     * 显示食物
     */
    public void showMe(Graphics g){
    	Graphics2D g2 = (Graphics2D)g;
    	g2.setColor(Color.red);
    	g2.fillRect(x * MyGrid.WHITH, y * MyGrid.HEIGH, MyGrid.WHITH, MyGrid.HEIGH);
    }
    
    public void creatNewFood(){
    	x = new Random().nextInt(MyGrid.GRID_X);
		y = new Random().nextInt(MyGrid.GRID_Y);
		p = new Point(x, y);
    }
    /**
     * 食物被蛇碰到
     * @param snake
     */
    public boolean isEatBySnake(Snake snake){
    	LinkedList<Point> snakeBodies = snake.getSnakeBody();
    	for (Point point : snakeBodies) {
			if(point.equals(this.p)){
				creatNewFood();
				return true;
			}
		}
    	return false;
    }
}

/**
 * 蛇类
 * @author Administrator
 *
 */
class Snake {
	private LinkedList<Point> snakeBody;
	private TouchListener listener;
	private int x;
	private int y;

	public static final int UPPER = -1;
	public static final int DOWN = 1;
	public static final int LEFT = -3;
	public static final int RIGHT = 3;

	private Point head;
	private Point tail;
	private int direction;
	private int oldDirection;
    
	public Snake() {
		init();
	}
	
	public void init(){
		snakeBody = new LinkedList<>();
		direction = 0;
		oldDirection = 0;
		x = 2;
		y = 2;
		for (int i = 0; i < 3; i++) {
			Point p = new Point(x++, y);
			snakeBody.add(p);
			direction = RIGHT;
		}
	}
    
	private Point newHead(int x, int y) {
		return new Point(x, y);
	}

	public LinkedList<Point> getSnakeBody() {
		return snakeBody;
	}

	/**
	 * 添加监听器,判断蛇是否碰到食物,障碍物,自己
	 * 
	 * @param listener
	 */
	public void addTouchListener(TouchListener listener) {
		this.listener = listener;
	}

	/**
	 * 蛇移动
	 */
	public void move() {
		tail = snakeBody.removeFirst();
		head = snakeBody.getLast();
		x = head.x;
		y = head.y;

		if (oldDirection + direction == 0) {
			this.direction = oldDirection;
		}

		switch (direction) {
		case UPPER:
			if (y == 0) {
				y = MyGrid.GRID_Y - 1;
			}
			y--;
			break;
		case DOWN:
			if (y == MyGrid.GRID_Y - 1) {
				y = 0;
			}
			y++;
			break;
		case LEFT:
			if (x == 0) {
				x = MyGrid.GRID_X - 1;
			}
			x--;
			break;
		case RIGHT:
			if (x == MyGrid.GRID_X - 1) {
				x = 0;
			}
			x++;
		}
		head = newHead(x, y);
		snakeBody.addLast(head);
		oldDirection = this.direction;
		listener.touchListener(this);
	}

	/**
	 * 蛇改变方向
	 */
	public void changeDirection(int direction) {

		this.direction = direction;
	}

	public void eatFood() {
		snakeBody.addFirst(tail);
	}

	/**
	 * 蛇显示
	 * 
	 * @param g
	 */
	public void showMe(Graphics g) {
		Graphics2D g2 = (Graphics2D) g;
		g2.setColor(Color.blue);
		for (Point point : snakeBody) {
			g2.fillRect(point.x * MyGrid.WHITH, point.y * MyGrid.HEIGH,
					MyGrid.WHITH, MyGrid.HEIGH);
		}
	}

	/**
	 * 蛇碰到自己
	 * 
	 * @param snake
	 * @return
	 */
	public boolean touchBySelf(Snake snake) {
		return false;
	}
}

/**
 * 格子
 * @author Administrator
 *
 */
class MyGrid {
    public static final int WHITH = 10;
    public static final int HEIGH = 10;
    public static final int GRID_X = 29;
    public static final int GRID_Y = 29;
}

interface TouchListener {
    void touchListener(Snake snake);
}

/**
 * 游戏面板
 * @author Administrator
 *
 */
class GamePanel extends JPanel{
	/**
	 * 
	 */
	private static final long serialVersionUID = 952972903675008331L;
	private Snake snake;
	private Food food;
	
    public GamePanel(Snake snake, Food food) {
		super();
		this.snake = snake;
		this.food = food;
	}

    public void paintGamePanel(){
    	repaint();
    }
    
	@Override
    protected void paintComponent(Graphics g) {
		super.paintComponent(g);
    	snake.showMe(g);
    	food.showMe(g);
    }

}

/**
 * 控制器
 * 按F2重新开始,按p暂停再按继续,方向键↑ ↓ → ←
 * @author Administrator
 *
 */
class MyControl extends KeyAdapter implements TouchListener{
	private boolean pause = true;
	private boolean restart = false;
	private Snake snake;
	private Food food;
	private GamePanel gamePanel;
	
    public MyControl(Snake snake, Food food, GamePanel gamePanel) {
		super();
		this.snake = snake;
		this.food = food;
		this.gamePanel = gamePanel;
	}
    
	@Override
    public void keyPressed(KeyEvent e) {
		int keycode = e.getKeyCode();
		switch (keycode) {
		case KeyEvent.VK_UP:
			keycode = Snake.UPPER;
			snake.changeDirection(keycode);
			break;
		case KeyEvent.VK_DOWN:
			keycode = Snake.DOWN;
			snake.changeDirection(keycode);
			break;
		case KeyEvent.VK_LEFT:
			keycode = Snake.LEFT;
			snake.changeDirection(keycode);
			break;
		case KeyEvent.VK_RIGHT:
			keycode = Snake.RIGHT;
			snake.changeDirection(keycode);
			break;
		case KeyEvent.VK_P:
		    pause = !pause;
			break;
		case KeyEvent.VK_F2:
			restart = !restart;
			break;
		}
    }
	
	@Override
	public void touchListener(Snake snake) {
		if(this.snake.touchBySelf(snake)){
			
		}
		if(this.food.isEatBySnake(snake)){
			snake.eatFood();
		}
	}
	
	public void startGame(){
		new snakeDrive().start();
	}
	
	private class snakeDrive extends Thread{
		@Override
		public void run() {
			while(true){
				while(pause){
					if(restart){
						snake.init();
						restart = !restart;
					}
					snake.move();
					gamePanel.paintGamePanel();
					try {
						Thread.sleep(300);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}					
				}
			}
		}
	}

}
蓝莓之恋9527 2015-10-15
  • 打赏
  • 举报
回复
三联
蓝莓之恋9527 2015-10-15
  • 打赏
  • 举报
回复
表示没做过这个

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧