日期:2014-05-20  浏览次数:20888 次

自己写的贪吃蛇,谁能帮我修改下蛇头碰到蛇身的的功能函数
我写好的处理,当处于运行时,在卜吃食物的情况下,在空白区域运行,也会触发蛇头碰到蛇身的的处理。
青高手解决下逻辑问题。
Java code

package game;

import java.awt.BorderLayout;    
import java.awt.Button;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Iterator;
import java.util.LinkedList;

import javax.swing.*;
import javax.swing.border.Border;

public class MFrame extends JFrame implements ActionListener, KeyListener, Runnable {
    private static final int UP=1;
    private static final int DOWN=2;
    private static final int LEFT=3;
    private static final int RIGHT=4;
    private static final int ROWS=30;
    private static final int COLS=40;
    
    int score =0,speed =500;
    boolean ispause = false,isend = false;
    JButton startGame,stopGame;
    JButton [][] PA = new JButton[ROWS][COLS];
    JLabel jl1,jl2;
    int direction = RIGHT,lastdirection = RIGHT;
    int x = 0,y = 0; 
    LinkedList<snakeact> list = new LinkedList<snakeact>();
    Thread nThread = new Thread(this);

    public MFrame() {
        setTitle("~贪吃蛇~刘松立~");
        setBounds(200, 200, 435, 390);
        setVisible(true);        
        
        startGame = new JButton("开始");
        stopGame = new JButton("暂停");        
        
        jl2 = new JLabel("分数   :  " + score);
        jl1 = new JLabel("速度   :  " + speed);
        GridLayout grid = new GridLayout(ROWS,COLS);
        JPanel jPanel=new JPanel(grid);
        for(int i=0;i<ROWS;i++)
            for(int j=0;j<COLS;j++)
            {
                PA[i][j] = new JButton();
                PA[i][j].setBackground(Color.lightGray);
                PA[i][j].setSize(10, 10);
                PA[i][j].setVisible(false);
                jPanel.add(PA[i][j]);
            }
        Border border = BorderFactory.createBevelBorder(0, Color.black, Color.black);
        jPanel.setBorder(border);
        startGame.addActionListener(this);
        stopGame.addActionListener(this);
        addKeyListener(this);
        JPanel jPanel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
        jPanel2.add(startGame);
        jPanel2.add(stopGame);
        jPanel2.add(jl2);
        jPanel2.add(jl1);
        
        getContentPane().add(jPanel2,BorderLayout.NORTH);
        getContentPane().add(jPanel,BorderLayout.CENTER);
        
        
        validate();
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }
    
    @Override
    public void keyTyped(KeyEvent e) {}
    @Override
    public void keyPressed(KeyEvent e) {
        if(!isend&&!ispause){
            if(e.getKeyCode() == KeyEvent.VK_UP){
                direction = UP;
            }
            if(e.getKeyCode() == KeyEvent.VK_DOWN){
                direction = DOWN;
            }
            if(e.getKeyCode() == KeyEvent.VK_LEFT){
                direction = LEFT;
            }
            if(e.getKeyCode() == KeyEvent.VK_RIGHT){
                direction = RIGHT;
            }
            move();
        }
    }
    
    public void move() {        
        int x = list.getFirst().getX();
        int y = list.getFirst().getY();
        switch (direction) {
        case UP:{
            if(lastdirection == DOWN)
                x = x+1;
            else {
                x = x-1;
                lastdirection = UP;
            }
            break;
        }
        case DOWN:{
            if(lastdirection == UP)
                x = x-1;
            else {
                x = x+1;
                lastdirection = DOWN;
            }
            break;
        }
        case LEFT:{
            if(lastdirection == RIGHT)
                y = y+1;
            else {
                y = y-1;
                lastdirection = LEFT;
            }
            break;
        }
        case RIGHT:{
            if(lastdirection == LEFT)
                y = y-1;
            else {
                y = y+1;
                lastdirection = RIGHT;
            }
            break;
        }
        default:
            break;
        }
        gameover go = new gameover();
        go.setBounds(200, 300, 435, 150);
        if (x>=0&&x<ROWS&&y>=0&&y<COLS) {
            snakeact temp = new snakeact();
            temp.setX(x);
            temp.setY(y);
            //bug 出现的地方
        //    if (PA[x][y].isVisible()&&PA[x][y].getBackground().equals(Color.lightGray)) {    
        //        go.setVisible(true);    
        //        isend = true;
        //    }
        //    else{
                list.addFirst(temp);
                PA[x][y].setVisible(true);
                 if (!addsnakebody()) {                
                        PA[list.getLast().getX()][list.getLast().getY()].setVisible(false);
                        list.removeLast();
                }   
                 else {
                            PA[x][y].setBackground(Color.lightGray);
                            food();
                            score += 100;
                      }
         //   }
        }
        else {
            this.dispose();
            go.setVisible(true);
            isend = true;
        }
        jl1.setText("分数   :  " + score);
        jl2.setText("速度   :  " + speed);
    }

