线程“AWT-EventQueue-0”中的异常java.lang.IndexOutOfBoundsException:索引:0,大小:0

时间:2014-01-12 21:18:06

标签: java swing

我想为两个玩家创建一个简单的蛇游戏。当我开始申请时,首先主窗口欢迎我们。

然后我从菜单栏中选择了玩家数量,并且我预计游戏应该根据玩家的数量来运行。当我点击一个或两个玩家时,调用newgame方法并启动计时器,称为gameTimer。但在Timer中,chargeSnake和disChargeSnake方法无法正常工作。他们没有创建蛇图形并且出现了一些错误。

如果你能提供帮助,我将不胜感激。

感谢。

我的小组:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.JPanel;

public class Grafik extends JPanel
{

    public Point feed;
    public boolean isThereFeed;

    private Color feedColor = null;
    private Color backgroundColor = null;
    private int x_start=0;
    private int y_start=0;

    private Boolean chargeSnakestate = false;
    private Boolean dischargeSnakestate = false;
    private Boolean putFeedState = false;
    private Color snakeColouuuur = null;


    public Grafik(){
        System.out.println("inside of grafik const"); 
        feedColor = Color.RED;                  
        feed = new Point();                     
        backgroundColor = Color.PINK;        
    }


    public void createGraphicYard()
    {        
        System.out.println("inside of creategraphicsyard"); 
        setBackground(backgroundColor);
        setPreferredSize(new Dimension(400,350));
        setBounds(0, 50, 400, 350);
        setVisible(true);
    }

     public void chargeSnake(int x, int y,Color snakeColor)
     {  
         System.out.println("inside of chargesnake"); 
         repaint(x_start,y_start,10,10);
         chargeSnakestate =true; 
         x_start = x;
         y_start = y;
         snakeColouuuur = snakeColor;
         repaint(x_start*10,y_start*10,10,10);
         System.out.println("chargeSnake1 : "+ snakeColouuuur+"   "+x_start+"   "+ y_start );
     }

     public void dischargeSnake(int x, int y)
     {
         System.out.println("inside of dischargesnake"); 
         repaint(x_start*10,y_start*10,10,10);
         dischargeSnakestate =true; 
         x_start = x;
         y_start = y;
         repaint(x_start*10,y_start*10,10,10);
     }

     public void putFeed(int x,int y)
     {
         System.out.println("inside of putfeed"); 
         repaint(x_start*10,y_start*10,10,10);
         putFeedState =true; 
         x_start = x;
         y_start = y;
         repaint(x_start*10,y_start*10,10,10);
     }


     public boolean isSnakeTookFeed(int snakeX, int snakeY)
     {
         System.out.println("inside of isSnakeTookFeed"); 
         boolean b=false;
         if((feed.x==snakeX)&&(feed.y==snakeY))
             b=true;
         else
             b=false;
         return b;
     }

