2011-02-04 4 views
1
import java.awt.Color; 

import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.GraphicsEnvironment; 
import java.awt.Rectangle; 
import java.awt.event.KeyEvent; 
import java.awt.event.KeyListener; 
import java.awt.image.BufferedImage; 
import javax.swing.JFrame; 
import javax.swing.JOptionPane; 

/** 
* 
* @author Zeveso 
*/ 
public class gameStart extends JFrame { 

//set Global variables 
final int WIDTH = 400, HEIGHT = 400; 
//Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); 
double cOspeed = .5; //car 1 speed 
double cTspeed = .5; //car 2 speed 
Boolean winnerChosen = false; 
Boolean canLap = false; 
Boolean canLapT = false; 
int cOlaps = 0; 
int cTlaps = 0; 
final int UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3; 
//direction of carOne 
int cODirection = UP; 
int cTDirection = UP; 
//setup for double buffer 
BufferedImage bufImg; 
//set Global Track 
//set outside 
Rectangle left = new Rectangle(0, 0, WIDTH/10, HEIGHT); 
Rectangle right = new Rectangle((WIDTH/10) * 9, 0, WIDTH/5, HEIGHT); 
Rectangle top = new Rectangle(0, 0, WIDTH, HEIGHT/8); 
Rectangle bottom = new Rectangle(0, (HEIGHT/15) * 14, WIDTH, HEIGHT/9); 
//set inside 
Rectangle topInr = new Rectangle((WIDTH/11) * 2, (HEIGHT/16) * 3, (WIDTH/14) * 9, HEIGHT/10); 
Rectangle bottomInr = new Rectangle((WIDTH/11) * 2, (HEIGHT/16) * 12, (WIDTH/14) * 9, HEIGHT/10); 
Rectangle leftInr = new Rectangle((WIDTH/11) * 2, HEIGHT/5, WIDTH/5, (HEIGHT/10) * 6); 
Rectangle rightInr = new Rectangle((WIDTH/12) * 6, (HEIGHT/20) * 7, WIDTH/2, (HEIGHT/10) * 3); 
//create finishLine 
Rectangle finishLine = new Rectangle(WIDTH/10, (HEIGHT/10) * 8, WIDTH/10, HEIGHT/70); 
//create checkpoint 
Rectangle checkPoint = new Rectangle((WIDTH/25) * 9, (HEIGHT/10) * 5, WIDTH/7, HEIGHT/70); 
//set Global Cars 
Rectangle carOne = new Rectangle(WIDTH/8, HEIGHT/2, WIDTH/30, WIDTH/30); 
Rectangle carTwo = new Rectangle(WIDTH/9, HEIGHT/2, WIDTH/30, WIDTH/30); 

public gameStart() { 
    super("Racing Game"); //set title 
    setSize(400, 400); //set the size 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //make sure it closes when you click the exit button 
    setVisible(true); //make sure its visible 
    setResizable(false); 
    setLocationRelativeTo(null); //set location of JFrame to middle 
    /* 
    * Set the location 
    * First get the size of screen from Global variables 
    * Then use .setLocation(); with those variables 
    */ 

    //start double buffer 
    bufImg = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().createCompatibleImage(WIDTH, HEIGHT); 

    //start cars up 
    moveMyCar moveCar = new moveMyCar(); 
    moveMyCar2 moveCar2 = new moveMyCar2(); 
    moveCar.start(); 
    moveCar2.start(); 
} 

@Override 
public void paint(Graphics g) { 
    Graphics2D gd = bufImg.createGraphics(); 
    try { 
     //setup double buffer in paint 
     gd.clearRect(0, 0, WIDTH, HEIGHT); 
     //draw finishline 
     gd.setColor(Color.RED); //set color 
     gd.fillRect(finishLine.x, finishLine.y, finishLine.width, finishLine.height); 
     //draw checkpoint 
     //gd.setColor(Color.CYAN); //set color 
     //gd.fillRect(checkPoint.x, checkPoint.y, checkPoint.width, checkPoint.height); 
     //draw track 
     //draw outside 
     gd.setColor(Color.LIGHT_GRAY); //set color 
     gd.fillRect(left.x, left.y, left.width, left.height); 
     gd.fillRect(right.x, right.y, right.width, right.height); 
     gd.fillRect(top.x, top.y, top.width, top.height); 
     gd.fillRect(bottom.x, bottom.y, bottom.width, bottom.height); 
     //draw inside 
     gd.fillRect(topInr.x, topInr.y, topInr.width, topInr.height); 
     gd.fillRect(bottomInr.x, bottomInr.y, bottomInr.width, bottomInr.height); 
     gd.fillRect(leftInr.x, leftInr.y, leftInr.width, leftInr.height); 
     gd.fillRect(rightInr.x, rightInr.y, rightInr.width, rightInr.height); 

     //draw car1 
     gd.setColor(Color.GREEN); // set color 
     //gd.fillRect(carOne.x, carOne.y, carOne.width, carOne.height); 
     gd.draw(carOne); 
     //draw car2 
     gd.setColor(Color.PINK); 
     //gd.fillRect(carTwo.x, carTwo.y, carTwo.width, carTwo.height); 
     gd.draw(carTwo); 
    } finally { 
     gd.dispose(); 
    } 

    g.drawImage(bufImg, 0, 0, this); 
} 

@Override 
public void update(Graphics g) { 
    paint(g); 
} 

private class moveMyCar extends Thread implements KeyListener { 
    @Override 
    public void run() { 
     addKeyListener(this); 
     while (true) { 
      try { 
       repaint(); 

       //check for collisions 
       if (carOne.intersects(left) || carOne.intersects(right) || carOne.intersects(top) || carOne.intersects(bottom) || carOne.intersects(topInr) || carOne.intersects(bottomInr) || carOne.intersects(leftInr) || carOne.intersects(rightInr)) { 
        if (cOspeed > 3.5) { 
         cOspeed = -5; 
        } 
        if (0 < cOspeed && cOspeed < 3.5) { 
         cOspeed = 1; 
        } 
       } 

       // check for laps 
       if (carOne.intersects(finishLine) && cODirection == UP && canLap == true) { 
        cOlaps++; 
        canLap = false; 
       } 
       if (carOne.intersects(checkPoint) && cODirection == DOWN) { 
        canLap = true; 
       } 

       // see if player won 
       if (cOlaps >= 3) { 
        winnerChosen = true; 
        JOptionPane.showMessageDialog(null, "Player 1 won the game!"); 
        break; 
       } 
       if (winnerChosen) { 
        break; 
       } 

       //increase speed 
       if (cOspeed <= 5) { 
        cOspeed += .2; 
       } 

       //change direction 
       if (cODirection == UP) { 
        carOne.y -= cOspeed; 
       } 
       if (cODirection == DOWN) { 
        carOne.y += cOspeed; 
       } 
       if (cODirection == LEFT) { 
        carOne.x -= cOspeed; 
       } 
       if (cODirection == RIGHT) { 
        carOne.x += cOspeed; 
       } 

       Thread.sleep(100); 

      } catch (Exception e) { 
       System.out.println("Error: " + e); 
       break; 
      } 
     } 
    } 

