Showing posts with label Snake. Show all posts
Showing posts with label Snake. Show all posts

Wednesday, 18 April 2012

Snake Game in Java

screen.java is using for fullscreen game develpment

import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
//import java.lang.reflect.InvocationTargetException;
import javax.swing.JFrame;
public class screen {

 private GraphicsDevice vc;
 
 //give vc access to monitor screen
 //Constructor
 public screen(){
  
  GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
  vc = e.getDefaultScreenDevice();
  
 }
 //get all compatible DM
 public DisplayMode[] getCompatibleDisplayModes(){
  return vc.getDisplayModes();
 }
 
 //compares DM passed in to vc DM and see if they matchs
 public DisplayMode findFirstCompatibleMode(DisplayMode modes[]){
  
  DisplayMode goodModes[] = vc.getDisplayModes();
  for(int x=0;x<modes.length;x++){
   for(int y=0;y<goodModes.length;y++){
    if(displayModesMatch(modes[x],goodModes[y])){
     return modes[x];
    }
   }
  }
  return null;
 }
 //get current DM 
 public DisplayMode getCurrentDisplayMode(){
  return vc.getDisplayMode();
 }
 
 //check if two modes match each other
 public boolean displayModesMatch(DisplayMode m1,DisplayMode m2){
  if(m1.getWidth() != m2.getWidth() || m1.getHeight() != m2.getHeight())
    return false;
  
  if(m1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI  && m2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m1.getBitDepth() != m2.getBitDepth())
   return false;
  
  if(m1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m1.getRefreshRate() != m2.getRefreshRate())
   return false;
  return true;
 }
 
 //make frame full screen
 public void setFullScreen(DisplayMode dm){
  JFrame f = new JFrame();
  f.setUndecorated(true);
  f.setIgnoreRepaint(true);
  f.setResizable(false);
  vc.setFullScreenWindow(f);
  
  if(dm != null && vc.isDisplayChangeSupported()){
   try{
    vc.setDisplayMode(dm);
   }catch(Exception ex){} 
  }
  f.createBufferStrategy(2);
 }
 //we will set graphics object equal to this
 public Graphics2D getGraphics(){
  
  Window w = vc.getFullScreenWindow();
  if(w != null){
   BufferStrategy s = w.getBufferStrategy();
   return (Graphics2D)s.getDrawGraphics();
  }else{
   return null;
  }
  
 }
 //update display
 public void update(){
  Window w =vc.getFullScreenWindow();
  if(w != null){
   BufferStrategy s = w.getBufferStrategy();
   if(!s.contentsLost()){
    s.show();
   }
  }
 }
 //return full screen window
 public Window getFullScreenWindow(){
  return vc.getFullScreenWindow();
 }
 //get witdh of window
 public int getWidth(){
  Window w = vc.getFullScreenWindow();
  if(w != null)
   return w.getWidth();
  else 
   return 0;
 }
 
 
 //get height of window
 public int getHeight(){
   Window w = vc.getFullScreenWindow();
   if(w != null)
    return w.getHeight();
   else 
    return 0;
 }
 // get out of fullscreen
 public void restoreScreen(){
  Window w = vc.getFullScreenWindow();
  if(w != null)
   w.dispose();
  vc.setFullScreenWindow(null);
 }
 
 //create image compatible with monitor
 public BufferedImage createCompatibleImage(int w,int h,int t){
  Window win =vc.getFullScreenWindow();
  if(win != null){
   GraphicsConfiguration gc = win.getGraphicsConfiguration();
   return gc.createCompatibleImage(w,h,t);
  }
  return null;
 }
 
}

Snake Game in Java

engerekcore.java is need to run game


import java.awt.*;
//import javax.swing.*;

public abstract class engerekcore extends engerek{
 
 //ekran modları
 private static DisplayMode modes[] = {
  new DisplayMode(800,600,32,0),
  new DisplayMode(800,600,24,0),
  new DisplayMode(800,600,16,0),
  new DisplayMode(640,480,32,0),
  new DisplayMode(640,480,24,0),
  new DisplayMode(640,480,16,0),
 };
 private boolean running;
 protected screen s;
 
 //stop method
 public void stop(){
  running = false;
 }
 