     public void specifyFeedCoordinate()
     {
         System.out.println("inside of specifyFeedCoordinate"); 
         List<Integer> possiblePlacesX = new ArrayList<Integer>();
         List<Integer> possiblePlacesY = new ArrayList<Integer>();

        Dimension size = getSize();
        int imageType = BufferedImage.TYPE_INT_ARGB;
        BufferedImage image = new BufferedImage(size.width, size.height, imageType);
        Graphics2D g2d = image.createGraphics();
        paint(g2d);

         for(int iy=0;iy<350;iy+=10)
         {
             for(int ix=0;ix<400;ix+=10)
             {
                 if ((Color.WHITE.equals(new Color(image.getRGB(ix+5, iy+5)))))
                 {
                     possiblePlacesX.add(ix / 10);
                     possiblePlacesY.add(iy / 10);
                 }
             }
         }
         Random random= new Random();
         int rnd=random.nextInt(possiblePlacesX.size()+1);
         feed.x=possiblePlacesX.get(rnd);
         try {
            Thread.sleep(25);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
         feed.y=possiblePlacesY.get(rnd);
     }

     public Dimension getPreferredSize() {
         System.out.println("inside of getpreffered size"); 
         return new Dimension(350,400);
     }

     public void paintComponent(Graphics g) {
         super.paintComponent(g);
         if(chargeSnakestate)
         {           
             System.out.println("inside of paintComponent"); 
             System.out.println("chargeSnakestate : "+ snakeColouuuur+"   "+x_start+"   "+ y_start );
             g.setColor(snakeColouuuur);
             g.fillRect(x_start, y_start, 10, 10);
         }
         if(dischargeSnakestate)
         {
             System.out.println("inside of paintComponent");
             g.setColor(backgroundColor);
             g.fillRect(x_start, y_start, 10, 10);
         }
         if(putFeedState)
         {
             System.out.println("inside of paintComponent");
             g.setColor(feedColor);
             g.fillRect(x_start, y_start, 10, 10);
         }
         Toolkit.getDefaultToolkit().sync();
         g.dispose();

         chargeSnakestate=false;
         dischargeSnakestate=false;
         putFeedState=false;
     }    
}

我的JFrame:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.concurrent.Semaphore;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Snake_Form extends JFrame {

    /**
     * 
     */
    private static final long serialVersionUID = 6139997831592727657L;

    private JPanel contentPane;

    private Snake []snake;
    private Grafik grafik;

    int numberOfPlayer=1;
    int maxNumberOfPlayer=2;
    boolean gameSituation=false;
    private JLabel lblFirstPlayerScore;
    private JLabel lblSecondPlayerScore;

    Color[] clr = {new Color(255,0,0)/*red*/,new Color(0,255,0)/*green*/,new Color(0,0,255)/*blue*/};

    private Timer gameTimer;
    private Timer waitTimer;

    int speed = 1;

    public Semaphore semaphore;

    public Snake[] getSnake() {
        return snake;
    }

    public void setSnake(Snake[] snake) {
        this.snake = snake;
    }

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    Snake_Form frame = new Snake_Form();
                    frame.pack();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Snake_Form() {
        setResizable(false);
        System.out.println("Snake_FORM");

        setPreferredSize(new Dimension(400, 400));
        setTitle("SNAKE GAME");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);

        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);

        JMenu mnGame = new JMenu("Game");
        menuBar.add(mnGame);

        JMenuItem start = new JMenuItem("Start");
        start.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("start menu item ına basıldı");

