Friday 27 April 2012

Dragging image in java

Draging Image dragme.java

import javax.swing.JFrame;
public class dragme extends JFrame{
 
 public dragme(){
  
  add(new dragged());
  
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 600);
        setLocationRelativeTo(null);
        setTitle("Dragging App");

        setResizable(false);
        setVisible(true);
  
 }
 
 public static void main(String[] args){
  new dragme();
 }
 
}


Dragged Image Class dragged.java

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.*;

import javax.swing.*;

public class dragged extends JPanel implements MouseMotionListener, MouseListener {
 private Image Dragged;
 private Image background;
 private static int x_coord = 150;
 private static int y_coord = 150;
 private boolean isdragged;
 private static int x_dragFrom = 0;
 private static int y_dragFrom = 0;
 public dragged(){
  
  setPreferredSize(new Dimension(300,300));
  setBackground(Color.WHITE);
  this.addMouseMotionListener(this);
  this.addMouseListener(this);
  LoadImage();
  
 }
 
 public void LoadImage(){
  
  Dragged = new ImageIcon("C:\\javapics\\deneme.png").getImage();
  background = new ImageIcon("C:\\javapics\\daaad.png").getImage();
 }
 
 public void paintComponent(Graphics g){
  
  super.paintComponent(g);
  g.drawImage(background, 0, 0, null);
  g.drawImage(Dragged, x_coord, y_coord, this);
  
 }
 public void mousePressed(MouseEvent e) {
        int x = e.getX();   // Save the x coord of the click
        int y = e.getY();   // Save the y coord of the click
        
        if (x >= x_coord && x <= (x_coord + Dragged.getWidth(null))
                && y >= y_coord && y <= (y_coord + Dragged.getWidth(null))) {
            isdragged = true;
            x_dragFrom = x - x_coord;  // how far from left
            y_dragFrom = y - y_coord;  // how far from top
        } else {
            isdragged = false;
        }
    }
  public void mouseDragged(MouseEvent e) {
         if (isdragged) {  
            
             x_coord = e.getX() - x_dragFrom;//to better dragging view
             y_coord = e.getY() - y_dragFrom;//to better dragging view
             
            //to prevent overflow left and right side
             x_coord  = Math.max(x_coord , 0);
             x_coord  = Math.min(x_coord , getWidth() - Dragged.getWidth(null));
             
             //to prevent overflow up and down side
             y_coord  = Math.max(y_coord , 0);
             y_coord  = Math.min(y_coord , getHeight() - Dragged.getHeight(null));
             
             this.repaint(); // Repaint because position changed.
         }
     }

     //we should change isdragged variable when mouse released for dragging
     public void mouseExited(MouseEvent e) {
         isdragged = false;
     }

     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
}

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


Object Oriented Programming in Cpp

Main Program main.cpp

#include<iostream>
#include<string>
#include<time.h>

#include"Land.h"
#include"Cost.h"
#include"Creature.h"
#include"Enchantment.h"

using namespace std;

