Monday 15 October 2012

N Queen Algorithm

package eight.queen.algorithm;



public class Queen {
 
 private int N = 8; 
 private int chess[][];
 
 
 public Queen(){
  chess = new int[N][N];
  System.out.println(N+" sizes chess table contain "+NQueen(0)+"\n");
 }
 
 public int NQueen(int currentRow){
  
  if(currentRow==N)
   return 1;
  int totalQueenSetting = 0;
  for(int i = 0;i<N;i++){
   if(chess[currentRow][i]==0){ 
    chess[currentRow][i] = 1+currentRow;
    setConsumedSquares(currentRow,i);
    
    totalQueenSetting += NQueen(currentRow+1);
    for(int k = 0; k<N;k++)
     for(int j = 0;j<N;j++)
      if(chess[k][j]==8){
       print();
       System.out.println("\t");
       break;
      }
    chess[currentRow][i] = 0;
    recover(currentRow);
   }
  }
  return totalQueenSetting;
 }
 public void setConsumedSquares(int row,int i){
  for(int j = row+1;j<N;j++){
   if(chess[j][i]==0)
   chess[j][i] = (1+row);
   if(i-(j-row)>=0 && chess[j][i-(j-row)] == 0)
    chess[j][i-(j-row)] = (1+row);
   if(i+(j-row) < N && chess[j][i+(j-row)] == 0)
    chess[j][i+(j-row)] = (1+row);
  }
   
 }
 public void recover(int row){
  for(int i = row;i<N;i++)
   for(int j = 0;j<N;j++)
    if(chess[i][j]==(1+row))
     chess[i][j] = 0;
 }
 public void print(){
  for(int i = 0; i<N;i++)
   for(int j = 0;j<N;j++){
    System.out.print(chess[i][j]+" ");
    if(j == N-1)
     System.out.println("\t");
   }
 }
 public static void main(String[] args){
  Queen test = new Queen();
  
 }
}

insertion sorting



public class insertionSorting {

 /**
  * @param args
  */
 
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  insertionSorting test = new insertionSorting();
 }
 
 public insertionSorting(){
  int array[] = {2,5,1,9,12,3,6,7,11,11,11,8,21,17,45,46,33,22};
  sorting(array);
  print(array);
 }
 
 public void sorting(int[] buffer){
  int key,i;
  for(int j = 1;j<buffer.length;j++)
  {
   key = buffer[j];
   i = j-1;
   while((i>=0) && buffer[i] > key){
    buffer[i+1] = buffer[i];
    i = i-1;
   }
   buffer[i+1] = key;
  }
 }
 public void print(int[] buffer){
  for(int i = 0;i<buffer.length;i++)
   System.out.print(buffer[i]+", ");
 }
 
}

Merge Sorting



public class mergeSort {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  mergeSort test = new mergeSort();
 }
 private int[] array;
 private int N;
 public mergeSort(){
  N = 10;
  array = new int[N];
  for(int i=0;i<array.length;i++)
   array[i] = (int)(Math.random()*10)+1;
  print(array);
  sort(array,0,N-1);
  print(array);
 }
 public void print(int []array){
  for(int i = 0;i<array.length;i++)
   System.out.print(array[i]+", ");
  System.out.println("");
 }
 public void sort(int []array,int p,int r){
  if(r-p>=1)
  {
   int q = (int)(Math.floor((double)((p+r)/2)));
   sort(array,p,q);
   sort(array,q+1,r);
   merge(array,p,q,r);
  } 
   
 }
 public void merge(int []array,int p,int q,int r){
  int n1 = q-p+1;
  int n2 = r-q;
  int left[] = new int[n1+1];
  int right[] = new int[n2+1];
  for(int i = 0;i<left.length-1;i++)
   left[i] = array[p+i];
  for(int i=0;i<right.length-1;i++)
   right[i] = array[q+i+1];
  left[n1] = 11;
  right[n2] = 11;
  int i = 0;
  int j = 0;
  for(int k = p;k<=r;k++){
   if(left[i]<=right[j]){
    array[k] = left[i];
    i++;
   }else{
    array[k] = right[j];
    j++;
   }
  }
  
 }
}

Saturday 11 August 2012

ActionListener Example

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import java.util.ArrayList;


public class makine extends JApplet{

 
 private int counter = 0;
 
 
 private ArrayList<String> liste;
 private String[] yazi;
 private JButton one,two,three,four,five,
 six,seven,eight,nine,zero,
 arti,eksi,bolu,carpi,CE,esit;
 
 
 
 private JTextField ekran;
 private JLabel yazar;
 private DecimalFormat dec;
 
