0

Really need help!!! wondering how i could change my applet into a JFrame. Im not liking the applet the guy used in his tutorial and i would like to switch to a JFrame. I am very new to java and yes i have very little knowledge. Any help would be greatly appreciated! The game is a snake game.

TUTORIAL: https://www.youtube.com/watch?v=FABTl1Q1byw

APPLET CLASS:

import java.applet.Applet;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Color;

public class snakeApplet extends Applet{

  private SnakeCanvas c;//410x310

    public void init(){
    c = new SnakeCanvas();
    c.setPreferredSize(new Dimension(410, 310));
    c.setVisible(true);
    c.setFocusable(true);
    this.add(c);
    this.setVisible(true);
    this.setSize(new Dimension(410, 310));

 }

 public void paint(Graphics g){
  this.setSize(new Dimension(410, 310));
 }
 }

GAME CLASS:

public class SnakeCanvas extends Canvas implements Runnable, KeyListener{
private final int BOX_HEIGHT = 10;
private final int BOX_WIDTH = 10;
private final int GRID_WIDTH = 25;
private final int GRID_HEIGHT = 25;

private LinkedList<Point> snake;
private Point fruit;
private int direction = Direction.NO_DIRECTION;

private Thread runThread;
private int score = 0;
private String highscore = "";

public void init() {

}

public void paint(Graphics g) {
    if (snake == null) {
        snake = new LinkedList<Point>();
        GenerateDefaultSnake();
        PlaceFruit();
    }

if (runThread == null) {
    this.setPreferredSize(new Dimension(640, 480));
    this.addKeyListener(this);
    runThread = new Thread(this);
    runThread.start();
}

if (highscore.equals("")) {
    highscore = this.GetHighScore();
}

drawFruit(g);
drawGrid(g);
drawSnake(g);
drawScore(g);

}

public void update(Graphics g) {
Graphics offScreenGraphics; //Graphics used to draw offscreen
BufferedImage offscreen = null;
Dimension d = this.getSize();

offscreen = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_ARGB);
offScreenGraphics = offscreen.getGraphics();
offScreenGraphics.setColor(this.getBackground());//CHANGE BACKGROUND COLOR
offScreenGraphics.fillRect(0, 0, d.width, d.height);
offScreenGraphics.setColor(this.getForeground());
paint(offScreenGraphics);

//flip
g.drawImage(offscreen, 0, 0, this);
}

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.NO_DIRECTION;

}


public void Move() {
Point head = snake.peekFirst();
Point newPoint = head;
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.remove(snake.peekLast());

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

 //if we reach this point in code, we're still alive
 snake.push(newPoint);
 }

 public void drawScore(Graphics g){
 g.drawString("Score: " + score, 0, BOX_HEIGHT * GRID_HEIGHT + 10);
 g.drawString("HighScore: " + highscore, 0, BOX_HEIGHT * GRID_HEIGHT + 20);
 }

 public void CheckScore(){
 if(highscore.equals(""))
 return;

 if(score > Integer.parseInt((highscore.split(":")[1]))){
 String name = JOptionPane.showInputDialog("NEW HIGHSCORE! PLEASE ENTER YOUR NAME.");
 highscore = name + ":" + score;

 File scoreFile = new File("highscore.dat");
 if(!scoreFile.exists()){
 try{
 scoreFile.createNewFile();
 }
 catch(Exception e){
 e.printStackTrace();
 }
 }
 FileWriter writeFile = null;
 BufferedWriter writer = null;
 try{
 writeFile = new FileWriter(scoreFile);
 writer = new BufferedWriter(writeFile);
 writer.write(this.highscore);
 }
 catch(Exception e){
 }
 finally{
 try{
 if(writer !=null)
  writer.close();
 }
 catch(Exception e){}
 }
 }
 }



 public void drawGrid(Graphics g){
 //drawing an outside rectangle
 g.drawRect(0, 0, GRID_WIDTH * BOX_WIDTH, GRID_HEIGHT * BOX_HEIGHT);

}