 //call init and gameloop
 public void run(){
  try{
   init();
   start();
   gameLoop();
  }finally{
   s.restoreScreen();
  }
 }
 //set to full screen
 public void init(){
  s = new screen();
  DisplayMode dm = s.findFirstCompatibleMode(modes);
  s.setFullScreen(dm);
  
  Window w = s.getFullScreenWindow();
  w.setFont(new Font("Arial",Font.PLAIN,20));
  w.setBackground(Color.white);
  w.setForeground(Color.black);
  running = true;
 }
 //main gameLoop
 public void gameLoop(){
  long startTime = System.currentTimeMillis();
  long cumTime = startTime;
  
  while(running){
   Graphics2D g = s.getGraphics();
   long timePassed = System.currentTimeMillis() - cumTime;
   cumTime += timePassed;
   if(pause==false){
    if(lost!=false){
     try{
     draw2(g);
     g.dispose();
     
     if(continued){
     collision();
     s.update();
     continued = false;
     continue;
     }
     }catch(Exception ex){}
    }else
     update(timePassed);
     draw(g);
     g.dispose();
     s.update();
   }else{
    try{
     draw3(g);
     g.dispose();
     s.update();
     if(becontinue){
     continue;
     }
    }catch(Exception ex){}
   }
   
   try{
    Thread.sleep(20);
 
   }catch(Exception ex){}
   
  }
 }
 //update snake move
 public void update(long timePassed){
  lastmove += timePassed;
  if(lastmove>movedelay){
   snakeupdate();
   if(growup==true){
   seedupdate();
   growup = false;
   }
   lastmove = 0;
  }
 }
 //draw game screen
 public abstract void draw(Graphics2D g);
 //draw lost screen
 public abstract void draw2(Graphics2D g);
 //draw pause screen
 public abstract void draw3(Graphics2D g);
}


Wednesday, 11 April 2012

Snake Game in Java

keyinputs.class is to use keylistener and keybord inputs

import java.awt.event.*;
import java.awt.*;
public class keyinputs extends engerekcore implements KeyListener{
 public static void main(String[] args){
  new keyinputs().run();
 }
 
 
 public String tostring(int a){
  return mess+""+a;
 }
 public String tostring2(int a){
  return mess3+""+a;
 }
 public int getsonrakiyon(){
  return sonrakiyon;
 }
 public void init(){
  super.init();
  Window w = s.getFullScreenWindow();
  w.setFocusTraversalKeysEnabled(false);
  w.addKeyListener(this);
 }
 
 //keypressed
 public void keyPressed(KeyEvent e){
  int keyCode = e.getKeyCode();
  
  if(keyCode == KeyEvent.VK_ENTER){//to stop //oyunu durdurur
   pause = true;
   becontinue = false;
  }
  if(keyCode == KeyEvent.VK_SPACE){
   pause = false;
   becontinue = true;
  } 
  if(keyCode == KeyEvent.VK_BACK_SPACE)
   continued = true;
  if(keyCode == KeyEvent.VK_ESCAPE){//to exit //oyundan çıkar
   stop();
  }else{
   yon = sonrakiyon;
   if(keyCode == KeyEvent.VK_W)
    if(yon!=kuzey && yon!=guney)
    sonrakiyon = kuzey;
   if(keyCode == KeyEvent.VK_S)
    if(yon!=guney && yon!=kuzey)
    sonrakiyon = guney;
   if(keyCode == KeyEvent.VK_A)
    if(yon!=bati && yon!=dogu)
    sonrakiyon = bati;
   if(keyCode == KeyEvent.VK_D)
    if(yon!=dogu && yon!=bati)
    sonrakiyon = dogu;
   e.consume();
  }
 }
 
 //keyReleased
 public void keyReleased(KeyEvent e){
  e.consume();
 }
 
 //last method from interface
 public void keyTyped(KeyEvent e){
  e.consume();
 }
 //engerekcoredaki draw metoduyla eş zamanlı çalışır//run in the same time with draw method in engerekcore  
 public synchronized void draw(Graphics2D g){
  
  Window w = s.getFullScreenWindow();//tam ekrana geçiş
  g.setColor(w.getBackground());//arka ekran rengi
  g.fillRect(0, 0, s.getWidth(), s.getHeight());
  g.setColor(w.getForeground());//ön ekran rengi
  g.setFont(new Font("Matisse ITC",1,18));//yazı biçimi
  for(int i=0;i<coord.size();i++)//yılanın ekrana bastırılması //drawing snake
   g.drawImage(coord.get(i).gethead(),coord.get(i).getx(),coord.get(i).gety(),null);
  for(int j=0;j<=780;j+=20){
   g.drawImage(wall,j,0,null);
   g.drawImage(wall,j,560,null);
   }
  for(int k=0;k<=560;k+=20){
   g.drawImage(wall,0,k,null);
   g.drawImage(wall,780,k,null);
   }
  for(int m = 0;m<8;m++)//yemin ekrana bastırılması //drawing seed
  g.drawImage(food.get(m).gethead(),food.get(m).getx(),food.get(m).gety(),null);
  g.drawString(tostring(score),570 ,595);
  g.drawString(mess2,100,595);
  g.drawString(tostring2(dead), 300, 595);
 }
 public synchronized void draw2(Graphics2D g){
  Window w = s.getFullScreenWindow();
  g.setColor(w.getBackground());
  g.fillRect(0, 0, s.getWidth(), s.getHeight());
  g.setColor(w.getForeground());
  g.setFont(new Font("Matisse ITC",1,50));
  g.drawString(mess5, 300, 250);
  g.drawString(mess6, 100, 350);
 }
 public synchronized void draw3(Graphics2D g){
  Window w = s.getFullScreenWindow();
  g.setColor(w.getBackground());
  g.fillRect(0, 0, s.getWidth(), s.getHeight());
  g.setColor(w.getForeground());
  g.setFont(new Font("Matisse ITC",1,50));
  g.drawString(mess4, 300, 250);
 }
}