 public String ToString(Double d)
 {
  return d.toString();
 }
 //@override
 public void init()
 { 
  yazi = new String[11];
  liste = new ArrayList<String>();
  for(int i = 0;i<11;i++){
   yazi[i] = "";
  }
  ActionHandler handler = new ActionHandler();
  Container container = this.getContentPane();
  container.setLayout(new FlowLayout(1,8,2));
  
  
  
  dec = new DecimalFormat("0.000");
  one = new JButton();
  one.setText("1");
  one.setSize(20, 20);
  one.setLocation(40, 40);
  container.add(one);
  one.addActionListener(handler);
  
  
  two = new JButton();
  two.setText("2");
  two.setSize(20, 20);
  two.setLocation(40, 40);
  container.add(two);
  two.addActionListener(handler);
  
  three = new JButton();
  three.setText("3");
  three.setSize(20, 20);
  three.setLocation(70, 40);
  container.add(three);
  three.addActionListener(handler);
  
  arti = new JButton();
  arti.setText("+");
  arti.setSize(20, 20);
  arti.setLocation(100, 40);
  container.add(arti);
  arti.addActionListener(handler);
  
  four = new JButton();
  four.setText("4");
  four.setSize(20, 20);
  four.setLocation(10, 70);
  container.add(four);
  four.addActionListener(handler);
  
  five = new JButton();
  five.setText("5");
  five.setSize(20, 20);
  five.setLocation(40, 70);
  container.add(five);
  five.addActionListener(handler);
  
  six = new JButton();
  six.setText("6");
  six.setSize(20, 20);
  six.setLocation(70, 70);
  container.add(six);
  six.addActionListener(handler);
  
  eksi = new JButton();
  eksi.setText("-");
  eksi.setSize(20, 20);
  eksi.setLocation(10, 70);
  container.add(eksi);
  eksi.addActionListener(handler);
  
  seven = new JButton();
  seven.setText("7");
  seven.setSize(20, 20);
  seven.setLocation(10, 100);
  container.add(seven);
  seven.addActionListener(handler);
  

  
  
  eight = new JButton();
  eight.setText("8");
  eight.setSize(20, 20);
  eight.setLocation(40, 100);
  container.add(eight);
  eight.addActionListener(handler);
  
  nine = new JButton();
  nine.setText("9");
  nine.setSize(20, 20);
  nine.setLocation(70, 100);
  container.add(nine);
  nine.addActionListener(handler);
  
  carpi = new JButton();
  carpi.setText("x");
  carpi.setSize(20, 20);
  carpi.setLocation(100, 130);
  container.add(carpi);
  carpi.addActionListener(handler);
  
  CE = new JButton();
  CE.setText("CE");
  CE.setSize(20, 20);
  CE.setLocation(10, 100);
  container.add(CE);
  CE.addActionListener(handler);
  
  zero = new JButton();
  zero.setText("0");
  zero.setSize(20, 20);
  zero.setLocation(40, 130);
  container.add(zero);
  zero.addActionListener(handler);
  
  
  
  
  bolu = new JButton();
  bolu.setText("/");
  bolu.setSize(20, 20);
  bolu.setLocation(100, 100);
  container.add(bolu);
  bolu.addActionListener(handler);
  
  
  
  esit = new JButton();
  esit.setText("=");
  esit.setSize(20, 20);
  esit.setLocation(70, 100);
  container.add(esit);
  esit.addActionListener(handler);
  
  ekran = new JTextField(15);
  ekran.setText(" ");
  ekran.setEditable(false);
  ekran.setDisabledTextColor(Color.BLUE );
  ekran.setVisible(true);
  ekran.setAlignmentY(JTextField.RIGHT_ALIGNMENT);
  ekran.setHorizontalAlignment(JTextField.RIGHT);
  ekran.setLocation(10,10);
  container.add(ekran);
  ekran.addActionListener(handler);
  
  yazar = new JLabel("Tested and Programmed by BY");
  container.add(yazar);
  
 }
 //inner class
 private class ActionHandler implements ActionListener
 {
  public void actionPerformed(ActionEvent event)
  {
   if(event.getSource() == one){
    if(counter<11){
     yazi[counter]+="1";
     ekran.setText(yazi[counter]);
    }else ;
   }if(event.getSource() == two){
    if(counter<11){
     yazi[counter]+="2";
     ekran.setText(yazi[counter]);
    }else ;
   }if(event.getSource() == three){
    if(counter<11){
     yazi[counter]+="3";
     ekran.setText(yazi[counter]);
    }else;
   }if(event.getSource() == four){
    if(counter<11){
     yazi[counter]+= "4";
     ekran.setText(yazi[counter]);
    }else;
   }if(event.getSource() == five){
    if(counter<11){
     yazi[counter] += "5";
     ekran.setText(yazi[counter]);
    }else;
   }if(event.getSource() == six){
    if(counter<11){
     yazi[counter] += "6";
     ekran.setText(yazi[counter]);
    }else;
   }if(event.getSource() == seven){
    if(counter<11){
     yazi[counter] += "7";
     ekran.setText(yazi[counter]);
    }else;
   }if(event.getSource() == eight){
    if(counter<11){
     yazi[counter] += "8";
     ekran.setText(yazi[counter]);
    }else;
   }if(event.getSource() == nine){
    if(counter<11){
     yazi[counter] += "9";
     ekran.setText(yazi[counter]);
    }else;
   }if(event.getSource() == zero){
    if(counter<11){
     yazi[counter] += "0";
     ekran.setText(yazi[counter]);
    }else;
   }if(event.getSource() == arti){
    try{
    if(Double.parseDouble(yazi[counter])>=0){
    counter++;
    yazi[counter] = "+";
    counter++;
    }else;
    }catch(Exception e){
     ekran.setText("Syntax Error");
    }
   }if(event.getSource() == eksi){
    try{
    if(Double.parseDouble(yazi[counter])>=0){
    counter++;
    yazi[counter] = "-";
    counter++;
    }else;
    }catch(Exception e){
     ekran.setText("Syntax Error");
    }
   }if(event.getSource() == bolu){
    try{
    if(Double.parseDouble(yazi[counter])>=0){
    counter++;
    yazi[counter] = "/";
    counter++;
    }else;
    }catch(Exception e){
     ekran.setText("Syntax Error");
    }
   }if(event.getSource() == carpi){
    try{
    if(Double.parseDouble(yazi[counter])>=0){
    counter++;
    yazi[counter] = "*";
    counter++;
    }
    }catch(Exception e){
     ekran.setText("Syntax Error");
    }
   }if(event.getSource() == CE){
    for(int i = 0;i<11;i++)
     yazi[i] = "";
     ekran.setText("");
     counter = 0;
   }if(event.getSource() == esit){
    //try{
    for(int i = 0;i<11;i++){
     liste.add(i,yazi[i]);
    }
    for(int i = 0;i<11;i++){
     try{
     if(yazi[i]=="/"){
       
     yazi[i] = ToString(Double.parseDouble(yazi[i-1])/Double.parseDouble(yazi[i+1]));
       yazi[i-1] = yazi[i];
       yazi[i+1] = yazi[i];
       liste.remove(0);
       liste.add(0,yazi[i]);
      }
     }catch(Exception e){
      ekran.setText("Syntax Error");
      counter = 0;
     }
    }
    for(int i = 0;i<11;i++){
     try{ 
     if(yazi[i]=="*"){
           yazi[i] = ToString(Double.parseDouble(yazi[i-1])*Double.parseDouble(yazi[i+1]));
       yazi[i-1] = yazi[i];
       yazi[i+1] = yazi[i];
       liste.remove(0);
       liste.add(0,yazi[i]);
       
      }
     }
     catch(Exception e){
      ekran.setText("Syntax Error");
      counter = 0;
     }
    }
    for(int i = 0;i<11;i++){
     try{
     if(yazi[i]=="+"){
                         yazi[i] = ToString(Double.parseDouble(yazi[i-1])+Double.parseDouble(yazi[i+1]));
       yazi[i-1] = yazi[i];
       yazi[i+1] = yazi[i];
       liste.remove(0);
       liste.add(0,yazi[i]);
      } 
     }
     catch(Exception e){
      ekran.setText("Syntax Error");
      counter = 0;
     }
    }
    for(int i = 0;i<11;i++){
     try{
     if(yazi[i]=="-"){
        
    yazi[i] = ToString(Double.parseDouble(yazi[i-1])-Double.parseDouble(yazi[i+1]));
       yazi[i-1] = yazi[i];
       yazi[i+1] = yazi[i];
       liste.remove(0);
       liste.add(0,yazi[i]);
      }
     }
     catch(Exception e){
      ekran.setText("Syntax Error");
      counter = 0;
     } 
    } 
     if(liste.isEmpty()){
      ekran.setText("Syntax Error");
      counter = 0;}
     else{
         if(liste.get(0)!="")
                              ekran.setText(liste.get(0).toString());
     }
     counter = 0;
     for(int i = 0;i<11;i++)
      yazi[i] = "";
     if(!liste.isEmpty())
      liste.clear();
      
    /*}catch(Exception e){
     ekran.setText("Syntax Error");
    }*/
   }
   
  }
 } 
}

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

}

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

Thursday 15 March 2012