int main() { 
 srand((unsigned)time(0)); 
 Land l1("black", "snow covered swamp"); 
 Land l2("blue", "island"); 
 l1.print(); 
 // for the following array, default constructor is called 5 times 
 // let’s randomly initialize land cards in the default constructor srand called at the beginning of the code 
 Land l3[5];
 // cost object: we need total 3 manas, one of them must be 
 // red mana (the last one) color of other two manas are unimportant 
 // order of the parameters: total, white, blue, black, green, red
 Cost *cost = new Cost(3,0,0,0,0,1); 
 // parameters : name, color, ap, hp, cost, description-flavor text 
 Creature c1("anaba shaman", "red", 2, 2, cost, "just try taking this bull by the horns.");
 delete cost; 
 cost = new Cost(5,1,0,0,0,0); 
 Creature c2("angel of mercy","white",3,3, cost,"when angel of mercy enters the battlefield, you gain 3 life."); 
 delete cost; 
 cost = new Cost(1,0,0,0,0,1); 
 Enchantment e("firebreathing", "red", 1,0, cost,"enchanted creature gets +1/+0 until end of turn.");
 // when a creature is enchanted, update its attack power and hit point 
 if (c2.canEnchantable(e)){
  cout << e.getName() << " is enchantable for " << c2.getName() << endl; 
  c2 + e; 
 } else if (c1.canEnchantable(e)){ 
  cout << e.getName() << " is not enchantable for " << c2.getName() << endl;
  cout << e.getName() << " is enchantable for " << c1.getName() << endl;
  c1 + e; 
 } else 
  cout << e.getName() << " can’t be enchanted to any creature!" << endl;
 if (c1.isAffordable(l3,5)) 
  // if you look closely, you can see that 5 is size :) 
  cout << c1.getName() << " is affordable according to land deck l3 " << endl;
 if (e.isAffordable(l3,5)) 
  cout << e.getName() << " is affordable according to land deck l3" << endl; 
 // show time
 Land *l4[8]; 
 for (int i=0; i<5; i++)
  l4[i]=&l3[i]; 
 l4[5]=&c1;
 l4[6]=&c2; 
 l4[7]=&e; 
 for (int i=0; i<8; i++) 
  l4[i]->print(); 
 getchar();
 return 0; 
}

Land Base class cpp file Land.cpp

#include<iostream>
#include<string>

#include "Land.h"

using namespace std;

Land::Land()//default constructor
{
 int random = rand()%5+1;
 switch(random){
  case 1:
   name = "Plains";
   color = "white";
   break;
  case 2:
   name = "Island";
   color = "blue";
   break;
  case 3:
   name = "Swamp";
   color = "black";
   break;
  case 4 :
   name = "Forest";
   color = "green";
   break;
  case 5: 
   name = "Mountain";
   color = "red";
   break;
 }
}

Land::Land(const string &s1,const string &s2)
{
 name = s1;
 color = s2;
}

void Land::print()const
{
 cout << "Name : "<< name << "  Color : "<< color << endl;
}

Land Base class header file Land.h

#ifndef LAND_H
#define LAND_H
#include<string>
#include<time.h>
#include<cstdlib>
using namespace std;

class Land{//Base Class
private :
 string name;
 string color;
public :
 Land();//default constructor
 Land(const string &,const string &);//copy constructor
 string getname()const {return name;}//return name variable
 string getcolor()const {return color;}//return color variable
 virtual void print()const;//virtual function from polymorphism
};

#endif

Creature Derived Class header file Creature.h

#ifndef CREATURE_H
#define CREATURE_H
#include<string>
#include "Enchantment.h"
#include "Land.h"
#include "Cost.h"

using namespace std;

class Creature: public Land  //public inhertance base class is Land
{
private :
 int ap;//attack point
 int hp;//hit point
 Cost *c1; //Cost pointer 
 string description;//description of creature
public :
 Creature(const string &,const string &,int AP,int,Cost *,const string &);//Constructor
 bool canEnchantable(const Enchantment &);//to control is Creature's color is useful for Land
 string getName()const{return Land::getname();}//return name variable
 bool isAffordable(const Land *,int);//to control is mana enough for Creature
 void print()const; //virtual function from polymorphism
 void operator+(const Enchantment &); //operator overloading
 ~Creature(){delete c1;}//Destructor
};
#endif

Creature Derived Class cpp file Creature.cpp

#include<iostream>
#include<string>

#include "Creature.h"

using namespace std;

Creature::Creature(const string &s1,const string &s2,int AP,int HP,Cost *cost,const string &s3):Land(s1,s2)
{
  ap = AP;
  hp = HP;
  c1 = new Cost(cost->getTotal(),cost->getWhite(),cost->getBlue(),cost->getBlack(),cost->getGreen(),cost->getRed());
  description = s3;
}

bool Creature::canEnchantable(const Enchantment &e)
{
  if(Land::getcolor().compare(e.getColor())==0)//compare function in string library return integer value
   return true;
  else
   return false;
}

void Creature::print()const //virtual function from polymorphism
{
  Land::print(); // virtual  base print function
  cout << "Attack Point : " << ap << "\n"
         << "Hit Point : " << hp << "\n"
  << "Total Mana : " << c1->getTotal() << "\n"
  << Land::getcolor() <<" Mana : " << c1->getmana() << "\n"
  << description << endl;
}

