2014-04-16 4 views
0

내 프로그래밍 클래스에 간단한 뱀 게임을 다시 만들려고합니다. 나는 이클립스 Eclipse에서 java를 사용하고있다. 당신이이 게임을하는 법을 모른다면, 뱀이 점을 먹을 때, 뱀이 자랄 때 게임이 끝나고 게임이 끝난 게임입니다. 어떤 도움을 많이 주시면 감사하겠습니다! 사용자가 만든 새로운 점은 현재 뱀의 내부에 항상 있기 때문에뱀 게임 문제, 뱀이 움직이지 않는다

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.Point; 
import java.awt.event.KeyEvent; 
import java.awt.event.KeyListener; 
import java.awt.image.BufferedImage; 
import java.util.LinkedList; 
import java.util.Random; 
import javax.swing.JFrame; 
public class Source extends JFrame implements Runnable, KeyListener { 
private final int boxHeight = 15; //each individual box height 
private final int boxWidth = 15; //each individual box width 
private final int gridWidth = 25; //Total width of all boxes in Grid 
private final int gridHeight = 25; //Total height of all boxes in Grid 
JFrame frame = new JFrame(); 
private LinkedList<Point> snake; 
public Point fruit; 
public int direction = Direction.noDirection; 
private Thread runThread; 
private Graphics globalGraphics; 
private int score = 0; 


public void paint (Graphics g) 
{ 
    setBounds(0,0,500,500); 
    snake = new LinkedList<Point>(); 
    GenerateDefaultSnake(); 
    PlaceFruit(); 
    globalGraphics = g.create(); 
    this.addKeyListener(this); 
    if (runThread == null){ 
     runThread = new Thread(this); 
     runThread.start(); 
    } 
} 
public void GenerateDefaultSnake(){ 

    score = 0; 
    snake.clear(); 
    snake.add(new Point (0,2)); 
    snake.add(new Point (0,1)); 
    snake.add(new Point (0,0)); 
    direction = Direction.noDirection; 
} 

public void Draw (Graphics g){ //main method of what will be drawn 
    g.clearRect(0, 0, boxWidth * gridWidth + 10, boxHeight * gridHeight +20); 
    //create a new image 
    BufferedImage buffer = new BufferedImage(boxWidth * gridWidth + 10, boxHeight * gridHeight +20, BufferedImage.TYPE_INT_ARGB); 
    Graphics bufferGraphics = buffer.getGraphics(); 

    DrawFruit(bufferGraphics); 
    DrawGrid(bufferGraphics); 
    DrawSnake(bufferGraphics); 
    DrawScore(bufferGraphics); 


    //flip 
    g.drawImage(buffer, 0,0, boxWidth * gridWidth +10, boxHeight * gridHeight +20, this); 

} 
public void Move(){ //directions 
    Point head = snake.peekFirst(); //head of snake, allows us to have body follow in chronological order 
    Point newPoint = head; 

    snake.remove(snake.peekLast()); //removes end of tail 
    if(newPoint.equals(fruit)) 
    { 
     score += 10; 
     Point addPoint = (Point) newPoint.clone(); 
     //the snake has hit the fruit 
     switch(direction){ 
     case Direction.North: 
      newPoint = new Point (head.x, head.y -1); 
      break; 
     case Direction.South: 
      newPoint = new Point(head.x,head.y +1); 
      break; 
     case Direction.West: 
      newPoint = new Point(head.x -1,head.y); 
      break; 
     case Direction.East: 
      newPoint = new Point(head.x + 1,head.y); 
      break; 
     } 
     snake.push(addPoint); 
     PlaceFruit(); 
    } 
    else if (newPoint.x < 0 || newPoint.x > (gridWidth - 1)){ 
     //we went out of bounds, reset game 
     GenerateDefaultSnake(); 
     return; 
    } 
    else if (newPoint.y < 0 || newPoint.y > (gridHeight - 1)){ 
     //we went out of bounds, reset game 
     GenerateDefaultSnake(); 
     return; 
    } 
    else if (snake.contains(newPoint)){ 
     //we ran into ourselves, reset game 

     GenerateDefaultSnake(); 
     return; 
    } 
    //if we reach this point of the game, we are still good 
    snake.push(newPoint); //pushes all points one point ahead when you eat fruit and adds fruit that you ate at the end 
} 

public void DrawScore(Graphics g){ 
    g.drawString("Score: " + score,0, boxHeight * gridHeight +10); 
} 
public void DrawGrid (Graphics g){ 
    //drawing outer rectangle 
    g.drawRect(0,0, gridWidth * boxWidth, gridHeight * boxHeight); //creates the outer rectangle 
    //drawing vertical lines of grid 
    for (int x = boxWidth; x < gridWidth * boxWidth; x += boxWidth){ 
     g.drawLine(x, 0, x, boxHeight * gridHeight); 
    } 
    //drawing horizontal lines of grid 
    for(int y = boxHeight; y < gridHeight * boxHeight; y += boxHeight){ 
     g.drawLine(0, y, gridWidth * boxWidth, y); 
    } 
} 
public void DrawSnake(Graphics g){ 
    g.setColor(Color.GREEN); 
    for (Point p : snake){ 
     g.fillRect(p.x * boxWidth, p.y * boxHeight, boxWidth, boxHeight); 
    } 
    g.setColor(Color.BLACK); 
} 
public void DrawFruit(Graphics g){ 
    g.setColor(Color.RED); 
    g.fillOval(fruit.x * boxWidth, fruit.y * boxHeight, boxWidth, boxHeight); 
    g.setColor(Color.BLACK); 
} 
public void PlaceFruit() 
{ 
    Random rand = new Random(); 
    int randomX = rand.nextInt(gridWidth); 
    int randomY = rand.nextInt(gridHeight); 
    Point randomPoint = new Point(randomX, randomY); 
    while (snake.contains(randomPoint)){ 
     randomX = rand.nextInt(gridWidth); 
     randomY = rand.nextInt(gridHeight); 
     randomPoint = new Point(randomX, randomY); 
    } 
    fruit = randomPoint; 

} 
public void run() { 
    while(true){ 
     //runs indefinitely, every second the objects in this loop will move 
     Move(); 
     Draw(globalGraphics); 
     try{ 
      Thread.currentThread(); 
      Thread.sleep(100); //game will be updating itself every tenth of a second (.1 of a second) 
     } 
     catch (Exception e){ 
      e.printStackTrace(); 
     } 
    } 
} 
@Override 
public void keyPressed(KeyEvent e) { 
    switch (e.getKeyCode()) 
    { 
    case KeyEvent.VK_UP: 
     if(direction != Direction.South) 
      direction = Direction.North; 
      break; 

    case KeyEvent.VK_DOWN: 
     if(direction != Direction.North) 
     direction = Direction.South; 
     break; 
    case KeyEvent.VK_RIGHT: 
     if(direction != Direction.West) 
     direction = Direction.East; 
     break; 
    case KeyEvent.VK_LEFT: 
     if(direction != Direction.East) 
     direction = Direction.West; 
     break; 
    } 
} 
    public class Direction { 
public static final int noDirection = 0; 
public static final int North = 1; 
public static final int South = 2; 
public static final int West = 3; 
public static final int East = 4; 
    } 
    public class Snake extends JFrame{ 