string library

#include<iostream>
#include<conio.h>
#include<string>
typedef string stringer
void main(){
   stringer mailto = "yilmazburk@gmail.com";
   cout << mailto << endl;
}

Tuesday 13 March 2012

Problem Getline is solved

Getline function sometimes runs badly i mean it's work useless for us so i can help you about getline's useless

/***************************************************************************** 

   using getline function/getline fonksiyonun istenildiği gibi kullanılması

******************************************************************************/
#include<string>
#include<iostream>

using namespace std;

void main(){
string film_name,country;
bool oscar;
int duration,number_of_actors;
double imdb_rating;
string getliner;

cout << "Please enter film's name : " << "\n";
cin.ignore(0,'\n'); //not read space and nextline character
getline(cin,film_name);

cout  << "Please enter film's year : "<< endl;
cin >> year;

cout  << "Please enter film's duration : "<< endl;
cin >> duration;

cout  << "Please enter number of actors : "<< endl;
cin >> number_of_actors;
getline(cin,getliner);

cout  << "Please enter film's country : "<< "\n";
cin.ignore(0,'\n');  //not read space and nextline character
getline(cin,country);

cout  << "Does the film have Oscar 0 or 1 : "<< endl;
cin >> oscar;

cout  << "Please enter imdb rating of the film : "<< endl;
cin >> imdb_rating;
getline(cin,getliner);

cout << "Film added" << endl;

cin.clear();
}

Saturday 3 March 2012

Memory Allocation in cpp with 2 Dimensional Arrays

Operation on matrices with pointers/Pointerlar ve Diziler Üzerinde hafıza işlemleri

/***********************************************************
Memory Allocation and Matrices Operations with pointers
************************************************************/
#include <iostream>
#include <ctimegt>
#include <cstdlibgt>
using namespace std;
/**********************************************************************************
*FONKSİYONUN ADI: multip_matrix
*ALDIĞI PARAMETRELER: int** ve int
*DÖNÜŞ DEĞERİ: void
*AMACI: İki boyutlu 2 diziyi matris ve işaretçi aritmetiğine göre çarpan fonksiyon
**********************************************************************************/
void multip_matrix(int **a, int **b, int **c, int k, int m, int n){

 int i,j,l;
 int sum=0;
 for(l=0;l<n;l++)
  for(i=0;i<k;i++){
   for(j=0;j<m;j++){
    sum+=*(*(b+j)+l)**(*(a+i)+j);
   }
   *(*(c+i)+l) = sum;
   sum = 0;
  }
}
/**********************************************************************************
*FONKSİYONUN ADI: multip_array
*ALDIĞI PARAMETRELER: int* ve int
*DÖNÜŞ DEĞERİ: void
*AMACI: Tek boyutlu 2 diziyi matris ve işaretçi aritmetiğine göre çarpan fonksiyon
**********************************************************************************/
void multip_array(int *a, int *b, int *c, int k, int m, int n){
 int i,j,l;
 int sum = 0;
 for(l=0;l<n;l++)
  for(i=0;i<k;i++){
   for(j=0;j<m;j++)
   sum += *(a+j+i*k)**(b+j*n+l);
   *(c+i*n+l) = sum;
   sum = 0;
  }
}
int main(){
srand(time(NULL));
 int k,m,n;
 int x = 0;
 int i,j,z,l;
 int sayac = 0;
 cout <<  "Matrislerin Boyutlarini Girin (k,m,n seklinde)" <<endl;
 cin >> k >> m >> n;
 
 //a dizisi için hafızadan yer alınıyor ve dizi oluşturuluyor
 int **a;
 a = new int*[k];
 for(i=0;i<k;i++)
  a[i] = new int[m];
 for(j=0;j<k;j++)
  for(z=0;z<m;z++)
   a[j][z] = rand()%6;
 //a dizisinin elemanlar ekrana bastırılıyor
 cout << "1.matris"<<endl;
 for(i=0;i<k;i++)
  for(j=0;j<m;j++){
   cout << a[i][j]<<" ";
   sayac++;
   if(sayac == m){
    cout<<endl;
    sayac = 0; 
   }
  }
 cout << endl;

 //b dizisi için hafızadan yer alınıyor ve dizi oluşturuluyor
 int **b ;
 b = new int*[m];
 for(i=0;i<m;i++)
  b[i] = new int[n];
 for(j=0;j<m;j++)
  for(z=0;z<n;z++)
   b[j][z] = rand()%6;
 //b dizisinin elemanlar ekrana bastırılıyor
 cout << "2.matris"<<endl;
 for(i=0;i<m;i++)
  for(j=0;j<n;j++){
   cout << b[i][j]<<" ";
   sayac++;
   if(sayac == n){
    cout<<endl;
    sayac = 0; 
   }
  }
  
 cout << endl;

 //c dizisi için hafızadan yer alınıyor ve dizi oluşturuluyor
 int **c = new int*[k];
 for(i=0;i<k;i++)
  c[i] = new int[n];
 
 system("pause");
 //multip_matrix fonksiyon çağrısı
 multip_matrix(a,b,c,k,m,n);

 //multip matrix fonksiyonu ile oluşturulan iki boyutlu çarpım dizisinin ekrana bastırılması
 cout << "carpim matrisi"<<endl;
 for(i=0;i<k;i++)
  for(j=0;j<n;j++){
   printf("%2d ",c[i][j]);
   sayac++;
   if(sayac == n){
    cout<<endl;
    sayac = 0; 
   }
  }
 //tek boyutlu diziler icin hafızadan yer alınıyor
 int *dizi1 = new int[k*m];
 int *dizi2 = new int[m*n];
 int *dizi3 = new int[k*n];
  
 for(i=0;i<k;i++)
  for(j=0;j<m;j++){
   dizi1[x] = a[i][j];
   x++;
  }
  x=0;
 for(i=0;i<m;i++)
  for(j=0;j<n;j++){
   dizi2[x] = b[i][j];
   x++;
  }
 cout<<endl;
 system("pause");
 //multip_array fonksiyon çağrısı
 multip_array(dizi1,dizi2,dizi3,k,m,n);
 //multip array fonksiyonu ile oluşturulan tek boyutlu çarpım dizisinin ekrana bastırılması
 for(i=0;i<k*n;i++)
  cout<< *(dizi3+i) <<" ";
  cout<<endl;
  
 //Her bir dizi için bellekten alınan yerler geri veriliyor 
for(i=0;i<k*m;i++)
 delete  a[i];//Try This
 delete [] a;
for(i=0;i<m*n;i++)
 delete  b[i];//Try This
 delete [] b;
 delete [] dizi1;
 delete [] dizi2;
 delete [] dizi3;

 system("pause");
 
return 0;
}

Ekran çıktısı aşağıdaki gibidir

Saturday 11 February 2012

Java-Adding an Image

images.java