void Creature::operator+(const Enchantment &e) //operator overloading
{
  ap = ap + e.getAp();
  hp = hp + e.getHp();
}

bool Creature::isAffordable(const Land *l,int size)
{ //Mana Array's size = 5 and it includes number of mana colors
 int manas[5] = {0,0,0,0,0};//White,Blue,Black,Green,Red
 if(c1->getTotal()>size)
   return false;
 else{
  for(int i = 0;i<size;i++){
   if(l[i].getcolor().compare("white")==0)
    //increment number of White Mana
    manas[0]++;
   if(l[i].getcolor().compare("blue")==0)
    //increment number of Blue Mana
    manas[1]++;     
   if(l[i].getcolor().compare("black")==0)
    //increment number of Black Mana
    manas[2]++; 
   if(l[i].getcolor().compare("green")==0)
    //increment number of Green Mana
    manas[3]++;
   if(l[i].getcolor().compare("red")==0)
    //increment number of Red Mana
    manas[4]++;
  }
  if(Land::getcolor().compare("white")==0){
   if(c1->getWhite() <= manas[0])
    return true;
  }else if(Land::getcolor().compare("blue")==0){
   if(c1->getBlue() <= manas[1])
    return true;
  }else if(Land::getcolor().compare("black")==0){
   if(c1->getBlack() <= manas[2])
    return true;
  }else if(Land::getcolor().compare("green")==0){
   if(c1->getGreen() <= manas[3])
    return true;
  }else if(Land::getcolor().compare("red")==0){
   if(c1->getRed() <= manas[4])
    return true;
  }
  return false;
 }
}

Enchantment Derived Class header file Enchantment.h

#ifndef ENCHANTMENT_H
#define ENCHANTMENT_H
#include<string>
#include "Cost.h"
#include "Land.h"

using namespace std;

class Enchantment : public Land //public inhertance base class is Land
{
private :
 int inc_ap;//increment atack point
 int inc_hp;//increment hit point;
 string description;//description of enchantment
 Cost *c2;//Cost pointer
public :
 Enchantment(const string &,const string &,int AP,int HP,Cost *,const string &);//Constructor
 string getColor()const{return Land::getcolor();}//get method to access private member called color in base class Land
 string getName()const{return Land::getname();}//get method to access private member called name in base class Land

 bool isAffordable(const Land *,int);//To control is mana enough for Enchantment 
 
 void print()const; //virtual function from polymorphism
 
 int getAp()const {return inc_ap;}//get method to access private inc_ap
 int getHp()const {return inc_hp;}//get method to access private inc_hp
 ~Enchantment(){delete c2;}//destructor
};

#endif

Enchantment Derived Class cpp file Enchantment.cpp

#include<iostream>
#include<string>

#include "Enchantment.h"

using namespace std;

bool Enchantment::isAffordable(const Land *l,int size)
{
 int manas[5] = {0,0,0,0,0}; //White,Blue,Black,Green,Red
 if(c2->getTotal()>size)
   return false;
 else{
  for(int i = 0;i<size;i++){
   if(l[i].getcolor().compare("white")==0)
    //increment number of White Mana
    manas[0]++;
   if(l[i].getcolor().compare("blue")==0)
    //increment number of White Mana
    manas[1]++;     
   if(l[i].getcolor().compare("black")==0)
    //increment number of White Mana
    manas[2]++; 
   if(l[i].getcolor().compare("green")==0)
    //increment number of White Mana
    manas[3]++;
   if(l[i].getcolor().compare("red")==0)
    //increment number of White Mana
    manas[4]++;
  }
  if(Land::getcolor().compare("white")==0){
   if(c2->getWhite() <= manas[0])
    return true;
  }else if(Land::getcolor().compare("blue")==0){
   if(c2->getBlue() <= manas[1])
    return true;
  }else if(Land::getcolor().compare("black")==0){
   if(c2->getBlack() <= manas[2])
    return true;
  }else if(Land::getcolor().compare("green")==0){
   if(c2->getGreen() <= manas[3])
    return true;
  }else if(Land::getcolor().compare("red")==0){
   if(c2->getRed() <= manas[4])
    return true;
  } 
  return false; 
 }
} 