Sunday, 8 April 2012

Snake Game in Java

engerek.class is to creat snake and update position of snake

import java.util.ArrayList;
import javax.swing.*;
import java.awt.Image;
//import java.math.*;
public class engerek extends variables{

//inner class
 protected class ekans{
 private double x;
 private double y;
 private Image head;
 //default constructor
 public ekans(){
  this.head = kelle;
  this.x = 0.0;
  this.y = 0.0;
 }
 //constructor
 public ekans(Image i,double a,double b){
  this.head = i;
  this.x = a;
  this.y = b;
 }
 public Image gethead(){
  return head;
 }
 public int getx(){
  return (int)x;}
 public int gety(){
  return (int)y;}
 public void setxy(double x,double y){
  this.x = x;
  this.y = y;
 }
 }
 protected Image askelle = new ImageIcon("C:\\Users\\engerek\\images\\aw.png").getImage();//to load Snake head image
 protected Image kelle = new ImageIcon("C:\\Users\\engerek\\images\\ae.png").getImage();//to Load Snake image
 protected Image wall = new ImageIcon("C:\\Users\\engerek\\images\\ay.png").getImage(); //to Load WALL image
 protected Image yem = new ImageIcon("C:\\Users\\engerek\\images\\as.png").getImage();//to Load Seed image 
 ArrayList<ekans> coord = new ArrayList<ekans>();
 ArrayList<ekans> food = new ArrayList<ekans>();
 public void addtile(Image i,int coorx,int coory){
  coord.add(0,new ekans(i,coorx,coory));
 }
 
 public void start(){
  addtile(kelle,320,300);
  addtile(kelle,300,300);
  addtile(kelle,280,300);
  addtile(kelle,260,300);
  addtile(kelle,240,300);
  addtile(kelle,220,300);
  food.add(new ekans(yem,300,400));
  food.add(new ekans(askelle,500,500));
  food.add(new ekans(yem,440,440));
  food.add(new ekans(askelle,100,100));
 }
 public Image load(Image i){
  i = new ImageIcon("C:\\javapics\\deadly.png").getImage();
     return i;
 }
 public void seedupdate(){
  double xco,yco;
  boolean tamamdir = false;
  while(tamamdir==false){
  xco = Math.random()*20;
  yco = Math.random()*20;
  xco = 20 + Math.round(xco)*40;
  yco = 20 + Math.round(yco)*40;
  for(int i = 0;i<coord.size();i++)
   if(xco!=coord.get(i).x && yco != coord.get(i).y){
    if(xco<760 && yco<560 )
    if(yco>20 && xco>20){
     if(index%2==1){
      food.remove(index);
      food.add(index,new ekans(yem,xco,yco));
     }else{
      food.remove(index);
      food.add(index,new ekans(askelle,xco,yco));
     }
    tamamdir = true;
    }
   }
  }
 }
 public void snakeupdate(){
  ekans e = coord.get(0); //ekans object is pointed first element of arraylist
  ekans newmove = new ekans();
  yon = sonrakiyon;
  switch(yon){
  case kuzey :
   newmove.x = e.x;
   newmove.y = e.y - 20.0;
   break;
  case guney : 
   newmove.x = e.x;
   newmove.y = e.y + 20.0;
   break;
  case bati :
   newmove.x = e.x - 20.0;
   newmove.y = e.y;
   break;
  case dogu :
   newmove.x = e.x + 20.0;
   newmove.y = e.y;
   break;
  }
  
  //collision of snake with walls
  if(newmove.x<20){
   lost = true;
   return;
  }if(newmove.x>780){
   lost = true;
   return;
  }if(newmove.y<20){
   lost = true;
   return;
  }if(newmove.y>560){
   lost = true;
   return;
  }
  //collision of snake with itself
  for(int i=0;i<coord.size();i++){
   if(newmove.x == coord.get(i).x && newmove.y == coord.get(i).y){
    lost = true;
    break;
   }
  }
  //eating seed and growing up
  for(int i = 0;i<food.size();i++)
  if(newmove.x==food.get(i).getx() && newmove.y == food.get(i).gety()){
  growup = true;
  score += 5;
  index = i;
  break;
  }
  if(growup==true){
  coord.add(0,newmove);
  }else{
   coord.add(0,newmove);
   coord.remove(coord.size()-1);
  }
   
 }
 //if collision is occur then snake starts up again
 public void collision(){
  coord.removeAll(coord);
  start();
  score = 0;
  dead++;
  lost = false;
  sonrakiyon = kuzey;
 }
}