    public void keyPressed(KeyEvent event) { 
     if (event.getKeyChar() == ' ') { 
      if (cOspeed > -3) { 
       cOspeed -= 1; 
      } 
     } 
     System.out.println(event); 
    } 

    public void keyReleased(KeyEvent event) { 
    } 

    public void keyTyped(KeyEvent event) { 
     if (event.getKeyChar() == 'a') { 
      cODirection = LEFT; 
     } 
     if (event.getKeyChar() == 's') { 
      cODirection = DOWN; 
     } 
     if (event.getKeyChar() == 'd') { 
      cODirection = RIGHT; 
     } 
     if (event.getKeyChar() == 'w') { 
      cODirection = UP; 
     } 
    } 
} 

private class moveMyCar2 extends Thread implements KeyListener { 

    @Override 
    public void run() { 
     addKeyListener(this); 
     while (true) { 
      try { 
       repaint(); 

       //check for collisions 
       if (carTwo.intersects(left) || carTwo.intersects(right) || carTwo.intersects(top) || carTwo.intersects(bottom) || carTwo.intersects(topInr) || carTwo.intersects(bottomInr) || carTwo.intersects(leftInr) || carTwo.intersects(rightInr)) { 
        if (cTspeed > 3.5) { 
         cTspeed = -5; 
        } 
        if (0 < cTspeed && cTspeed < 3.5) { 
         cTspeed = 1; 
        } 
       } 

       // check for laps 
       if (carTwo.intersects(finishLine) && cTDirection == UP && canLapT == true) { 
        cTlaps++; 
        canLapT = false; 
       } 
       if (carTwo.intersects(checkPoint) && cTDirection == DOWN) { 
        canLapT = true; 
       } 

       // see if player won 
       if (cTlaps >= 3) { 
        winnerChosen = true; 
        JOptionPane.showMessageDialog(null, "Player 2 won the game!"); 
        break; 
       } 
       if (winnerChosen) { 
        break; 
       } 

       //increase speed 
       if (cTspeed <= 5) { 
        cTspeed += .2; 
       } 

       //change direction 
       if (cTDirection == UP) { 
        carTwo.y -= cTspeed; 
       } 
       if (cTDirection == DOWN) { 
        carTwo.y += cTspeed; 
       } 
       if (cTDirection == LEFT) { 
        carTwo.x -= cTspeed; 
       } 
       if (cTDirection == RIGHT) { 
        carTwo.x += cTspeed; 
       } 

       Thread.sleep(100); 

      } catch (Exception e) { 
       System.out.println("Error: " + e); 
       break; 
      } 
     } 
    } 