void Enchantment::print()const //virtual function from polymorphism
{
  Land::print();//virtual base print function
  cout << "Increment Attack Point by : " << inc_ap << "\n"
   <<  "Increment Hit Point by : " << inc_hp << "\n"
   << "Total Mana : " << c2->getTotal() << "\n"
   << Land::getcolor() << " Mana : " << c2->getmana() << "\n"
   << description << endl;
  
}

Enchantment::Enchantment(const string &s,const string &s2,int AP,int HP,Cost *cost,const string &s3):Land(s,s2)
{ 
  // Constructor
  inc_ap = AP;
  inc_hp = HP;
  c2 = new Cost(cost->getTotal(),cost->getWhite(),cost->getBlue(),cost->getBlack(),cost->getGreen(),cost->getRed());
  description = s3;
}

Cost Class header file Cost.h

#ifndef COST_H
#define COST_H

using namespace std;

class Cost{
private :
 int Total;
 int White;
 int Blue;
 int Black;
 int Green;
 int Red;
public :
 Cost(int,int,int,int,int,int);
 int getmana()const;
 int getTotal()const {return Total;}
 int getWhite()const {return White;}
 int getBlue()const {return Blue;}
 int getBlack()const {return Black;}
 int getGreen()const {return Green;}
 int getRed()const {return Red;}
};

#endif

Cost Class cpp file Cost.cpp

#include<iostream>
#include<string>

#include "Cost.h"

using namespace std;

Cost::Cost(int total,int white,int blue,int black,int green,int red)
{
 Total = total;
 White = white;
 Blue = blue;
 Black = black;
 Green = green;
 Red = red;
}

int Cost::getmana()const
{
 if(White!=0)
  return White;
 else if(Blue!=0)
  return Blue;
 else if(Black!=0)
  return Black;
 else if(Green!=0)
  return Green;
 else if(Red!=0)
  return Red;
 else
  return 0;
}

OUTPUT

Tuesday 17 April 2012

Signals and Systems

                Sinyaller ve Sistemler çıkmış vize soruları



Wednesday 11 April 2012

Linked List/Bağlantılı liste

List Example with cpp / Bağlantılı liste örneği

#include<iostream>
#include<string>
#include<stdlib.h>
#include<stdio.h>
#include<iomanip>
#include<ctype.h>

using namespace std;
#include "Kayit.h"
typedef struct listeDugumu listeDugumu;
typedef listeDugumu *listeDugumuPtr;


