Sunday, 5 May 2019

Redbox Game Studios - Solitaire #1


Ultimate Classic Solitaire card game 

New experience and joy Solitaire, also known as Klondike, Solitaire or Patience, is the most popular single player card game in the world. If you like classic Solitaire, you're going to love this crisp and clear solitaire game!

Game Features: 

• FREE
• Beautiful graphics
• Klondike Solitaire Draw 1 card
• Klondike Solitaire Draw 3 cards
• Option for all winning deals
• Auto complete
• Unlimited free undos
• Unlimited free hints
• Intelligent hints and auto hints
• Daily Challenge
• Timed mode and Untimed mode
• Vegas scoring and Vegas cumulative scoring
• Customizable card faces, card backs and backgrounds
• High scores and personal statistics
• Sound that can be turned on/off
• Tablet and phone support
• Multiple windows and tasks support
• No network required
• And so much more!

 


Play the #1 FREE SOLITAIRE card game on Android Play Store and AppStore now and see for yourself why so many others love this game!
Facebook : https://www.facebook.com/RedboXGameStudios/
Twitter : https://twitter.com/studio_redbox
Instagram : https://www.instagram.com/redboxgamestudios/
Pinterest : https://www.pinterest.com/redboxgamestudios/
Youtube : https://www.youtube.com/channel/UCucroP4IAXm5Ks6gKta2L7g
Dailymotion : https://www.dailymotion.com/redbox-game-studios

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