    public void keyPressed(KeyEvent event) { 
     if (event.getKeyChar() == 'm') { 
      if (cTspeed > -3) { 
       cTspeed -= 1; 
      } 
     } 
    } 

    public void keyReleased(KeyEvent event) { 
     System.out.println(event.getKeyCode()); 
    } 

    public void keyTyped(KeyEvent event) { 

     if (event.getKeyCode() == event.VK_LEFT) { 
      cTDirection = LEFT; 
     } 
     if (event.getKeyCode() == event.VK_DOWN) { 
      cTDirection = DOWN; 
     } 
     if (event.getKeyCode() == event.VK_RIGHT) { 
      cTDirection = RIGHT; 
     } 
     if (event.getKeyCode() == event.VK_UP) { 
      cTDirection = UP; 
     } 
     } 
    } 
} 

다음은 나의 코드입니다. 나는 두 가지 것을 궁금해했다. 첫째, 내가 줄에 오류가 80 행 80 :어떻게 VK_ 문제와 NullPointerException을 수정합니까?

Graphics2D gd = bufImg.createGraphics(); 

어쨌든 그것은 스레드에서 예외 "AWT-EventQueue의-0"java.lang.NullPointerException이 내가이 얻을 생각했다 궁금 해서요 그. 매번 발생하지는 않지만 때로는 발생합니다. 그렇지 않다면 어떻게 수정해야합니까?

또한 위쪽, 아래쪽, 왼쪽, 오른쪽 화살표 키에 event.VK_ 키를 사용했는데 작동하지 않습니다. 그것은 "정적 필드 접근"이라고 말합니다. 그것에 대해 어떻게해야합니까?

감사합니다.

+0

는 전체 스택 추적을 게시 할 수 현재이 같은 작업을 수행하는 방법에 대해 배울 수 있는가? – Jeremy

+0

이 줄에 NPE가 설치되어 있습니까? 그렇다면 bufImg는 null이며 ctor에 그래픽 컨텍스트를 만들 수없는 경우에만 발생할 수 있습니다. –

+0

@ Jeremy Heiler 나는 거기에 그 쓸모없는 것들을 넣었다. 당신이 알 필요가있는 것은 "NPE"입니다. 처음에는 null이기 때문에 생각하지만 그 다음에 추가 된 것들이 있습니다. 이 게임은 event.VK_ 이외의 것은 괜찮습니다. – Zeveso

답변

1

BufferedImage에서 백그라운드 페인팅을 수행 한 다음 BufferedImage를 JPanel의 paintComponent에 그립니다. painting in Swing

는 예를 들어, 이미 생성 된 코드를 사용하여 :

import java.awt.*; 
import java.awt.image.BufferedImage; 
import javax.swing.*; 