If you want to debug this class, then you should use class that FullScreen.java
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
public class images extends JFrame{

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  DisplayMode dm = new DisplayMode(800,600,16,DisplayMode.REFRESH_RATE_UNKNOWN);
  images i = new images();
  i.run(dm);
 } 
  
 private FullScreen s; 
 private Image bg;
 private Image pic;
        private Image ani;
 private boolean loaded;
 //run method
 public void run(DisplayMode dm){
  setBackground(Color.WHITE);
  setForeground(Color.BLACK);
  setFont(new Font("Arial",Font.PLAIN,24));
  loaded = false;
  s = new  FullScreen();
  try{
   s.setFullScreen(dm, this);
   loadpics();
   try{
    
    Thread.sleep(3000);//milliseconds
    
   }catch(Exception ex){}
  }finally{
   s.restoreScreen();
  }
 }
 
 //load pictures
 public void loadpics(){
  bg = new ImageIcon("C:\\anywhere.jpg").getImage();
  pic = new ImageIcon("C:\\anywhere.png").getImage();
                ani = new ImageIcon("C:\\anywhere.gif").getImage();
  loaded = true;
  repaint();
 }
 
 public void paint(Graphics g){
  if(g instanceof Graphics2D){
   Graphics2D g2 = (Graphics2D)g;
   g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
  }
  if(loaded){
   g.drawImage(bg, 30, 30, null);
   g.drawImage(pic, 170, 180, null);
   g.drawImage(ani,100,100,null);
  }
  
 }
 
 
}

Friday 10 February 2012

Java-Full Screen App

burkan.java


import java.awt.*;
import javax.swing.JFrame;
public class burkan extends JFrame{

 /**
  * @param args
  */
public static void main(String[] args) {
 // TODO Auto-generated method stub
 DisplayMode dm = new DisplayMode(800,600,16,DisplayMode.REFRESH_RATE_UNKNOWN);
 burkan b = new burkan();
 b.run(dm);
}

public void run(DisplayMode dm){
    setBackground(Color.WHITE);
    setForeground(Color.BLACK);
    setFont(new Font("Arial",Font.PLAIN,24));
  
    FullScreen s = new  FullScreen();
    try{
    s.setFullScreen(dm, this);
    try{
  
    Thread.sleep(3000);
   
    }catch(Exception ex){}
    }finally{
    s.restoreScreen();
    }
}
 
public void paint(Graphics g){
 if(g instanceof Graphics2D){
  Graphics2D g2 = (Graphics2D)g;
  g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
 }
  g.drawString("Hello World!!!", 200, 200);
 } 
}

FullScreen.java

import javax.swing.JFrame;
import java.awt.*;
public class FullScreen {
 private GraphicsDevice vc;
 
 public FullScreen(){
  
  GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
  vc = env.getDefaultScreenDevice();
  
 }
 
 public void setFullScreen(DisplayMode dm,JFrame window){
  
  window.setUndecorated(true);
  window.setResizable(false);
  vc.setFullScreenWindow(window);
  
  if(dm != null && vc.isDisplayChangeSupported()){
   
   try{
    vc.setDisplayMode(dm);
   }catch(Exception ex){}
   
  }
 }
 public Window getFullScreenWindow(){
 
  return vc.getFullScreenWindow();
 
 }
 
 public void restoreScreen(){
  Window w = vc.getFullScreenWindow();
  if(w != null){
   w.dispose();
  }
  vc.setFullScreenWindow(null);
 }
  
}

Saturday 4 February 2012

Java - Thread

burkan.java

import javax.swing.*;
public class burkan {
 public static void main(String[] args){
   
  
 Thread t1 = new Thread(new threads(300,300,1500));
 Thread t2 = new Thread(new threads(250,250,3500));
 Thread t3 = new Thread(new threads(200,200,6500));
 Thread t4 = new Thread(new threads(100,100,8500));
 Thread t5 = new Thread(new threads(50,50,10500));
   
 t1.start();
 t2.start();
 t3.start();
 t4.start();
 t5.start();
 }
}



graphics.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class graphics extends JPanel{
 private int a,b;
 public graphics(int i, int j) {
   //constructor
   a=i;
   b=j;
 }

 public void paintComponent(Graphics g){
 super.paintComponents(g);
 this.setBackground(Color.WHITE);
   
 g.setColor(Color.blue);
 g.drawRect(100,100, a, b);
    
  }
    
  
   
  
}


threads.java

import java.util.*;
import java.awt.*;
import javax.swing.*;
 public class threads implements Runnable{
 private int x,y;
 public int time;
 public JFrame f = new JFrame("LOOP");
 
 public threads(int a,int b,int t){
  //constructor
  x=a;
  y=b;
  time = t;
  
 }
 
 
    public void run(){
     
     try{
      Thread.sleep(time);
   graphics p = new graphics(x,y);

   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.setSize(800,600);
   f.setVisible(true);
   f.add(p);
     
     }catch(Exception e){}
     
    }
}

Monday 16 January 2012

How to create binary tree

#include<iostream>
#include<stdio.h>
#include<time.h>
#include<iomanip>
#include<conio.h>
#define dimension 11
using namespace std;