    c = new Source(); 
    c.setPreferredSize(new Dimension (640,480)); 
    c.setVisible(true); 
    c.setFocusable(true); 
    } 
    @Override 
    public void keyReleased(KeyEvent arg0) { 
// TODO Auto-generated method stub 
    } 
    @Override 
    public void keyTyped(KeyEvent arg0) { 
// TODO Auto-generated method stub 
    } 
    }* 
+2

뱀이 움직이는 부분은 무엇입니까? – CodeCamper

+0

호기심에서 벗어나서 어떻게 시작하나요? (당신과 똑같은 방법으로 테스트 할 수 있습니다). – user3507600

+0

코드의 public void Move() 부분은 뱀이 움직이게하기로되어 있습니다. 나는 문제가 @CodeCamper – user3542369

답변

1

문제는 당신 move() 방법, 당신은 항상 마지막 경우 (else if (snake.contains(newPoint)))에 실패합니다.

나는 해결책을 찾고 있습니다.

편집 :

이 부분은 잘못된 것입니다 :

if(newPoint.equals(fruit)) 
{ 
    score += 10; 
    Point addPoint = (Point) newPoint.clone(); 
    //the snake has hit the fruit 
    switch(direction){ 
    case Direction.North: 
     newPoint = new Point (head.x, head.y -1); 
     break; 
    case Direction.South: 
     newPoint = new Point(head.x,head.y +1); 
     break; 
    case Direction.West: 
     newPoint = new Point(head.x -1,head.y); 
     break; 
    case Direction.East: 
     newPoint = new Point(head.x + 1,head.y); 
     break; 
    } 
    snake.push(addPoint); 
    PlaceFruit(); 
} 

편집 2 : 머리가 나쁜 상자는 점 addPoint이 열매를 타격하기위한 점검해야한다는 권리입니다. 과일을 조금 더 잘 처리 할 논리를 추가했습니다.