                if(!gameSituation)
                {
                    newGame();
                }
                else
                {
                    gameTimer.setDelay(150);
                    gameTimer.start();
                }
            }
        });
        mnGame.add(start);

        JMenuItem stop = new JMenuItem("Stop");
        stop.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("stop menu item ına basıldı");
                gameTimer.stop();
            }
        });
        mnGame.add(stop);

        JMenuItem newGame = new JMenuItem("New Game");
        newGame.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("new game menu item ına basıldı");
                newGame();
            }
        });
        mnGame.add(newGame);

        JMenu mnSpeed = new JMenu("Speed");
        menuBar.add(mnSpeed);

        JMenuItem level1 = new JMenuItem("Level  1");
        level1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Level 1 menu item ına basıldı");
                speed = 1;
                gameTimer.setDelay(150);
                for (int i = 0; i < numberOfPlayer; i++)
                {
                    snake[i].snakeSpeed=speed;
                }
            }
        });
        mnSpeed.add(level1);

        JMenuItem level2 = new JMenuItem("Level  2");
        level2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Level 2 menu item ına basıldı");
                speed = 2;
                gameTimer.setDelay(130);
                for (int i = 0; i < numberOfPlayer; i++)
                {
                    snake[i].snakeSpeed=speed;
                }
            }
        });
        mnSpeed.add(level2);

        JMenuItem level3 = new JMenuItem("Level  3");
        level3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("LEvel 3 menu item ına basıldı");
                speed = 3;
                gameTimer.setDelay(110);
                for (int i = 0; i < numberOfPlayer; i++)
                {
                    snake[i].snakeSpeed=speed;
                }
            }
        });
        mnSpeed.add(level3);

        JMenuItem level4 = new JMenuItem("Level  4");
        level4.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("level 4 menu item ına basıldı");
                speed = 4;
                gameTimer.setDelay(90);
                for (int i = 0; i < numberOfPlayer; i++)
                {
                    snake[i].snakeSpeed=speed;
                }
            }
        });
        mnSpeed.add(level4);

        JMenuItem level5 = new JMenuItem("Level  5");
        level5.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("level 5 menu item ına basıldı");
                speed = 5;
                gameTimer.setDelay(80);
                for (int i = 0; i < numberOfPlayer; i++)
                {
                    snake[i].snakeSpeed=speed;
                }
            }
        });
        mnSpeed.add(level5);

        JMenuItem level6 = new JMenuItem("Level  6");
        level6.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Level  6  menu item ına basıldı");
                speed = 6;
                gameTimer.setDelay(70);
                for (int i = 0; i < numberOfPlayer; i++)
                {
                    snake[i].snakeSpeed=speed;
                }
            }
        });
        mnSpeed.add(level6);

        JMenuItem level7 = new JMenuItem("Level  7");
        level7.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Level 7  menu item ına basıldı");
                speed = 7;
                gameTimer.setDelay(60);
                for (int i = 0; i < numberOfPlayer; i++)
                {
                    snake[i].snakeSpeed=speed;
                }
            }
        });
        mnSpeed.add(level7);

        JMenuItem level8 = new JMenuItem("Level  8");
        level8.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Level 8  menu item ına basıldı");
                speed = 8;
                gameTimer.setDelay(50);
                for (int i = 0; i < numberOfPlayer; i++)
                {
                    snake[i].snakeSpeed=speed;
                }
            }
        });
        mnSpeed.add(level8);

        JMenuItem level9 = new JMenuItem("Level  9");
        level9.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Level 9  menu item ına basıldı");
                speed = 9;
                gameTimer.setDelay(40);
                for (int i = 0; i < numberOfPlayer; i++)
                {
                    snake[i].snakeSpeed=speed;
                }

            }
        });
        mnSpeed.add(level9);

        JMenu mnPlayer = new JMenu("Player");
        menuBar.add(mnPlayer);

        JMenuItem mntmOnePlayer = new JMenuItem("One Player");
        mntmOnePlayer.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("One Player menu item ına basıldı");
                numberOfPlayer = 1;
                lblFirstPlayerScore.setVisible(true);
                lblSecondPlayerScore.setVisible(false);
                lblFirstPlayerScore.setText("Birinci Oyuncu PUAN : " + snake[0].score );

                newGame();
            }
        });
        mnPlayer.add(mntmOnePlayer);

        JMenuItem mntmTwoPlayer = new JMenuItem("Two Player");
        mntmTwoPlayer.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Two Player menu item ına basıldı");

                numberOfPlayer = 2;
                lblFirstPlayerScore.setVisible(true);
                lblSecondPlayerScore.setVisible(true);
                lblFirstPlayerScore.setText("Birinci Oyuncu PUAN : " + snake[0].score );
                lblSecondPlayerScore.setText("ikinci Oyuncu PUAN : " + snake[1].score );
                newGame();
            }
        });
        mnPlayer.add(mntmTwoPlayer);

        JMenu mnHelp = new JMenu("Help");
        menuBar.add(mnHelp);

        final JMenuItem learnGame = new JMenuItem("Learn Game");
        learnGame.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                JOptionPane.showMessageDialog(learnGame, "        Game starts when the user select the “Player” menu \nfrom the game board and choose how many people\nhe/she will want to play.\n\n        Joy pad will be appointed for the -One Player- \nand E,S,F,D will be appointed for the -Second Player- \nto play the game. (E->Up S->Left F->Right D->Down).","Learn Game",JOptionPane.INFORMATION_MESSAGE);
            }
        });
        mnHelp.add(learnGame);

        final JMenuItem aboutGame = new JMenuItem("About Game");
        aboutGame.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(aboutGame, "Snake Game written by Merve =)", "About Game", JOptionPane.INFORMATION_MESSAGE);
            }
        });

        mnHelp.add(aboutGame);

        contentPane = new JPanel();