struct tree{
 int value;
 tree *leftptr;
 tree *rightptr;
};
typedef tree Tree;
typedef Tree *treePtr;
void create(treePtr *,int);
void silme(treePtr *);
void remove(treePtr);
void inorder(treePtr);
void postorder(treePtr);
void preorder(treePtr);
void go_array(treePtr,int[],int *);
void main(){
 srand(time(NULL));
 int val,i,key;  //val means value, i means counter , key is keyboard input
 int counter=0;
 int arrayx[dimension]={0};
 treePtr root = NULL;
 for(i=0;i<11;i++){

  val = rand()%999+1;
  create(&root,val);
 }

 go_array(root,arrayx,&counter);
 cout << "inorder scanning..." << endl;
 inorder(root);
 cout <<endl<<"Preorder scanning..."<<endl;
 preorder(root);
 cout <<endl<<"Postorder scanning..."<<endl;
 postorder(root);
 cout<<endl;
 cout << "Array : "<<endl;
 for(i=0;i<11;i++)
  cout <<arrayx[i] <<"  ";
 cout<<endl;
 cout <<"Sayac = "<<counter<<endl;
 cout <<endl<< "Press 1 to delete a node from to tree or 0 to pass and exit : ";
 cin.ignore(0,'\n');
 cin>>key;
 cout << key<<endl;
 if(key==1)
 remove(root);
 inorder(root);
 getch();
}
void create(treePtr *proot,int qvalue){
 treePtr tara,yeni;
 yeni = new Tree;
 tara = *proot;
 yeni->value=qvalue;
 yeni->leftptr = NULL;
 yeni->rightptr = NULL;
 bool bulundu = false;
 if((*proot)==NULL){//ilk düğüm ekleniyor
  *proot = yeni;
 }
 while(tara!=NULL && bulundu!=true){
  if(qvalue<tara->value){
   if(tara->leftptr!=NULL)
    tara=tara->leftptr;
   else{
    tara->leftptr = yeni;
    bulundu = true;
   }     
  }
  else if(qvalue>tara->value){
    if(tara->rightptr!=NULL)
     tara=tara->rightptr;
    else{
     tara->rightptr = yeni;
     bulundu = true;
    }
  }
  else 
   break;
 }
}
void inorder(treePtr p){
 if(p){
  inorder(p->leftptr);
  cout << p->value <<"  ";
  inorder(p->rightptr);
 }
}
void postorder(treePtr p){
 if(p){
  inorder(p->leftptr);
  inorder(p->rightptr);
  cout << p->value <<"  ";
  
 }
}
void preorder(treePtr p){
 if(p){
  cout << p->value <<"  ";
  inorder(p->leftptr);
  inorder(p->rightptr);
 }
}
void go_array(treePtr p,int q[dimension],int *s){

 if(p){
  
  go_array(p->leftptr,q,s);
  q[*s]=p->value;
  (*s)++;
  go_array(p->rightptr,q,s);
  
  
 }
}
void remove(treePtr p){
 
 int sil;
 cout << "NE SILMEK ISTIYORSUN : ";
 cin.ignore(2,'\n');
 cin >> sil;
 char yon;
 treePtr tara,ust;
 tara = p;
 bool var = false;
 while(tara && var!=true){
  if(sil<tara->value){
    ust=tara;
    yon = 'l';
    tara=tara->leftptr;
  }else if(sil>tara->value){
    ust=tara;
    yon = 'r';
    tara=tara->rightptr;
  }else
   var = true;
 }
 if(var==true){
  if(yon=='l')
   silme(&(ust->leftptr));
  else if(yon=='r')
   silme(&(ust->rightptr));
  else 
   silme(&p);
 }
 else
  cout << "HATA" <<endl;

}
void silme(treePtr *s){
 treePtr r,q;
 r=*s;
 if(r==NULL)
  return;
 else if(r->rightptr==NULL){
  *s=r->leftptr;
  delete r;
 }
 else if(r->leftptr==NULL){
  *s=r->rightptr;
  delete r;
 }
 else {
  for(q=r->rightptr;q->leftptr;q=q->leftptr);
  q=r->leftptr;
  *s=r->rightptr;
  delete r;
 }

}

Syntax Highligter 3 and Blogspot

Syntax Highlighter version 3.0.83 has been released and there are quite a few changes in the way things work now. I realized this when the rendering on this site broke after I modified it to use the latest release. So, here is the steps required to setup the "hosted" version of the latest Syntax Highlighter (version 3.0.83) and integrate with your Blogger/Blogspot blog.

Installation

  1. Navigate to Dashboard > Design > Edit HTML
  2. Backup the current template by clicking on the link Download Full Template
  3. In the textarea, press CTRL+F to find the code </head>
  4. Copy the below code and paste it just above

And Save it if you want to add another languages,gooo.
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>
Moreover,you can replace shThemeDefault in the above line with any one of the following themes:
Django - shThemeDjango
Eclipse - shThemeEclipse
Emacs - shThemeEmacs
Fade to Grey - shThemeFadeToGrey
Midnight - shThemeMidnight
RDark - shThemeRDark

Usage

To use it in your blog post, there are a couple of things that need to be done.
  1. Escape all code by replacing any occurrences of:
    1. < with &lt;
    2. > with &gt;
  2. Enclose the escaped code between <pre class="brush:[brush_name];[optional_params]"> and </pre>
  3. Setup the proper brush name (based on the code being highlighted) in the opening pre tag. Using the correct brush will ensure proper highlighting of the code

Tuesday 10 January 2012

Basic File Reading in C

#include< stdio.h>
#include< stdlib.h>
int main()
{
int hesap;
char ad[30];
double bakiye;
FILE*fPtr;
fPtr=fopen("musteri.txt","r");
if(fPtr==NULL)
printf("Dosya Bozuk!!!");
else{
printf("%-10s%-13s%s\n","hesap","isim","bakiye");
fscanf(fPtr,"%d%s%lf",&hesap,ad,&bakiye);

while(!feof(fPtr)){
printf("%-10d%-13s%7.2f\n",hesap,ad,bakiye);
fscanf(fPtr,"%d%s%lf",&hesap,ad,&bakiye);
}
fclose(fPtr);
}
system("pause");
return 0;
}
    

Write Sequential File in C


#include< stdio.h>
#include< stdlib.h>

int main()
{
    int hesap;
    char isim[30];
    double bakiye;
    
    FILE*cfPtr;
    
    if((cfPtr=fopen("musteri.txt","w"))==NULL)
    printf("Dosya acilamadi\n");
    else{
         printf("Hesap numarasini,ismi ve bakiyeyi giriniz.\n");
         printf("EOF ile veri girisini sonlandiriniz\n");
         printf("? ");
         scanf("%d%s%lf",&hesap,isim,&bakiye);
         
         while(!feof(stdin))
         {
                fprintf(cfPtr,"%d %s %.2f\n",hesap,isim,bakiye);
                printf("? ");
                scanf("%d%s%lf",&hesap,isim,&bakiye);            
                            
                            }
         fclose(cfPtr);
         }
    system("pause");
    return 0;
    
    }

Random Access File Writing in C

#include< stdio.h>

struct musteriVerisi{
int hesapNo;
char soyisim[15];
char isim[10];
double bakiye;
};
int main(){
    FILE*cfPtr;
    struct musteriVerisi musteri={0,"","",0.0};
    if((cfPtr=fopen("kredi.dat","r+"))==NULL)
    printf("Dosya acilamiyor\n");
    else{
        printf("Hesap numarasini giriniz(1-100)\n");
    scanf("%d",&musteri.hesapNo);
    while(musteri.hesapNo!=0)
    {
    printf("soyisim,isim,bakiye giriniz\n");
    fscanf(stdin,"%s%s%lf",musteri.soyisim,musteri.isim,&musteri.bakiye);
    fseek(cfPtr,(musteri.hesapNo-1)*sizeof(struct musteriVerisi),SEEK_SET);
    fwrite(&musteri,sizeof(struct musteriVerisi),1,cfPtr);
    printf("Hesap numarasini giriniz(1-100)\n");
    scanf("%d",&musteri.hesapNo);         
        } 
        fclose(cfPtr);
        
    }   
getch();
return 0;
}

Random Access File Reading in C

#include

struct musteriVerisi{
   int hesapNo;
   char soyisim[15];
   char isim[10];
   double bakiye;
   };
int main()
{
FILE*cfPtr;
struct musteriVerisi musteri={0,"","",0.0};
if((cfPtr=fopen("kredi.dat","r"))==NULL)
printf("Dosya acilamiyor\n");
else{
 printf("%-6s%-16s%-11s%10s\n","HspNo","Soyisim","Isim","Bakiye");
     while(!feof(cfPtr))
 {
 fread(&musteri,sizeof(struct musteriVerisi),1,cfPtr);
 
 if(musteri.hesapNo!=0)
 printf("%-6d%-16s%-11s%10.2f\n",musteri.hesapNo,
musteri.soyisim,musteri.isim,musteri.bakiye);        
     } 
     fclose(cfPtr);
 }
 getch();
 return 0;
}

