Hi guys.. I am having some problem with snake game project using JAVA Applet. I already have the sour code of a snake game from my friends, but I failed to make it functions probably under a JApplet.
I need to do a similiar UI like click a start button. then the snake game will start in a preset area. But I fail to do that as the snake game always run in a new Frame.
I am a new bird for JAVA. Is there any1 can help?
Appreciate if u guys can hep.
Thanks.
The code I have is something like this:
import java.awt.Point;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import java.awt.Container;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JApplet;
import javax.swing.JFrame;
import java.awt.geom.Point2D;
import java.util.Random;
public class Snake extends javax.swing.JApplet {
private char map[][];
private String map_2[][];
private Timer timer_snake;
private int t_delay=1000; // 200ms per timer expire event
private String map_string[] = new String[100];
private String map_matrix = "";
boolean game = false, ate=false, game2=false, playing=false;
Point[] places = new Point[374];
int size=3, hsize=0;
int dir = 0; // 0 - right
// 1 - left
// 2 - up
// 3 - down
Point apple = new Point(12,7);
/** Initializes the applet jSnake */
public void init() {
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
map = new char[50][100];
int x=0,y=0;
for (x=0; x<100; x++)
{
for (y=0; y<50; y++)
{
map[y][x] = ' ';
}
}
y = 0;
for (x=0; x<44; x++)
{
map[y][x] = '#';
}
y = 24;
for (x=0; x<44; x++)
{
map[y][x] = '#';
}
x = 1;
for (y=1; y<24; y++)
{
map[y][x] = + '#';
}
x = 98;
for (y=1; y<24; y++)
{
map[y][x] = '#';
}
timer_snake = new Timer(t_delay, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int n = 0;
map_matrix = "";
// Move snake one step forward
// (You have to be creative and write your codes here)
int a , b;
b=10;
for (a=10; a< 13; a++)
{
map[b][a] = 'S';
}
if(dir==1 )
{
for (a=12; a< 20; a++)
{
a=a+1;
map[b][a] = 'S';
int c = a - 1;
map[b][c] = ' ';
}
}
// Did the snake crash into an obstacle, including itself?
// (Write codes here)
// Converting map into a string so it can be
// displayed in JTextArea
for (int m = 0; m<25; m++)
{
// Converting one line at a time, 25 horizontal
// lines in total
map_string[m] = String.valueOf(map[m]);
map_matrix += map_string[m] + "\n";
}
area.setText(map_matrix);
}
});
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private void startbuttonActionPerformed(java.awt.event.ActionEvent evt)
{
timer_snake.start();
}
// Variables declaration - do not modify
private javax.swing.JTextArea area;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton startbutton;
// End of variables declaration
}
-------------------------------------------------------------------------
//until here is what the lecturer provided. He hope e follow this way to get the game start.
//below is what my friend done for me. But i fail to apply into the main program. Need your guys help
-----------------------------------------------------------------------------
class engin {
/** Creates a new instance of engin */
public engin()
{
}
public void Move_mySnake(int newDirection,boolean food_eaten)
{
if(!Game_Over)
{
switch(newDirection)
{
case 1: if(direction!=3)
{
my_snake.put_Head_postion(0,-step_to_move);
direction=1;
}
else move_as_last(direction);
break;//UP
case 2: if(direction!=4)
{
my_snake.put_Head_postion(step_to_move,0);
direction=2;
}
else move_as_last(direction);
break;//RIGHT
case 3:
if(direction!=1)
{
my_snake.put_Head_postion(0,step_to_move);
direction=3;
}
else move_as_last(direction);
break;//DOWN
case 4:
if(direction!=2)
{
my_snake.put_Head_postion(-step_to_move,0);
direction=4;
}
else move_as_last(direction);
break;//LEFT
}
if(food_eaten)
{
my_snake.Increase_lenght();// IF the Snake ate new Food
}
my_snake.Move_snake();
if((my_snake.getHeadX()==snakeFood.get_int_X())&&(my_snake.getHeadY()== snakeFood.get_int_Y()))
{
snakeFood.getFood();
Score+=20;
my_snake.Increase_lenght();
while(check_food_place())
{
snakeFood.getFood();
}
}
Game_Over=my_snake.check_game_over();
}
if(Game_Over)
{
JOptionPane.showConfirmDialog(null,"Score = "+Integer.toString(Score),"Your Score",JOptionPane.DEFAULT_OPTION);
// Thread.yield();
}
}
public void move_as_last(int diirec)
{
switch(direction)
{
case 1:
my_snake.put_Head_postion(0,-step_to_move);
break;//UP
case 2:
my_snake.put_Head_postion(step_to_move,0);
break;//RIGHT
case 3:
my_snake.put_Head_postion(0,step_to_move);
break;//DOWN
case 4:
my_snake.put_Head_postion(-step_to_move,0);
break;//LEFT
}
}
public int[] return_Snake_postionsX()
{
return my_snake.get_All_postionsX();
}
public int[] return_Snake_postionsY()
{
return my_snake.get_All_postionsY();
}
public int get_Oval_size()
{
return my_snake.getOval_Size();
}
public int get_my_snake_lenght()
{
return my_snake.get_lenght();
}
public void set_step_length()
{
step_to_move=5;
}
public int get_Food_X()
{
return (int)snakeFood.getX();
}
public int get_Food_Y()
{
return (int)snakeFood.getY();
}
public boolean check_food_place()
{
int xfood=(int)snakeFood.getX();
int yfood=(int)snakeFood.getY();
if(xfood>260||yfood>260)return true;
else
return my_snake.compare_with_foodPostion(xfood,yfood);
}
public boolean get_Game_over()
{
return Game_Over;
}
private int direction=2;
private boolean Game_Over;
private boolean Moving_vertical=false;
private snake my_snake=new snake();
private final Food snakeFood=new Food();
private int step_to_move=20;
private int Score;
}
class MainFrame extends JApplet implements KeyListener{
/** Creates a new instance of MainFrame */
public void init() {
setSize(540,540);
Container cpane=getContentPane();
cpane.add(snakePanel);
addKeyListener(this);
}
/**
* @param args the command line arguments
*
*/
public static void main(String[] args) {
// TODO code application logic here
MainFrame my_Game=new MainFrame();
JFrame myFrame=new JFrame(" Simple Snake Game ");
myFrame.setSize(300,300);
myFrame.getContentPane().add(my_Game);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.addKeyListener(my_Game);
my_Game.init();
my_Game.start();
my_Game.setVisible(true);
myFrame.setVisible(true);
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==UP) {
snakePanel.set_Direction(1);
} else if (e.getKeyCode()==RIGHT) {
snakePanel.set_Direction(2);
} else if(e.getKeyCode()==DOWN) {
snakePanel.set_Direction(3);
} else if(e.getKeyCode()==LEFT) {
snakePanel.set_Direction(4);
}
}
public void keyReleased(KeyEvent e) {
}
private final int LEFT = 37;
private final int RIGHT = 39;
private final int UP = 38;
private final int DOWN = 40;
private myPanel snakePanel=new myPanel();
}
class myPanel extends JPanel {
/** Creates a new instance of myPanel */
public myPanel() {
setBorder(my_border);
// mythread.setPriority(1);
mythread.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D=(Graphics2D)g;
g2D.setColor(Color.BLUE);
/* g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2D.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);*/
Parts_X=my_engin.return_Snake_postionsX();
Parts_Y=my_engin.return_Snake_postionsY();
for(int i=0;i<my_engin.get_my_snake_lenght();i++) {
g2D.fillRect(Parts_X[i],Parts_Y[i],my_Oval_size,my_Oval_size);
}
g2D.setColor(Color.RED);
g2D.fillOval(my_engin.get_Food_X()+5,my_engin.get_Food_Y()+5,my_Oval_size-5,my_Oval_size-5);
}
class MY_Thread extends Thread {
public void run() {
while(true) {
my_engin.Move_mySnake(direction,false);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
repaint();
if(my_engin.get_Game_over()) {
stop();
}
}
}
}
public void set_Direction(int newDirection) {
direction=newDirection;
}
private engin my_engin=new engin();
private int Parts_X[];
private int Parts_Y[];
private int direction=2;
private boolean is_my_first_moves=true;
private final MY_Thread mythread=new MY_Thread();
private final int my_Oval_size=my_engin.get_Oval_size();
private final int LEFT = 37;
private final int RIGHT = 39;
private final int UP = 38;
private final int DOWN = 40;
private LineBorder my_border=new LineBorder(Color.green.darker(),3);
}
class snake {
/** Creates a new instance of snake */
public snake() {
for(int i=0;i<snake_length;i++) {
PostionsX[i]=20;
PostionsY[i]=20;
}
}
public void Move_snake() {
for(int i=0;i<snake_length;i++) {
PostionsX[snake_length-i]=PostionsX[snake_length-(i+1)];
PostionsY[snake_length-i]=PostionsY[snake_length-(i+1)];
}
PostionsX[0]=headX;
PostionsY[0]=headY;
}
public void put_Head_postion(int x,int y) {
headX+=x;
headY+=y;
}
public boolean check_game_over() {
for(int i=1;i<snake_length;i++)
{
if((PostionsX[i]==headX)&&(PostionsY[i]==headY)) {
return true;
}
}
if(headX<0||headX>260||headY<0||headY>260) {
return true;
}
return false;
}
public boolean compare_with_foodPostion(int x,int y) {
for(int i=0;i<snake_length;i++) {
if(x==PostionsX[i]&&y==PostionsY[i]) {
return true;
}
}
return false;
}
public synchronized void Increase_lenght() {
snake_length++;
}
public int get_lenght() {
return snake_length;
}
public int getOval_Size() {
return Oval_size;
}
public int[] get_All_postionsX() {
return PostionsX;
}
public int[] get_All_postionsY() {
return PostionsY;
}
public int getHeadX() {
return PostionsX[0];
}
public int getHeadY() {
return PostionsY[0];
}
private int headX=20;
private int headY=20;
private int[] PostionsX=new int[300];
private int[] PostionsY=new int[300];
private int snake_length=5;
private final int Oval_size=20;
}
class Food {
/** Creates a new instance of Food */
public Food() {
Food_Postion.setLocation((((int)((Math.random()*(100)))%20)*20),((((int)(Math.random()*(10)))%20)*20));
int x=(int)Food_Postion.getX();
int y=(int)Food_Postion.getY();
while(x>260||y>260) {
Food_Postion.setLocation((((int)((Math.random()*(100)))%20)*20),((((int)(Math.random()*(10)))%20)*20));
x=(int)Food_Postion.getX();
y=(int)Food_Postion.getY();
}
}
public void getFood() {
// Food_Postion.setLocation((((int)(Food_Generator.nextInt(20)*(100)))%20)*20,((((int)(Food_Generator.nextInt(100)*(10)))%20)*20));
Food_Postion.setLocation((((int)((Math.random()*(100)))%20)*20),((((int)(Math.random()*(10)))%20)*20));
}
public double getX() {
return Food_Postion.getX();
}
public double getY() {
return Food_Postion.getY();
}
public int get_int_X() {
return (int)Food_Postion.x;
}
public int get_int_Y() {
return (int)Food_Postion.y;
}
Point2D.Float Food_Postion=new Point2D.Float();
Random Food_Generator=new Random();
}