public void Move(){ //directions 

    Point head = snake.peekFirst(); //head of snake, allows us to have body follow in chronological order 
    Point newPoint = head; 

    snake.remove(snake.peekLast()); //removes end of tail 


    Point addPoint = (Point) newPoint.clone(); 
    switch(direction) { 
    case Direction.North: 
     newPoint = new Point (head.x, head.y -1); 
     break; 
    case Direction.South: 
     newPoint = new Point(head.x,head.y +1); 
     break; 
    case Direction.West: 
     newPoint = new Point(head.x -1,head.y); 
     break; 
    case Direction.East: 
     newPoint = new Point(head.x + 1,head.y); 
     break; 
    } 

    //the snake has hit the fruit 
    if(newPoint.equals(fruit)) 
    { 
     score += 10; 
     fruit = null; 
     snake.push(addPoint); 
    } 
    else if (newPoint.x < 0 || newPoint.x > (gridWidth - 1)){ 
     //we went out of bounds, reset game 
     GenerateDefaultSnake(); 
     return; 
    } 
    else if (newPoint.y < 0 || newPoint.y > (gridHeight - 1)){ 
     //we went out of bounds, reset game 
     GenerateDefaultSnake(); 
     return; 
    } 
    else if (snake.contains(newPoint)){ 
     //we ran into ourselves, reset game 
     GenerateDefaultSnake(); 
     return; 
    } 

    //if we reach this point of the game, we are still good 
    PlaceFruit(); 
    snake.push(newPoint); //pushes all points one point ahead when you eat fruit and adds fruit that you ate at the end 
} 

그뿐만 아니라, 당신의 PlaceFruit() 방법의 첫 번째 라인으로 if (fruit != null) return;을 추가합니다.

+0

도움을 주셔서 감사합니다. 코드를 변경했지만 뱀이 움직이지 않는 것처럼 보입니다. 어떤 제안? @ user3507600 – user3542369

+0

@ user3542369 버튼을 눌렀을 것으로 추측합니까? 시작 방향을 지정하지 않으므로 화살표 키를 누를 때까지 이동하지 않습니다. – user3507600

+0

문제가 발생했습니다. 게임을 시작했을 때 게임 중간에 점이 나타나지 않는 경우가있었습니다. 나는 그것이 뱀이 이미있는 곳으로 점이 재배치되기 때문에 그것이 실제로 추측되기 전에 뱀이 그것을 "먹는다"고 생각합니다. 또 다른 점은 나타나지 않습니다. 그리고 나서 우리는 단지 뱀으로 남았습니다. 어떤 해결책? 나는 이것이 PlaceFruit() 메소드의 문제점이라고 생각한다. @ user3507600 – user3542369

0

뱀이 움직이게하는 코드는 약간 잘못되었습니다. 당신은 항상 움직여야하고 뱀이 그것에 들어가면 점수를 더하고 과일 만 다시 만듭니다. 아래 참조 :

public void Move(){ //directions 

    Point head = snake.peekFirst(); //head of snake, allows us to have body follow in chronological order 
    Point newPoint = head; 

    snake.remove(snake.peekLast()); //removes end of tail 


    Point addPoint = (Point) newPoint.clone(); 
    switch(direction) { 
    case Direction.North: 
     newPoint = new Point (head.x, head.y -1); 
     break; 
    case Direction.South: 
     newPoint = new Point(head.x,head.y +1); 
     break; 
    case Direction.West: 
     newPoint = new Point(head.x -1,head.y); 
     break; 
    case Direction.East: 
     newPoint = new Point(head.x + 1,head.y); 
     break; 
    } 

    //the snake has hit the fruit 
    if(newPoint.equals(fruit)) 
    { 
     score += 10; 
     snake.push(addPoint); 
     PlaceFruit(); 
    } 
    else if (newPoint.x < 0 || newPoint.x > (gridWidth - 1)){ 
     //we went out of bounds, reset game 
     GenerateDefaultSnake(); 
     PlaceFruit(); 
     return; 
    } 
    else if (newPoint.y < 0 || newPoint.y > (gridHeight - 1)){ 
     //we went out of bounds, reset game 
     GenerateDefaultSnake(); 
     PlaceFruit(); 
     return; 
    } 
    else if (snake.contains(newPoint)){ 
     //we ran into ourselves, reset game 
     GenerateDefaultSnake(); 
     PlaceFruit(); 
     return; 
    } 

    //if we reach this point of the game, we are still good 
    snake.push(newPoint); //pushes all points one point ahead when you eat fruit and adds fruit that you ate at the end 
} 
+0

뱀이 지금 움직입니다!지금은 과일을 먹으면 다른 과일은 나오지 않습니다. – user3542369

+0

나는 이미 그 사실을 알아 채고 그것을 고치기 위해 편집을하고있었습니다. :) –

+0

신경 쓰지 마라, 그것은 기능적으로 완벽하다! 정말 고맙습니다! – user3542369