Simple Poker Game in C

#include
#include
#include
#include
/*#define SATIR 4
#define SUTUN 13*/
void desteyikar(int[][13]);
void desteyidagit(int[][13],const char*[],const char*[]);
void durum(int[][13],const char*[],const char*[]);
//int yeniden(void);

//void renk(char*[],char*[]);
int main()
{
    int again;
    const char*takim[4]={"kupa","karo","sinek","maca"};
    const char*taraf[13]={"as","iki","uc","dOrt","bes","alti","yedi","sekiz","dokuz","on","vale","kiz","papaz"};
      int deste[4][13]={0};
      char secim;
      
      
    
  
   printf("Poker oynamak ister misin E/H ? ");
 scanf("%c",&secim);
   if(secim!='h')
   {
   srand(time(0));
   desteyikar(deste);
  
   desteyidagit(deste,taraf,takim);
 
   durum(deste,taraf,takim);
  /*printf("Tekrar oynamak ister misin ? E/H");
  scanf("%c",&secim);*/
}

    getch();
    
    return 0;
       
}
void desteyikar(int adeste[][13])
{
    int satir,sutun,kart;

    for(kart=1;kart<=52;kart++)
    {
    do{
    satir=rand()%4;
    sutun=rand()%13;
    }while(adeste[satir][sutun]!=0);
    
    adeste[satir][sutun]=kart;
    }
}

void desteyidagit(int adeste[][13],const char*ataraf[],const char*atakim[])
{    
     
    
     int kart,satir,sutun;
     printf("Your hand is \n\n");
     for(kart=1;kart<=5;kart++)
     for(satir=0;satir<=3;satir++)
     for(sutun=0;sutun<=12;sutun++)
  
     if(adeste[satir][sutun]==kart)
     { 
     printf("%5s %-8s\t",atakim[satir],ataraf[sutun]);
     }
     printf("\nMy hand is \n\n");
     for(kart=6;kart<=10;kart++)
     for(satir=0;satir<=3;satir++)
     for(sutun=0;sutun<=12;sutun++)
  
     if(adeste[satir][sutun]==kart)
     { 
     printf("%5s %-8s\t",atakim[satir],ataraf[sutun]);
     }

}

void durum(int adeste[][13],const char*ataraf[],const char*atakim[])
{ 
      int kart,satir,sutun,r=0,q=0;
      char s1[5],s2[5],s3[5],s4[5],s5[5],s6[5],s7[5],s8[5],s9[5],s10[5];
      int buyukluk[10],i;
     for(kart=1;kart<=10;kart++)
     for(satir=0;satir<=3;satir++)
     for(sutun=1;sutun<=12;sutun++)
    { 
     if(adeste[satir][sutun]==1)
     { 
      
         
     *s1=*ataraf[sutun];
     *(s1+1)=*(ataraf[sutun]+1);
 *(s1+2)=*(ataraf[sutun]+2);
 *(s1+3)=*(ataraf[sutun]+3);
 *(s1+4)=*(ataraf[sutun]+4);                           
     }
     if(adeste[satir][sutun]==2)
     {  
    
     *s2=*ataraf[sutun];
     *(s2+1)=*(ataraf[sutun]+1);
 *(s2+2)=*(ataraf[sutun]+2);
 *(s2+3)=*(ataraf[sutun]+3);
 *(s2+4)=*(ataraf[sutun]+4);                      
    
     }
     if(adeste[satir][sutun]==3)
     { 
   *s3=*ataraf[sutun];
     *(s3+1)=*(ataraf[sutun]+1);
 *(s3+2)=*(ataraf[sutun]+2);
 *(s3+3)=*(ataraf[sutun]+3);
 *(s3+4)=*(ataraf[sutun]+4);
   
     }
     if(adeste[satir][sutun]==4)
     { 
   *s4=*ataraf[sutun];
     *(s4+1)=*(ataraf[sutun]+1);
 *(s4+2)=*(ataraf[sutun]+2);
 *(s4+3)=*(ataraf[sutun]+3);
 *(s4+4)=*(ataraf[sutun]+4);
  
     }
     if(adeste[satir][sutun]==5)
     { 
   *s5=*ataraf[sutun];
     *(s5+1)=*(ataraf[sutun]+1);
 *(s5+2)=*(ataraf[sutun]+2);
 *(s5+3)=*(ataraf[sutun]+3);
 *(s5+4)=*(ataraf[sutun]+4);
     }
     if(adeste[satir][sutun]==6)
     {
  for(i=0;i<=4;i++)
  *(s6+i)=*(ataraf[sutun]+i);       
     }
     if(adeste[satir][sutun]==7)
     {
  for(i=0;i<=4;i++)
  *(s7+i)=*(ataraf[sutun]+i);       
     }
     if(adeste[satir][sutun]==8)
     {
  for(i=0;i<=4;i++)
  *(s8+i)=*(ataraf[sutun]+i);       
     }
     if(adeste[satir][sutun]==9)
     {
  for(i=0;i<=4;i++)
  *(s9+i)=*(ataraf[sutun]+i);       
     }
     if(adeste[satir][sutun]==10)
     {
  for(i=0;i<=4;i++)
  *(s10+i)=*(ataraf[sutun]+i);       
     }
    }

    buyukluk[0]=sizeof(s1)/sizeof(char);
    buyukluk[1]=sizeof(s2)/sizeof(char);
    buyukluk[2]=sizeof(s3)/sizeof(char);
    buyukluk[3]=sizeof(s4)/sizeof(char);
    buyukluk[4]=sizeof(s5)/sizeof(char);
    buyukluk[5]=sizeof(s6)/sizeof(char);
    buyukluk[6]=sizeof(s7)/sizeof(char);
    buyukluk[7]=sizeof(s8)/sizeof(char);
    buyukluk[8]=sizeof(s9)/sizeof(char);
    buyukluk[9]=sizeof(s10)/sizeof(char);
    

    if(buyukluk[0]==buyukluk[1])
      if((*s1==*s2)&&(*(s1+1)==*(s2+1)))
  r++;
 if(buyukluk[0]==buyukluk[2])
      if((*s1==*s3)&&(*(s1+1)==*(s3+1)))
  r++;
     if(buyukluk[0]==buyukluk[3])
      if((*s1==*s4)&&(*(s1+1)==*(s4+1)))
  r++;
     if(buyukluk[0]==buyukluk[4])
      if((*s1==*s5)&&(*(s1+1)==*(s5+1)))
  r++;
     if(buyukluk[1]==buyukluk[2])
      if((*s2==*s3)&&(*(s2+1)==*(s3+1)))
  r++;
     if(buyukluk[1]==buyukluk[3])
      if((*s2==*s4)&&(*(s2+1)==*(s4+1)))
  r++;  
  if(buyukluk[1]==buyukluk[4])
      if((*s2==*s5)&&(*(s2+1)==*(s5+1)))
  r++;
 if(buyukluk[2]==buyukluk[3])
      if((*s3==*s4)&&(*(s3+1)==*(s4+1)))
  r++;
     if(buyukluk[2]==buyukluk[3])
      if((*s3==*s5)&&(*(s3+1)==*(s5+1)))
  r++;
     if(buyukluk[3]==buyukluk[4])
      if((*s4==*s5)&&(*(s4+1)==*(s5+1)))
  r++;
     
    if(buyukluk[5]==buyukluk[6])
      if((*s5==*s6)&&(*(s5+1)==*(s6+1)))
  q++;
 if(buyukluk[5]==buyukluk[7])
      if((*s5==*s7)&&(*(s5+1)==*(s7+1)))
  q++;
     if(buyukluk[5]==buyukluk[8])
      if((*s5==*s8)&&(*(s5+1)==*(s8+1)))
  q++;
     if(buyukluk[5]==buyukluk[9])
      if((*s5==*s9)&&(*(s5+1)==*(s9+1)))
  q++;
     if(buyukluk[6]==buyukluk[7])
      if((*s6==*s7)&&(*(s6+1)==*(s7+1)))
  q++;
     if(buyukluk[6]==buyukluk[8])
      if((*s6==*s8)&&(*(s6+1)==*(s8+1)))
  q++;  
  if(buyukluk[6]==buyukluk[9])
      if((*s6==*s9)&&(*(s6+1)==*(s9+1)))
  q++;
 if(buyukluk[7]==buyukluk[8])
      if((*s7==*s8)&&(*(s7+1)==*(s8+1)))
  q++;
     if(buyukluk[7]==buyukluk[9])
      if((*s7==*s9)&&(*(s7+1)==*(s9+1)))
  q++;
     if(buyukluk[8]==buyukluk[9])
      if((*s8==*s9)&&(*(s8+1)==*(s9+1)))
  q++;
    
     
    if(r==1)
    printf("\nYour hand has One pair\n");
    if(r==2)
    printf("\nYour hand has Two pair\n"); 
    if(r==3)
    printf("\nYour hand has Three of a Kind\n");
    if(r==6)
    printf("\nYour hand has Four of a Kind\n");
    printf("\n\n");

    if(q==1)
    printf("\nMy hand has One pair\n");
    if(q==2)
    printf("\nMy hand has Two pair\n"); 
    if(q==3)
    printf("\nMy hand has Three of a Kind\n");
    if(q==6)
    printf("\nMy hand has Four of a Kind\n");
    printf("\n-------------------------------------------\n");
    if(r>q)
    printf("Your hand is winner\n");
    if(q>r)
    printf("My hand is winner\n");
    if(q==r)
    printf("Draw\n");
}
  