//      contentPane.setSize(new Dimension(400, 400));
        contentPane.setBounds(0,0,400,400);
        contentPane.setPreferredSize(new Dimension(400,400));
        contentPane.setBackground(Color.WHITE);
        setContentPane(contentPane);
        contentPane.setLayout(null);

        lblFirstPlayerScore = new JLabel("lblFirstPlayerScore");
        lblFirstPlayerScore.setBounds(10, 0, 150, 25);
        lblFirstPlayerScore.setVisible(false);          //when the game is loaded score does not seem
        contentPane.add(lblFirstPlayerScore);

        lblSecondPlayerScore = new JLabel("lblSecondPlayerScore");
        lblSecondPlayerScore.setBounds(10, 25, 150, 25);
        lblSecondPlayerScore.setVisible(false);         //when the game is loaded score does not seem
        contentPane.add(lblSecondPlayerScore);


        grafik= new Grafik();

        grafik.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if(e.getKeyCode()==KeyEvent.VK_LEFT) snake[1].route=1;
                if(e.getKeyCode()==KeyEvent.VK_RIGHT) snake[1].route=2;
                if(e.getKeyCode()==KeyEvent.VK_UP) snake[1].route=3;
                if(e.getKeyCode()==KeyEvent.VK_DOWN) snake[1].route=4;
                //if (e.KeyCode == Keys.Escape) Application.Exit();

                if(e.getKeyCode()==KeyEvent.VK_S) snake[1].route=1;
                if(e.getKeyCode()==KeyEvent.VK_F) snake[1].route=2;
                if(e.getKeyCode()==KeyEvent.VK_E) snake[1].route=3;
                if(e.getKeyCode()==KeyEvent.VK_D) snake[1].route=4;

                for(int i=0;i<numberOfPlayer;i++)
                {
                    snake[i].waitInt=20;
                }
                waitTimer.stop(); 
                gameTimer.start();  
            }
        });

        grafik.createGraphicYard(); 

        grafik.feed.x=-1;
        grafik.feed.y=-1;
        grafik.isThereFeed=false;

        contentPane.add(grafik);


        //when the game is loaded 2 Snake Object is set
        snake= new Snake[maxNumberOfPlayer];




        //start the game with one player
        for(int i=0; i<maxNumberOfPlayer;i++)
        {
            snake[i]= new Snake();
        }

        //Create a timer.
        gameTimer = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                gameTickerTick();
            }
        });

        //Create a timer.
        waitTimer = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                waitTimerTick();
            }
        });

        semaphore= new Semaphore(1);
    }

    void newGame()
    {
        System.out.println("new Game icindeyim");

        gameTimer.stop();

        grafik.createGraphicYard();
        grafik.isThereFeed=false;

        for(int i=0; i<numberOfPlayer;i++)
        {
            snake[i].length=5;
            snake[i].tailLength=5;
            snake[i].x=5+i*5;
            snake[i].y=5+i*5;
            snake[i].route=2-i;
            snake[i].score=0;
            snake[i].defaultSnake();
            snake[i].snakeColor = clr[i];
        }

        gameSituation=true;
        gameTimer.start();
    }

    private void snakeGameIsOver() {
        System.out.println("oyun bitti");
        gameSituation=false;
        try {
            gameTimer.wait(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(!gameSituation)
            gameTimer.stop();
        else
            gameTimer.start();

        if(numberOfPlayer==1)
            JOptionPane.showMessageDialog(lblFirstPlayerScore, "Game is over...");
        else
            JOptionPane.showInputDialog(lblFirstPlayerScore+"\n"+lblSecondPlayerScore, "Game is over..");
        lblFirstPlayerScore.setText("SCORE: "+snake[0].score);
        grafik.createGraphicYard();
        grafik.isThereFeed=gameSituation;
        if(!gameSituation)
            gameTimer.stop();
        else
            gameTimer.start();
    }

    void gameTickerTick()
    {
        System.out.println(" In gametimer");    

        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        for(int i=0;i<numberOfPlayer;i++)
        {
            //shift the snake one unit to its route
            if(snake[i].route==1) snake[i].snakeGoesLeft();
            if(snake[i].route==2) snake[i].snakeGoesRight();
            if(snake[i].route==3) snake[i].snakeGoesUp();
            if(snake[i].route==4) snake[i].snakeGoesDown();

            //when the game area border ends permits the snake pass other side
            if(snake[i].x>39) snake[i].x=0;
            else if(snake[i].x<0) snake[i].x=40;

            if(snake[i].y>39) snake[i].y=0;
            else if(snake[i].y<0) snake[i].y=40;

            System.out.println("I will charge");            
            //charge the snake
            grafik.chargeSnake(snake[i].x,snake[i].y,snake[i].snakeColor);
            System.out.println("I have charged");

            //adds the added unit to tail of snake
            snake[i].areaX[snake[i].tailLength]=snake[i].x;
            snake[i].areaY[snake[i].tailLength]=snake[i].y;
            snake[i].tailLength++;

            System.out.println("I will discharged");
            //discharge the snake
            grafik.dischargeSnake(snake[i].areaX[snake[i].tailLength-snake[i].length], snake[i].areaY[snake[i].tailLength-snake[i].length]);
            System.out.println("I have discharged");


            if(snake[i].tailLength>899)
            {
                snake[i].tailLength=snake[i].length;
                for(int z=0;z<snake[i].length;++z)
                {
                    snake[i].areaX[snake[i].length-z]=snake[i].areaX[900-z];
                    snake[i].areaY[snake[i].length-z]=snake[i].areaY[900-z];
                }
            }

            if((grafik.isSnakeTookFeed(snake[i].x, snake[i].y)==false)&&(grafik.isThereFeed==false))
            {
                //create new feed and its coordinate
                grafik.specifyFeedCoordinate();
                grafik.putFeed(grafik.feed.x,grafik.feed.y);
                grafik.isThereFeed=true;
            }

            if(grafik.isSnakeTookFeed(snake[i].x, snake[i].y)==true)
            {
                grafik.feed.x=-1;
                grafik.feed.y=-1;
                grafik.isThereFeed=false;
                snake[i].score+=1*snake[i].snakeSpeed;
                snake[i].length+=1;
                if(i==0)
                    lblFirstPlayerScore.setText("First Player Score: "+snake[i].score);
                else if(i==1)
                    lblSecondPlayerScore.setText("Second Player Score: "+snake[i].score);               
            }
        }

        for(int i=0;i<numberOfPlayer;i++)
        {
            if(snake[i].isSnakeCrashedItself(contentPane)==true)
            {
                gameTimer.stop();;
                waitTimer.start();

                if(snake[i].waitInt<=0)
                {                       
                }
                else
                {
                    snake[i].waitInt=20;
                }
            }               
        }
        semaphore.release();
    }

    void waitTimerTick()
    {
        System.out.println("wait timer");
        for(int i=0;i<numberOfPlayer;i++)
        {
            snake[i].waitInt--;
            if(snake[i].waitInt==0)
            {
                waitTimer.stop();
                snakeGameIsOver();
                break;
            }
        }
    }
}

我的蛇对象:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.swing.JPanel;


public class Snake 
{
    public Color snakeColor;
    public int route;
    public int length,tailLength;
    public int x,y,snakeSpeed;
    public int score;
    public int waitInt;
    public int[] areaX= new int[1000];
    public int[] areaY= new int[1000];

    protected Random randomm;

    //Snake constructor
    public Snake()
    {
        snakeColor= Color.BLUE;
        snakeSpeed=1;
        randomm= new Random();
        System.out.println("Snake has been constructed.");
    }

    //turn the snake right side
    public void snakeGoesRight()
    {
        this.x+=1;
    }
    //turn the snake left side
    public void snakeGoesLeft()
    {
        this.x-=1;
    }
    //turn the snake upper
    public void snakeGoesUp()
    {
        this.y-=1;
    }
    //turn the snake down side
    public void snakeGoesDown()
    {
        this.y+=1;
    }

    //check the snake if it s crashed itself or not
    public boolean isSnakeCrashedItself(JPanel jpanel)
    {
        System.out.println("inside of isSnakeCrashedItself function");
        Dimension size = jpanel.getSize();
        int imageType = BufferedImage.TYPE_INT_ARGB;
        BufferedImage image = new BufferedImage(size.width, size.height, imageType);
        Graphics2D g2d = image.createGraphics();
        jpanel.paint(g2d);

        boolean situation= false;
        int x= this.x*10;
        int y=this.y*10;

        try
        {
            if(route==1)
            {
                if((!Color.WHITE.equals(new Color(image.getRGB(x-5,y+5)))))
                {
                    situation=true;
                }
                else
                    situation=false;
            }
            if(route==2)
            {
                if((!Color.WHITE.equals(new Color(image.getRGB(x+15, y+5)))))
                {
                    situation=true;
                }
                else
                    situation=false;
            }
            if(route==3)
            {
                if((!Color.WHITE.equals(new Color(image.getRGB(x+5, y-5)))))
                {
                    situation=true;
                }
                else
                    situation=false;
            }
            if(route==4)
            {
                if((!Color.WHITE.equals(new Color(image.getRGB(x+5, y+15)))))
                {
                    situation=true;
                }
                else
                    situation=false;
            }       
        }
        catch(Exception e)
        {
            //e.message
            return false;
        }
        return situation;
    }
    //it makes the snake s properties default
    public void defaultSnake()
    {
        System.out.println("inside of default snake function");

        areaX=null;
        areaY=null;

        areaX= new int[1000];
        areaY=new int[1000];

        for(int i=0;i<1000;i++)
        {
            areaX[i]=0;
            areaY[i]=0;
        }
    }
}

控制台输出:

I will charge
inside of chargesnake
chargeSnake1 : java.awt.Color[r=255,g=0,b=0]   6   5
I have charged
I will discharged
inside of dischargesnake
I have discharged
inside of isSnakeTookFeed
inside of specifyFeedCoordinate
inside of paintComponent
chargeSnakestate : java.awt.Color[r=255,g=0,b=0]   0   0
inside of paintComponent
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at Grafik.specifyFeedCoordinate(Grafik.java:117)
    at Snake_Form.gameTickerTick(Snake_Form.java:498)
    at Snake_Form$19.actionPerformed(Snake_Form.java:378)
    at javax.swing.Timer.fireActionPerformed(Unknown Source)
    at javax.swing.Timer$DoPostEvent.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

1 个答案:

答案 0 :(得分:2)

     int rnd=random.nextInt(possiblePlacesX.size()+1);
     feed.x=possiblePlacesX.get(rnd);

     // ...

     feed.y=possiblePlacesY.get(rnd);

看看你在这做什么?您最终可能会得到rnd的值与列表的大小相同,这当然会为您提供上面的好堆栈跟踪。

在您的确切情况下,您的列表为空(size() == 0),并且您正在尝试访问项0。相反,你应该只处理这种情况(空列表)和(可能)什么都不做。

你的代码中还有其他问题,比如@MadProgrammer提到的问题,我不会详细介绍......