void ekle(listeDugumuPtr *,listeDugumu *,int);
void listeyazdir(listeDugumuPtr);
int bosMu(listeDugumuPtr);
void sil(listeDugumuPtr *,int,int);
void menu(void);
void listebosalt(listeDugumuPtr *);
//void listeyibol(listeDugumuPtr *,int);
int main(){

 listeDugumuPtr baslangicPtr=NULL;
 listeDugumu *kayitPtr;
 kayitPtr =new listeDugumu;
 int dugumsayisi=0;
 int sirano;
 menu();
 int secim;
 cout << "? : ";
 cin >> secim;
 
 while(secim!=8){
   
  switch(secim){
  case 1 :
   cout << "Lutfen eklemek istediginiz kisinin bilgilerini giriniz" << endl;
   cout << "Eklenecek ismi giriniz : ";
   cin.ignore(1000, '\n');
   cin.getline(kayitPtr->isim,AD_UZUNLUK);
      cout <<"Eklenecek Telefon numarasi : ";
   cin >> setw(TEL_UZUNLUK) >> kayitPtr->tel_numarasi;
   cout << endl;
   ekle(&baslangicPtr,kayitPtr,dugumsayisi);
      listeyazdir(baslangicPtr);
   break;
  case 2 :
    if(!bosMu(baslangicPtr)){
    cout << "Silinecek siranoyu giriniz :";
    cin >> sirano;
    sil(&baslangicPtr,sirano,dugumsayisi);
    cout << "Kayit silindi" << endl;
    }else
     cout << "liste bos" << endl;
         break;
  case 3 : 
   listebosalt(&baslangicPtr);
     cout << "liste bosaltildi..." << endl;
   break;
  /*case 4 :
   cout << "listeyi kaca bolmek istiyorsunuz ?" << endl;
   cin >> kac;
   listeyibol(&baslangicPtr,dugumsayisi);
   break;
   */
  default:
   cout << "Yanlis bir giris yaptiniz tekrar giriniz" << endl;
   menu();
        break;
       }
  cout << "? : "; 
  cin >> secim;
 }
 cout << "program kapatılıyor";
 delete kayitPtr;
 
 return EXIT_SUCCESS;
}
void menu(void){
cout << "1-Kayit ekle" << endl;
cout << "2-Kayit sil" << endl;
cout << "3-Listeyi bosalt" << endl;
cout << "4-Listeyi ikiye bol" << endl;
cout << "8-Cikis" << endl;
  
}
void ekle(listeDugumuPtr *sPtr,listeDugumu *savePtr,int dugum_sayisi){
 listeDugumuPtr tara,arka,yeni;
  tara=*sPtr;
  yeni = new listeDugumu;
        *yeni=*savePtr;
  yeni->sonrakiPtr=NULL;
  if(*sPtr==NULL){
  *sPtr=yeni;//ilk düğüm ekleniyor
  dugum_sayisi++;
  return;
     }
  if(strcmp(yeni->isim,(*sPtr)->isim)<0)
  {
   yeni->sonrakiPtr=*sPtr;//Basa ekleniyor
   *sPtr=yeni;
   dugum_sayisi++;
   return;
  }
  while(tara && strcmp(yeni->isim,tara->isim)>0)
  {
  arka=tara;
  tara=tara->sonrakiPtr;
  
  }
  if(tara){
   yeni->sonrakiPtr=tara;//araya ekleniyor
   arka->sonrakiPtr=yeni;
   
  }
  else
   arka->sonrakiPtr=yeni;//sona ekleniyor
      dugum_sayisi++;
}
void listeyazdir(listeDugumuPtr suandakiPtr){
 int i=1;
 if(suandakiPtr==NULL)
  cout << "Rehber bos" << endl;
 else{
  cout << "Liste : " << endl;
    while(suandakiPtr!=NULL){
     cout << i << suandakiPtr->isim << "\t" << suandakiPtr->tel_numarasi << endl;
     suandakiPtr=suandakiPtr->sonrakiPtr;
     i++;
    }
 }
}
int bosMu(listeDugumuPtr basPtr){
   return basPtr==NULL;
}
void sil(listeDugumuPtr *sPtr,int sira,int dugum_sayisi){
 listeDugumuPtr tara,arka;
 int sayac=1;
 tara=*sPtr;
 if(sira<=0){
  cout << "yanlis sira no girdiniz" << endl;
  return;
 }
 if(sira==1){
 *sPtr=(*sPtr)->sonrakiPtr;
 delete tara;
 dugum_sayisi--;
 return;
 }
 while(tara && (sayac<sira)){
 arka=tara;
 tara=tara->sonrakiPtr;
 sayac++;
 }
 if(sayac<sira)
  cout << "silinecek kayit bulunamadi" << endl;
 else{
  arka->sonrakiPtr=tara->sonrakiPtr;
     delete tara;
     dugum_sayisi--;

 }
    
}
void listebosalt(listeDugumuPtr *sPtr){
   listeDugumuPtr tara;
   
    if(*sPtr==NULL)
  cout << "liste bos" << endl;
 else 
  while(*sPtr){
     tara=*sPtr;
  *sPtr=(*sPtr)->sonrakiPtr;
  delete tara;
  }

}

kayit.h is a header file for liste_example.cpp


#define AD_UZUNLUK 30
#define TEL_UZUNLUK 15
struct listeDugumu{
char isim[AD_UZUNLUK];
char tel_numarasi[TEL_UZUNLUK];
struct listeDugumu *sonrakiPtr;
};

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