Magic Square

#include <stdio.h>
#include<stdlib.h>
int main()
{   
    int k,i,j,n;
    int row,col,newRow,newCol; 
int square[20][20];  //boyut arttırılabilir
    printf("matrisin boyutunu giriniz...\n");
scanf("%d",&n);
    for(i=0;i<n;i++) {
        for(j=0;j<n;j++) {
                square[i][j]=0;
        }
    }

    row=1;
    col=(n+1)/2;
    k=1;
    square[row-1][col-1]=k;


    for(k=2;k<=n*n;k++)
    {
        newRow=row-1;
        newCol=col+1;
        if (newRow==0&&newCol==(n+1))
        {
            newRow=row+1;
            newCol=n;
            row=newRow;
            col=newCol;
            square[row-1][col-1]=k;
        }
        else
        {
            while(newRow==0) //while if ile degistirilebilir
            {
            newRow=n;
            }
            while(newCol==(n+1))
            {
                newCol=1;
            }
            if(square[newRow-1][newCol-1]==0)
            {
                row=newRow;
                col=newCol;
                square[row-1][col-1]=k;
            }
            else
            {
                newRow=row+1;
                newCol=col;
                while(newRow==(n+1))
                {
                    newRow=1;
                }
                    row=newRow;
                    col=newCol;
                    square[row-1][col-1]=k;
            }
        }
    }
printf("%d*%d magic square:\n",n,n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d ",square[i][j]);
}
printf("\n");
}
     system("pause");
    return 0;
}

Monday 9 January 2012

Ms-Dos codes

   ADDUSERS Add or list users to/from a CSV file
   ADmodcmd Active Directory Bulk Modify
   ARP      Address Resolution Protocol
   ASSOC    Change file extension associations•
   ASSOCIAT One step file association
   ATTRIB   Change file attributes
b
   BCDBOOT  Create or repair a system partition
   BOOTCFG  Edit Windows boot settings
   BROWSTAT Get domain, browser and PDC info
c
   CACLS    Change file permissions
   CALL     Call one batch program from another•
   CD       Change Directory - move to a specific Folder•
   CHANGE   Change Terminal Server Session properties
   CHKDSK   Check Disk - check and repair disk problems
   CHKNTFS  Check the NTFS file system
   CHOICE   Accept keyboard input to a batch file
   CIPHER   Encrypt or Decrypt files/folders
   CleanMgr Automated cleanup of Temp files, recycle bin
   CLEARMEM Clear memory leaks
   CLIP     Copy STDIN to the Windows clipboard.
   CLS      Clear the screen•
   CLUSTER  Windows Clustering
   CMD      Start a new CMD shell
   CMDKEY   Manage stored usernames/passwords
   COLOR    Change colors of the CMD window•
   COMP     Compare the contents of two files or sets of files
   COMPACT  Compress files or folders on an NTFS partition
   COMPRESS Compress individual files on an NTFS partition
   CON2PRT  Connect or disconnect a Printer
   CONVERT  Convert a FAT drive to NTFS.
   COPY     Copy one or more files to another location•
   CSCcmd   Client-side caching (Offline Files)
   CSVDE    Import or Export Active Directory data 
d
   DATE     Display or set the date•
   DEFRAG   Defragment hard drive
   DEL      Delete one or more files•
   DELPROF  Delete NT user profiles
   DELTREE  Delete a folder and all subfolders
   DevCon   Device Manager Command Line Utility 
   DIR      Display a list of files and folders•
   DIRUSE   Display disk usage
   DISKCOMP Compare the contents of two floppy disks
   DISKCOPY Copy the contents of one floppy disk to another
   DISKPART Disk Administration
   DNSSTAT  DNS Statistics
   DOSKEY   Edit command line, recall commands, and create macros
   DSACLs   Active Directory ACLs
   DSAdd    Add items to active directory (user group computer) 
   DSGet    View items in active directory (user group computer)
   DSQuery  Search for items in active directory (user group computer)
   DSMod    Modify items in active directory (user group computer)
   DSMove   Move an Active directory Object
   DSRM     Remove items from Active Directory
