Showing posts with label Game Progamming. Show all posts
Showing posts with label Game Progamming. Show all posts

Saturday, 9 June 2012

PingPong Game in Java

Board.java 

 

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Board extends JPanel implements ActionListener{
 
 private final int width = 600;
 private final int height = 600;
 
 private int delay = 30;//time delay to update
 private int board_x;//board x location
 private int board_y;//board y location
 private int ball_x;//ball x location
 private int ball_y;//ball y location
 private float ball_xv;//ball x violation
 private float ball_yv;//ball y violation
 
 //conditions
 private boolean running = true;
 private boolean contin= true; 
 private boolean tryagain = false;
 
 //for keyboard 
 private boolean pause = false;
 private boolean left = false;
 private boolean right = false;
 
 //for mouse motions
 private boolean dragged = false;
 private int howfarx = 0; //how far mouse click x coordinate from object's x coordinate
 
 
 private Image ball;
 private Image board;
 private Timer timer;
 private Image background;
 
 private String msg = "presss";
 
 
 public Board()
 {
  addKeyListener(new TAdapter()); 
  addMouseMotionListener(new MAdapter());
  addMouseListener(new MAdapter());
  setBackground(Color.white);
  load();
  setFocusable(true);
  init();
 }
 public void load()
 {
  board = new ImageIcon("C:\\javapics\\board.png").getImage();
  ball = new ImageIcon("C:\\javapics\\ae.png").getImage();
  background = new ImageIcon("C:\\javapics\\backgroud.png").getImage();
 }
 public void actionPerformed(ActionEvent e) {
  
  if(running)
  {
      if(contin)
      {
       ballmoving();
       boardmove();
       lose();
      }
      
  }
   repaint();
 }
 public void start()
 {
  ball_xv = -0.4f;
  ball_yv = -0.3f;
  board_x = 240;
  board_y = 580;
  ball_x = 300;
  ball_y = 240;
 }
 public void init()
 {
  start();
  timer = new Timer(delay,this);
  timer.start();
 }
 public void paint(Graphics g)
 {
  super.paint(g);
  if(contin)
  {
   g.drawImage(ball, ball_x, ball_y,this);
   g.drawImage(board, board_x, board_y,this);
   Toolkit.getDefaultToolkit().sync();
   g.dispose();
  }
  if(tryagain)
  {
   String msg2 = "Press Enter to try again";
         Font small = new Font("Arial", Font.BOLD, 15);

         g.setColor(Color.black);
         g.setFont(small);
         g.drawString(msg2,200,300);
         
  }
  if(pause)
  {
   String msg2 = "Pause! Press Space to continue";
         Font small = new Font("Helvetica", Font.BOLD, 15);

         g.setColor(Color.black);
         g.setFont(small);
         g.drawString(msg2,200,300);
         
  }
  if(!running)
  { 
   g.drawImage(background, 0, 0,this);
  }
  
 }
 public void lose()
 {
  if(ball_y + 20 > height)
  { 
   contin = false;
   tryagain = true;
   
  }
  
 }
 public void ballmoving()
 {
  
  if(ball_x < 1)
   ball_xv = Math.abs(ball_xv);
  else if((ball_x + 20) > (width-21))
   ball_xv = -Math.abs(ball_xv);
  
  if(ball_y < 1)
   ball_yv = Math.abs(ball_yv);
  else if((ball_y+20) > (height-21))
   if(ball_x >= board_x && ball_x <= (board_x+100) )
   ball_yv = -Math.abs(ball_yv);
  
  update(delay);
  
 }
 public void update(int timedelay)//to update ball location on the screen
 {
  ball_x = (ball_x + (int)(ball_xv*delay));
  ball_y = (ball_y + (int)(ball_yv*delay));
 }
 public void boardmove()//to play with keyboard
 {
  if(left){
   board_x -= 40;
   left = false;
  }
  if(right){
   board_x += 40;
   right = false;
  }
 }
 private class MAdapter extends MouseAdapter
 {
  public void mousePressed(MouseEvent e)
  {
   int mousex = e.getX();
   int mousey = e.getY();
   if(mousex >= board_x && mousex <= (board_x+ 100))
    if(mousey >= board_y && mousey <= (board_y+100)){
     dragged = true;
     howfarx =  mousex - board_x;
   }else {
     dragged = false;
   }
  }
  public void mouseDragged(MouseEvent e)
  { 
   if(dragged){
    board_x = e.getX() - howfarx;
    
    board_x = Math.max(0, board_x);//to prevent overflow from sides
    board_x = Math.min(board_x, (width-120));/////////////////////
   }
  }
  public void mouseExited(MouseEvent e)
  {
   dragged = false;
   howfarx = 0;
  }
  public void mouseMoved   (MouseEvent e) {}  // ignore these events
  public void mouseEntered (MouseEvent e) {}  // ignore these events
  public void mouseClicked (MouseEvent e) {}  // ignore these events
  public void mouseReleased(MouseEvent e) {}  // ignore these events
 }
 private class TAdapter extends KeyAdapter
 { 
  public void keyPressed(KeyEvent e)
  {
   int key = e.getKeyCode();
   if(key == KeyEvent.VK_Z)
   { 
    msg = "pressed z";
    if((board_x - 40) >= 0)//to prevent overflow from left side from 
     left = true;
    else
     left = false;//nothing
   }
   if(key == KeyEvent.VK_X)
   {
    msg = "pressed x";
    if((board_x + 150) <= width)//to prevent overflow form right side of game area
     right = true;
    else 
     right = false;//nothing
   }
   if(key == KeyEvent.VK_ENTER){
    start();
    contin = true;
    tryagain = false;
    pause = false;
   }
   if(key == KeyEvent.VK_SPACE){
    if(!pause){
    contin = false;
    pause = true;
    tryagain = false;
    }else{
     contin = true;
     pause = false;
     tryagain = false;
    }
   }
   if(key == KeyEvent.VK_ESCAPE){
    running = false;
    contin = false;
    pause = false;
    tryagain = false;
   }
  }
 }
}



import javax.swing.*;
public class pinpong extends JApplet {

 /**
  * @param args
  */
 public pinpong()
 { 
  this.setContentPane(new Board()); 
 }
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  JFrame window = new JFrame();
  window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(586, 630);
        window.setLocationRelativeTo(null);
        window.setTitle("pinpong");
        window.setContentPane(new Board());
        window.setResizable(false);
        window.setVisible(true);
 }

}

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


public class variables {
 
 //directions/yönler
 protected static final int kuzey = 1;
 protected static final int guney = 2;
 protected static final int bati = 3;
 protected static final int dogu = 4;
 
 //direction
 protected int yon = kuzey;
 
 //next direction
 protected int sonrakiyon = kuzey;
 
 protected long movedelay = 100; //millisecond to go or (X/V) Road/Velocity //ilerleme hızı
 protected long lastmove = 0;//time for next step
 
 //game status
 protected boolean becontinue = true;  // game is continuing //oyun devam ediyor
 protected boolean pause = false; //game is paused //oyun durduruldu
 protected boolean lost = false;//kaybettin
 protected boolean continued= false;
 //eat seed
 protected static boolean growup = false;
 protected String mess = "Score = ";
 protected String mess2 = "Press ESC to Exit ";
 protected String mess3 = "Number of dead = ";
 protected String mess4 = "Pause";
 protected String mess5 = "You LOSE";
 protected String mess6 = "Try Again-Press Enter or Exit";
 protected static int score = 0;
 protected static int dead = 0;
 protected static int index ;
 
 
}

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