    public boolean addsnakebody() {
        int x = list.getFirst().getX();
        int y = list.getFirst().getY();
        if (PA[x][y].getBackground().equals(Color.yellow)&&PA[x][y].isVisible()) {
            return true;
        }
            return false;
    }
    
    public void food() {
        int x = (int) (Math.random() * ROWS);
        int y = (int) (Math.random() * COLS);
        while(PA[x][y].isVisible()){
             x = (int) (Math.random() * ROWS);
             y = (int) (Math.random() * COLS);
        }
        PA[x][y].setBackground(Color.yellow);
        PA[x][y].setVisible(true);
    }
    
    @Override
    public void keyReleased(KeyEvent e) {}

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == startGame){
            start();
        }
        if(e.getSource() == stopGame ){
            stop();
        }        
    }
    
    public void start(){
        for(int i=0;i<ROWS;i++)
            for(int j=0;j<COLS;j++)
            {
                PA[i][j].setBackground(Color.lightGray);
                PA[i][j].setVisible(false);
            }
        startGame.setEnabled(false);
        list.removeAll(list);
        for (int i = 0; i < 3; i++) {
            snakeact tempSnakeact = new snakeact();
            tempSnakeact.setX(9);
            tempSnakeact.setY(10-i);
            list.add(tempSnakeact);
        }
        Iterator<snakeact> iter = list.iterator();
        while(iter.hasNext()){
            snakeact te = iter.next();
            PA[te.getX()][te.getY()].setVisible(true);
        }
        
        x = (int) (Math.random() * ROWS);
        y = (int) (Math.random() * COLS);
        while(PA[x][y].isVisible()){
             x = (int) (Math.random() * ROWS);
             y = (int) (Math.random() * COLS);
        }
        PA[x][y].setBackground(Color.yellow);
        PA[x][y].setVisible(true);
        
        requestFocus();
                
        nThread.start();
    }
    
    public void stop(){
        if(ispause){
            ispause = false;
            stopGame.setText("暂停");
        }
        else {
            ispause = true;
            stopGame.setText("继续");
        }
        requestFocus();
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        new MFrame();
    }

    @Override
    public void run() {
        while (true) {        
            try {
            Thread.sleep(speed);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
            if (!isend&&!ispause) {
                move();
            }
        }
    }
}

package game;

public class snakeact {
    private int x;
    private int y;
    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }
    public int getY() {
        return y;
    }
    public void setY(int y) {
        this.y = y;
    }
}

package game;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;


public class gameover extends JDialog implements ActionListener{
        JButton restart,exit;
        JLabel  over;
        Box baseBox,box1,box2;
        
    gameover(){
        restart = new JButton("再来一盘");
        exit = new JButton("退出游戏");
        over = new JLabel("真遗憾!你失败了!");
        
        restart.addActionListener(this);
        exit.addActionListener(this);
        
        box1 = Box.createHorizontalBox();
        box2 = Box.createHorizontalBox();
        baseBox = Box.createVerticalBox();        
        
        box1.add(restart);
        box1.add(Box.createHorizontalStrut(40));
        box1.add(exit);
        
        box2.add(over);
        
        baseBox.add(Box.createVerticalStrut(20));
        baseBox.add(box2);
        baseBox.add(Box.createVerticalStrut(15));
        baseBox.add(box1);
        
        setLayout(new FlowLayout());
        add(baseBox);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == exit) {
            this.dispose();
        }
        if (e.getSource() == restart) {
            this.dispose();
            new MFrame();
        }
    }
}