public class GameStartJPanel extends JPanel { 
    private final static int WIDTH = 400, HEIGHT = 400; 

    private final static Rectangle left = new Rectangle(0, 0, WIDTH/10, HEIGHT); 
    private final static Rectangle right = new Rectangle((WIDTH/10) * 9, 0, WIDTH/5, HEIGHT); 
    private final static Rectangle top = new Rectangle(0, 0, WIDTH, HEIGHT/8); 
    private final static Rectangle bottom = new Rectangle(0, (HEIGHT/15) * 14, WIDTH, HEIGHT/9); 

    private final static Rectangle topInr = new Rectangle((WIDTH/11) * 2, (HEIGHT/16) * 3, (WIDTH/14) * 9, 
       HEIGHT/10); 
    private final static Rectangle bottomInr = new Rectangle((WIDTH/11) * 2, (HEIGHT/16) * 12, (WIDTH/14) * 9, 
       HEIGHT/10); 
    private final static Rectangle leftInr = new Rectangle((WIDTH/11) * 2, HEIGHT/5, WIDTH/5, (HEIGHT/10) * 6); 
    private final static Rectangle rightInr = new Rectangle((WIDTH/12) * 6, (HEIGHT/20) * 7, WIDTH/2, 
       (HEIGHT/10) * 3); 
    private final static Rectangle finishLine = new Rectangle(WIDTH/10, (HEIGHT/10) * 8, WIDTH/10, HEIGHT/70); 

    private final static Rectangle checkPoint = new Rectangle((WIDTH/25) * 9, (HEIGHT/10) * 5, WIDTH/7, HEIGHT/70); 

    private final static Rectangle carOne = new Rectangle(WIDTH/8, HEIGHT/2, WIDTH/30, WIDTH/30); 
    private final static Rectangle carTwo = new Rectangle(WIDTH/9, HEIGHT/2, WIDTH/30, WIDTH/30); 

    private BufferedImage backgroundImage; 

    public GameStartJPanel() { 
     backgroundImage = createBackgroundImage(); 
     setPreferredSize(new Dimension(WIDTH, HEIGHT)); 
    } 

    private BufferedImage createBackgroundImage() { 
     BufferedImage bckgdImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); 
     Graphics2D gd = bckgdImage.createGraphics(); 
     try { 

      gd.clearRect(0, 0, WIDTH, HEIGHT); 

      gd.setColor(Color.RED); 
      gd.fillRect(finishLine.x, finishLine.y, finishLine.width, finishLine.height); 

      gd.setColor(Color.LIGHT_GRAY); 
      gd.fillRect(left.x, left.y, left.width, left.height); 
      gd.fillRect(right.x, right.y, right.width, right.height); 
      gd.fillRect(top.x, top.y, top.width, top.height); 
      gd.fillRect(bottom.x, bottom.y, bottom.width, bottom.height); 

      gd.fillRect(topInr.x, topInr.y, topInr.width, topInr.height); 
      gd.fillRect(bottomInr.x, bottomInr.y, bottomInr.width, bottomInr.height); 
      gd.fillRect(leftInr.x, leftInr.y, leftInr.width, leftInr.height); 
      gd.fillRect(rightInr.x, rightInr.y, rightInr.width, rightInr.height); 

      // do this in the paintComponent method 
      // gd.setColor(Color.GREEN); 
      // gd.draw(carOne); 
      // gd.setColor(Color.PINK); 
      // gd.draw(carTwo); 
     } finally { 
      gd.dispose(); 
     } 

     return bckgdImage; 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     if (backgroundImage != null) { 
      g.drawImage(backgroundImage, 0, 0, null); 
     } 

     Graphics2D g2 = (Graphics2D) g; 
     g.setColor(Color.GREEN); 
     g2.draw(carOne); 
     g.setColor(Color.PINK); 
     g2.draw(carTwo); 
    } 

    private static void createAndShowUI() { 
     JFrame frame = new JFrame("GameStartJPanel"); 
     frame.getContentPane().add(new GameStartJPanel()); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     java.awt.EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       createAndShowUI(); 
      } 
     }); 
    } 
} 
관련 문제