public void drawSnake(Graphics g){
g.setColor(Color.GREEN);
for (Point p: snake){
g.fillRect(p.x * BOX_WIDTH, p.y * BOX_HEIGHT, BOX_WIDTH, BOX_HEIGHT);
}
g.setColor(Color.BLACK);
}

public void drawFruit(Graphics g){
g.setColor(Color.RED);
g.fillOval(fruit.x * BOX_WIDTH, fruit.y * BOX_HEIGHT, BOX_WIDTH, BOX_HEIGHT);
g.setColor(Color.BLACK);
}


public void PlaceFruit(){
Random rand = new Random();
int randomX = rand.nextInt(GRID_WIDTH);
int randomY = rand.nextInt(GRID_HEIGHT);
Point randomPoint = new Point(randomX, randomY);
while(snake.contains(randomPoint)){
randomX = rand.nextInt(GRID_WIDTH);
randomY = rand.nextInt(GRID_HEIGHT);
randomPoint = new Point (randomX, randomY);
}
fruit = randomPoint; 
}

@Override
public void run(){
while(true){//runs indefinitely
Move();
repaint();

try{
Thread.currentThread();
Thread.sleep(100);
}
catch(Exception e){
e.printStackTrace();
}
}

}

public String GetHighScore(){ 

FileReader readFile = null;
BufferedReader reader = null; 

try{
readFile = new FileReader("highscore.dat");
reader = new BufferedReader(readFile);
return reader.readLine();
}
catch(Exception e){
return "Nobody:0";
}

finally{
try{
if(reader != null)
reader.close();
}
catch(Exception e){
e.printStackTrace();
}
}

}

@Override
public void keyTyped(KeyEvent e){
//TODO Auto-generated method stub

}

@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;

} 
}

@Override
public void keyReleased(KeyEvent e){

}



}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 1
    Have you looked at making a [hybrid](http://stackoverflow.com/q/12449889/230513)? – trashgod Jun 15 '14 at 17:52
  • like making the applet run in a JFrame? would love to know how –  Jun 15 '14 at 17:59
  • @Pasoon: Actually the code that you pasted here, doesn't belongs to `Swing`, it belongs to `AWT`. So why the question is tagged with `Swing`? – nIcE cOw Jun 15 '14 at 18:08
  • 1
    mistake... but what does that have to do with my question? –  Jun 15 '14 at 18:16
  • @Pasoon Please don't make such radical edits to your question, if you have a new question (i.e. how to add sound to a game) - please *ask another* question. – Elliott Frisch Jun 16 '14 at 01:42
  • @Pasoon: I pointed that out for a reason, since, now as suggested in the answer, you be mixing both `Swing` and `AWT` components together(JFrame - Canvas), which is not a good practice. Moreover, in the code, KeyListeners are used, when [KeyBinding](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html), is to be used. `paint()` method is used, instead `paintComponent()` should be used, these are some of the thingies I can see in a quick review. IMHO, I doubt, where this accepted answer will take you. – nIcE cOw Jun 16 '14 at 03:34

1 Answers1

1

I think the easiest solution is make snakeApplet a JFrame.

public class SnakeFrame extends JFrame {
  private static final long serialVersionUID = 1L;
  private SnakeCanvas c;// 410x310

  public SnakeFrame() {
    c = new SnakeCanvas();
    c.setPreferredSize(new Dimension(410, 310));
    c.setVisible(true);
    c.setFocusable(true);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.add(c);
  }

  public static void main(String[] args) {
    Runnable doRun = new Runnable() {
      @Override
      public void run() {
        SnakeFrame sf = new SnakeFrame();
        sf.setSize(new Dimension(410, 310));
        sf.setVisible(true);
      }
    };
    new Thread(doRun).start();
  }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249