e
   ECHO     Display message on screen•
   ENDLOCAL End localisation of environment changes in a batch file•
   ERASE    Delete one or more files•
   EVENTCREATE Add a message to the Windows event log
   EXIT     Quit the current script/routine and set an errorlevel•
   EXPAND   Uncompress files
   EXTRACT  Uncompress CAB files
f
   FC       Compare two files
   FIND     Search for a text string in a file
   FINDSTR  Search for strings in files
   FOR /F   Loop command: against a set of files•
   FOR /F   Loop command: against the results of another command•
   FOR      Loop command: all options Files, Directory, List•
   FORFILES Batch process multiple files
   FORMAT   Format a disk
   FREEDISK Check free disk space (in bytes)
   FSUTIL   File and Volume utilities
   FTP      File Transfer Protocol
   FTYPE    Display or modify file types used in file extension associations•
g
   GLOBAL   Display membership of global groups
   GOTO     Direct a batch program to jump to a labelled line•
   GPUPDATE Update Group Policy settings
h
   HELP     Online Help
i
   iCACLS   Change file and folder permissions
   IF       Conditionally perform a command•
   IFMEMBER Is the current user in an NT Workgroup
   IPCONFIG Configure IP
k
   KILL     Remove a program from memory
l
   LABEL    Edit a disk label
   LOCAL    Display membership of local groups
   LOGEVENT Write text to the NT event viewer
   LOGMAN   Manage Performance Monitor
   LOGOFF   Log a user off
   LOGTIME  Log the date and time in a file
m
   MAPISEND Send email from the command line
   MBSAcli  Baseline Security Analyzer. 
   MEM      Display memory usage
   MD       Create new folders•
   MKLINK   Create a symbolic link (linkd)
   MODE     Configure a system device
   MORE     Display output, one screen at a time
   MOUNTVOL Manage a volume mount point
   MOVE     Move files from one folder to another•
   MOVEUSER Move a user from one domain to another
   MSG      Send a message
   MSIEXEC  Microsoft Windows Installer
   MSINFO32 System Information
   MSTSC    Terminal Server Connection (Remote Desktop Protocol)
   MV       Copy in-use files
n
   NET      Manage network resources
   NETDOM   Domain Manager
   NETSH    Configure Network Interfaces, Windows Firewall & Remote access
   NETSVC   Command-line Service Controller
   NBTSTAT  Display networking statistics (NetBIOS over TCP/IP)
   NETSTAT  Display networking statistics (TCP/IP)
   NOW      Display the current Date and Time 
   NSLOOKUP Name server lookup
   NTBACKUP Backup folders to tape
   NTRIGHTS Edit user account rights
o
   OPENFILES Query or display open files
p
   PATH     Display or set a search path for executable files•
   PATHPING Trace route plus network latency and packet loss
   PAUSE    Suspend processing of a batch file and display a message•
   PERMS    Show permissions for a user
   PERFMON  Performance Monitor
   PING     Test a network connection
   POPD     Restore the previous value of the current directory saved by PUSHD•
   PORTQRY  Display the status of ports and services
   POWERCFG Configure power settings
   PRINT    Print a text file
   PRINTBRM Print queue Backup/Recovery
   PRNCNFG  Display, configure or rename a printer
   PRNMNGR  Add, delete, list printers set the default printer
   PROMPT   Change the command prompt•
   PsExec     Execute process remotely
   PsFile     Show files opened remotely
   PsGetSid   Display the SID of a computer or a user
   PsInfo     List information about a system
   PsKill     Kill processes by name or process ID
   PsList     List detailed information about processes
   PsLoggedOn Who's logged on (locally or via resource sharing)
   PsLogList  Event log records
   PsPasswd   Change account password
   PsService  View and control services
   PsShutdown Shutdown or reboot a computer
   PsSuspend  Suspend processes
   PUSHD    Save and then change the current directory•
q
   QGREP    Search file(s) for lines that match a given pattern.
r
   RASDIAL  Manage RAS connections
   RASPHONE Manage RAS connections
   RECOVER  Recover a damaged file from a defective disk.
   REG      Registry: Read, Set, Export, Delete keys and values
   REGEDIT  Import or export registry settings
   REGSVR32 Register or unregister a DLL
   REGINI   Change Registry Permissions
   REM      Record comments (remarks) in a batch file•
   REN      Rename a file or files•
   REPLACE  Replace or update one file with another
   RD       Delete folder(s)•
   RMTSHARE Share a folder or a printer
   ROBOCOPY Robust File and Folder Copy
   ROUTE    Manipulate network routing tables
   RUN      Start | RUN commands
   RUNAS    Execute a program under a different user account
   RUNDLL32 Run a DLL command (add/remove print connections)
s
   SC       Service Control
   SCHTASKS Schedule a command to run at a specific time
   SCLIST   Display NT Services
   SET      Display, set, or remove environment variables•
   SETLOCAL Control the visibility of environment variables•
   SETX     Set environment variables permanently
   SFC      System File Checker 
   SHARE    List or edit a file share or print share
   SHIFT    Shift the position of replaceable parameters in a batch file•
   SHORTCUT Create a windows shortcut (.LNK file)
   SHOWGRPS List the NT Workgroups a user has joined
   SHOWMBRS List the Users who are members of a Workgroup
   SHUTDOWN Shutdown the computer
   SLEEP    Wait for x seconds
   SLMGR    Software Licensing Management (Vista/2008)
   SOON     Schedule a command to run in the near future
   SORT     Sort input
   START    Start a program or command in a separate window•
   SU       Switch User
   SUBINACL Edit file and folder Permissions, Ownership and Domain
   SUBST    Associate a path with a drive letter
   SYSTEMINFO List system configuration
t
   TASKLIST List running applications and services
   TASKKILL Remove a running process from memory
   TIME     Display or set the system time•
   TIMEOUT  Delay processing of a batch file
   TITLE    Set the window title for a CMD.EXE session•
   TLIST    Task list with full path
   TOUCH    Change file timestamps    
   TRACERT  Trace route to a remote host
   TREE     Graphical display of folder structure
   TSSHUTDN Remotely shut down or reboot a terminal server
   TYPE     Display the contents of a text file•
   TypePerf Write performance data to a log file
u
   USRSTAT  List domain usernames and last login
v
   VER      Display version information•
   VERIFY   Verify that files have been saved•
   VOL      Display a disk label•
w
   WAITFOR  Wait for or send a signal
   WHERE    Locate and display files in a directory tree
   WHOAMI   Output the current UserName and domain
   WINDIFF  Compare the contents of two files or sets of files
   WINMSDP  Windows system report
   WINRM    Windows Remote Management
   WINRS    Windows Remote Shell
   WMIC     WMI Commands
   WUAUCLT  Windows Update
x
   XCACLS   Change file and folder permissions
   XCOPY    Copy files and folders
   ::       Comment / Remark•