Vous êtes sur la page 1sur 86

------------------------------------(1) SPECIAL MESSAGE ------------------------------------package javaapplication22; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.

*; public class vacation extends JFrame { ShapeCanvas canvas; public vacation() { canvas = new ShapeCanvas(); JButton button = new JButton("Next"); //declares object or event source class moveAllListener implements ActionListener { public void actionPerformed(ActionEvent e) { canvas.repaint(); //certifies the ActionListener command canvas.moveAll(); //calls moveAll class to move objects } } button.addActionListener(new moveAllListener()); setLayout(new BorderLayout()); setTitle( "Happy Happy Vacation!" ); setSize( 800, 600 ); // size of the border setResizable( false ); //disables the maximize button add( canvas, BorderLayout.CENTER ); add( button, BorderLayout.SOUTH ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); // exits program } public static void main ( String args[] ) { ( new vacation() ).setVisible( true ); // if setVisible is false, there'll be no visible output } } interface Shape { public void draw(Graphics g); // calls draw(Graphics g) class public void move(); // calls move() class

} class ShapeCanvas extends Canvas { ArrayList<Shape> s; //declares the shape variables in their position int v = 0; // initializes v value to 0; v = no of clicks Image buffer = null; // scans class for images public ShapeCanvas() { setBackground(Color.BLACK); // positions the shapes s = new ArrayList<Shape>(); s.add(new Staff(-10000,20,100,30,0xffff00,100,0,50)); //1 s.add(new Note8(25,105,50,40,20,8,0x00ffff,0,25,22,"letz",0)); //2 s.add(new Note2(110,90,50,40,0x00ffff,25,22,"enjoy",0)); //3 s.add(new Note4(195,105,50,40,0x00ffff,25,21,"our",0)); //4 s.add(new Note8(280,90,50,40,20,8,0x00ffff,0,25,22,"vacation",0)); //5 s.add(new Note2(365,105,50,40,0x00ffff,25,20,"&",0)); //6 s.add(new Note4(450,90,50,40,0x00ffff,25,20,"4get",0)); //7 s.add(new Note8(535,105,50,40,20,8,0x00ffff,0,25,22,"diz",0)); //8 s.add(new Note2(620,90,50,40,0x00ffff,25,22,"hell",0)); //9 s.add(new Note4(705,105,50,40,0x00ffff,25,20,"sem" ,0)); //10 s.add(new Heart(250,225,300,20,0xff0000,0xff1493,0,0,0,true)); //11 s.add(new Guitar(25, 500, 0x800080)); //12 s.add(new Guitar(650, 500, 0x0000cd)); //13 } public void paint(Graphics g2) { if(buffer == null) { buffer = createImage(getWidth(), getHeight()); } Graphics g = buffer.getGraphics(); g.clearRect(0, 0, getWidth(), getHeight()); //clears screen to give way for the ff if(v>=0) s.get(0).draw(g); //condition used to display staff for(int i=1; i<7; i++) { if(v>=i+2) { s.get(i).draw(g); //condition used to display first note }

} if(v>=8) { s.get(11).draw(g); // gets guitar w/ heart s.get(12).draw(g); // gets guitar w/ heart } if(v==8) // 8th Click displays "4get" { Font music = new Font("Curlz MT", Font.BOLD, 150); g.setFont(music); g.setColor(new Color(0xff00ff)); g.drawString(" 4get", 218, 358); //Shadow colored pink (x,y) g.setColor(new Color(0xffffff)); g.drawString(" 4get",215, 355); } if(v==9) { Font music = new Font("Curlz MT", Font.BOLD, 150); g.setFont(music); g.setColor(new Color(0x8a2be2)); g.drawString(" 4get", 218, 358); g.setColor(new Color(0xffffff)); g.drawString(" 4get",215, 355); } if(v==10) { Font music = new Font("Curlz MT", Font.BOLD, 150); g.setFont(musicP); g.setColor(new Color(0xff0000)); g.drawString(" 4get", 218, 358); g.setColor(new Color(0xffffff)); g.drawString(" 4get",215, 355); } if(v>=11) { s.get(7).draw(g); } if(v>=12) { s.get(8).draw(g); } if(v>=13) { s.get(9).draw(g); s.get(10).draw(g); // gets heart }

if(v==13) { Font heart = new Font("Curlz MT", Font.BOLD, 90); g.setFont(heart); g.setColor(new Color(0xff0000)); g.drawString("HELL SEM", 218, 358); g.setColor(new Color(0xffffff)); g.drawString("HELL SEM",215, 355); } if(v>=14) { Font hvd = new Font("Papyrus", Font.BOLD, 40); g.setFont(hvd); g.setColor(new Color(0x000000)); g.drawString("Happy Happy Vacation!", 162, 342); g.setColor(new Color(0xffffff)); g.drawString("Happy Happy Vacation!", 165, 340); } g2.drawImage(buffer, 0, 0, null); } public void update(Graphics g) // initiates next button event { paint(g); } public void moveAll() // responsible for the movement of the notes { if(v>=0) s.get(0).move(); for(int i=1; i<s.size(); i++) { if(v>=i+2) { s.get(i).move(); } } v++; } } class Line implements Shape// responsible for all the lines { int x1, y1, x2, y2, color, moveY; boolean a, b;

public Line( int x1, int y1, int x2, int y2, int color, int moveY, boolean a, boolean b) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; this.color = color; this.moveY = moveY; this.a = a; this.b = b; } public void draw(Graphics g) { g.setColor(new Color(color)); g.drawLine(x1,y1,x2,y2); } public void move() { if(a) { if(b) { y1 -= moveY; y2 -= moveY; b = false; } else { y1 += moveY; y2 += moveY; b = true; } } } } class Circle implements Shape { int x, y, w, h, color, newC, moveY, check; boolean a = true; boolean b;

public Circle( int x, int y, int w, int h, int color, int newC, int moveY, int check, boolean b) { this.x = x; this.y = y; this.w = w; this.h = h; this.color = color; this.newC = newC; this.moveY = moveY; this.check = check; this.b = b; } public void draw(Graphics g) { if(a) g.setColor(new Color(color)); else g.setColor(new Color(newC)); g.fillOval(x,y,w,h); } public void move() // responsible for the movement of the circle { if(check == 0) { if(a) a = false; else a = true; } if(check == 1) { if(b) { y -= moveY; b = false; } else { y += moveY; b = true; } } }

} class Rectangle implements Shape { int x, y, w, h, color; public Rectangle( int x, int y, int w, int h, int color) { this.x = x; this.y = y; this.w = w; this.h = h; this.color = color; } public void draw(Graphics g) { g.setColor(new Color(color)); g.fillRect(x,y,w,h); } public void move() {} } class Diamond implements Shape { int[] x = new int[4]; int[] y = new int[4]; int color, newC; boolean a = true; public Diamond(int x1, int y1, int s, int color, int newC) { x[0] = x1; x[1] = x1 + (s/2); x[2] = x1 + s; x[3] = x1 + (s/2); y[0] = y1 + (s/2); y[1] = y1 + s; y[2] = y1 + (s/2); y[3] = y1; this.color = color; this.newC = newC; } public void draw(Graphics g) // responsible for the colors

{ if(a) g.setColor(new Color(color)); else g.setColor(new Color(newC)); g.fillPolygon(x,y,4); } public void move() { if(a) a = false; else a = true; } } class Heart implements Shape { Circle c1; Circle c2; Diamond d; public Heart(int x1, int y1, int s, int cx, int color, int newC, int moveX, int moveY, int check, boolean b) { c1 = new Circle( x1-(s/7)-1, y1-(s/7),(s*5/7), (s*5/7), color, newC, moveY, check, b); c2 = new Circle( x1+(s/2)-(s/7)+cx, y1-(s/7), (s*5/7), (s*5/7), color, newC, moveY, check, b); d = new Diamond(x1, y1, s, color, newC); } public void draw(Graphics g) // displays heart { c1.draw(g); c2.draw(g); d.draw(g); } public void move() // moves heart { c1.move(); c2.move(); d.move();

} } class Curve implements Shape //curves of the staff { int x, y, w, h, color, moveX, moveY, check; boolean b; public Curve(int x, int y, int w, int h, int color, int moveX, int moveY, int check, boolean b) { this.x = x; this.y = y; this.w = w; this.h = h; this.color = color; this.moveX = moveX; this.moveY = moveY; this.check = check; this.b = b; // boolean value to know when to move staff } public void draw(Graphics g) { g.setColor(new Color(color)); g.drawArc(x, y, w, h, 0, 180); g.drawArc(x+w, y, w, h, 0, -180); } public void move() { if(check == 0) { x += moveX; } else if(check == 1) { if(b) { y -= moveY; b = false; } else { y += moveY; b = true;

} } } } class Poly implements Shape // All shapes with corners are polygons except circle { int[] x = new int[5]; int[] y = new int[5]; int color; public Poly(int x1, int y1, int w, int h, int color) { x[0] = x1; x[1] = x1+(w/2); x[2] = x1+w; x[3] = x1+(w*2/3); x[4] = x1+(w/3); y[0] = y1; y[1] = y1-(h/3); y[2] = y1; y[3] = y1-h; y[4] = y1-h; this.color = color; } public void draw(Graphics g) { g.setColor(new Color(color)); g.fillPolygon(x,y,5); } public void move() {} } class Guitar implements Shape { Poly p; Rectangle a, b; Heart h; Line[] l = new Line[6]; public Guitar(int x, int y, int color) { p = new Poly(x,y,120, 150,color); a = new Rectangle(x+40,y-90,40,20,0x000000);

b = new Rectangle(x+40,y-250,40,120,0xd2691e); for(int i=0; i<6; i++)// to create two guitars l[i] = new Line( x+45+(i*6), y-250, x+45+(i*6), y-90, 0x000000, 0, false, false); h = new Heart(x+38,y-270,45,3,0xff0000,0xff0000,0,0,3,false); } public void draw(Graphics g) { p.draw(g); a.draw(g); b.draw(g); for(int i=0; i<6; i++) // to create two guitars l[i].draw(g); h.draw(g); } public void move() {} } class Words implements Shape { int size, x, y, color, moveY; boolean b; String word; public Words(int size, int x, int y, int moveY, String word, boolean b) { this.size = size; this.x = x; this.y = y; this.moveY = moveY; this.word = word; this.b = b; } public void draw(Graphics g) { Font f = new Font("Papyrus", Font.ITALIC | Font.BOLD, size); g.setFont(f); g.setColor(Color.RED); g.drawString(word,x,y); } public void move() { if(b)

{ y -= moveY; b = false; } else { y += moveY; b = true; } } } class Note4 implements Shape { Circle c; Line l; Words W; public Note4(int x, int y, int w, int h, int color, int moveY, int size, String word, int a) { c = new Circle(x, y, w, h, color, color, moveY, 1, true); l = new Line( x-(h/2), y+(h/2), x+w+(h/2), y+(h/2), color, moveY, true, true); W = new Words(size, x-a+7, y+27, moveY, word, true); } public void draw(Graphics g) { c.draw(g); l.draw(g); W.draw(g); } public void move() { c.move(); l.move(); W.move(); } } class Note2 implements Shape { Circle c; Line l; Words W;

public Note2(int x, int y, int w, int h, int color, int moveY, int size, String word, int a) { c = new Circle(x, y, w, h, color, color, moveY, 1, true); l = new Line( x+w-1, y+(h/2), x+w-1, y-w, color, moveY, true, true); W = new Words(size, x-a+7, y+27, moveY, word, true); } public void draw(Graphics g) { c.draw(g); l.draw(g); W.draw(g); } public void move() { c.move(); l.move(); W.move(); } } class Note8 implements Shape { Circle c; Line l; Curve C; Words W; public Note8(int x, int y, int w, int h, int wA, int hA, int color, int moveX, int moveY, int size, String word, int a) { c = new Circle(x, y, w, h, color, color, moveY, 1, true); l = new Line( x+w-1, y+(h/2), x+w-1, y-w, color, moveY, true, true); C = new Curve( x+w, y-w, wA, hA, color, moveX, moveY, 1, true); W = new Words(size, x-a+7, y+27, moveY, word, true); } public void draw(Graphics g) { c.draw(g); l.draw(g); C.draw(g); W.draw(g); }

public void move() { c.move(); l.move(); C.move(); W.move(); } } class StaffL implements Shape //displays the staff line as a whole // without this, the staff line will appear broken { Curve[] c; int n; public StaffL(int x, int y, int w, int h, int color, int moveX, int moveY, int n) { this.n = n; c = new Curve[n]; for(int i = 0; i<n; i++) { c[i] = new Curve( x+(i*w*2), y, w, h, color, moveX, moveY, 0, true); } } public void draw(Graphics g) { for(int i = 0; i<n; i++) { c[i].draw(g); } } public void move() { for(int i = 0; i<n; i++) { c[i].move(); } } } class Staff implements Shape //displays the staff as a whole // without this, the staff will appear broken {

StaffL[] s; public Staff(int x, int y, int w, int h, int color, int moveX, int moveY, int n) { s = new StaffL[5]; for(int i = 0; i<5; i++) // mirrors the staff line into five { s[i] = new StaffL( x, y+(h*i), w, h, color, moveX, moveY, n); } } public void draw(Graphics g) { for(int i = 0; i<5; i++) // mirrors the staff line into five { s[i].draw(g); } } public void move() { for(int i = 0; i<5; i++) // mirrors the staff line into five { s[i].move(); } } }

----------------------------(2) GAMES -----------------------------

import java.awt.*; import java.awt.event.*; import java.applet.*; import javax.swing.*; import javax.swing.event.*; /* <applet code="Dxball1.class" width=670 height=300> </applet> */

public class DXBall1 extends Applet implements Runnable,KeyListener,MouseListener { Thread th; static Rectangle ob[] = new Rectangle[30]; Ball ball; Bar bar; Message mes; int i,j; int x = 1; int y=1; int z = 0; int xx,yy1,zz; int b,b1; int flag; //static int yy=0; boolean runing=true; Image dbimage; Graphics dbg; int c1,c2,c3,c4; int flagg=1; //int ballCheck=0; String ss = ""; String ss1=""; String me = ""; static int score = 0; static Font ff; TextArea ta; public void start() { th = new Thread(this); runing = false; //th.start(); } public void stop() { runing = true; th = null; } public void run() { for(; ;)

{ if(ball.over()) { ss = "Game Over!!!!!"; ss1 = "You have loss the game"; repaint(); System.out.print("braek"); break; } try {

Thread.sleep(20); if(runing)break; int tempx=Ball.flagx; int tempy=Ball.flagy; if (tempx==1) ball.move(); else ball.move1(); if(tempy==1) ball.move2(); else ball.move3(); if(tempy==1) ball.move(); else ball.move3(); repaint();

} catch(InterruptedException ie) { ie.printStackTrace(); } } } public void init() { /*me =" THIS IS A DXBALL GAME. "+

" This Game is Devlopped by Md.Mujibur Rahman "+ " University of DIU BATCH 9th ROLL 9007 "+ " Created by Mujibur's Group "+ " HOW TO PLAY "+ " Level 1: First You press mouse "+ "when you press mouse the the ball is moved "+ "Then Score will be increase "+ " Control the bar for using left arrow and right arrow "+ "the Ball moved Randomly "+ "If the ball hits the Rectangle "+ "Then Score will Increase "+ "if the ball is passed the bar level "+ "Game will be over and Game is finished"; setLayout(null); ta = new TextArea(me); ta.setBounds(470,120,150,150); ta.setEditable(false); add(ta);*/ int xx=30,mm=30; for(int i =0 ;i<24;i=i+3) { ob[i] = new Rectangle(xx,mm); ob[i].display=true; mm=mm+20; ob[i+1] = new Rectangle(xx,mm);

ob[i+1].display=true; mm=mm+20; ob[i+2] = new Rectangle(xx,mm); ob[i+2].display=true; xx=xx+50; mm = 30; } mes =new Message(); ball = new Ball(90,250); bar = new Bar(70); ff = new Font("arial",Font.BOLD,20); this.addKeyListener(this); this.addMouseListener(this); } public void paint(Graphics g) { int count=0; for(int i=0;i<24;i++) { if(ob[i].display==false) count++; } if(count==24) { mes.mess(g); return; } g.setFont(new Font("arial",Font.PLAIN,15)); g.setColor(Color.gray); g.fillRect(470,30,150,70); g.setColor(Color.blue); g.drawString("Score: "+score,480,50); g.drawString("Status:"+Ball.over,480,70); g.drawString("Life: "+Ball.life,480,90); //g.drawString(""+Bar.yy,455,50); g.setColor(Color.black); g.fillRect(20,20,410,300); g.setColor(Color.red);

g.setFont(ff); g.drawString(ss,100,200); g.drawString(ss1,100,230); g.setColor(Color.red); for(int j = 0;j<24;j++) { if(ob[j].display==false) { continue; } System.out.print("check false : "+ob[j].display); if(ob[j].display==true) { breaking(j) ; } if(ob[j].display==true) ob[j].ppaint(g); } ball.bpaint(g); bar.barpaint(g); } public void keyTyped(KeyEvent k) { } public void keyReleased(KeyEvent k) { } public void keyPressed(KeyEvent k) { int R =k.getKeyCode(); if(R==k.VK_LEFT) { if(bar.yy > 25) bar.yy=bar.yy-10; System.out.println("Left"); repaint();

} if(R==k.VK_RIGHT) { if(bar.yy < 365 ) { bar.yy=bar.yy+10; } System.out.println("Right"); repaint();

} } public void mousePressed(MouseEvent me) { th.start(); } public void mouseReleased(MouseEvent me) { } public void mouseClicked(MouseEvent me) { } public void mouseExited(MouseEvent me) { } public void mouseEntered(MouseEvent me) { } public void update(Graphics g) //to remove flickering { if (dbimage==null) { dbimage=createImage(this.getSize().width,this.getSize().height); dbg=dbimage.getGraphics(); } dbg.setColor(getBackground()); dbg.fillRect(0,0,this.getSize().width,this.getSize().height); dbg.setColor(getForeground()); paint(dbg);

g.drawImage(dbimage,0,0,this); } public boolean breaking(int i) { if(check(i)) return true; else return false; } public boolean check(int i) { int am,ami; am = Math.abs(ball.x1-ob[i].x); ami = Math.abs(ball.y1-ob[i].y); if(am<20 && ami<20 ) { ob[i].display=false; score=score+10; Ball.flagy=1; return true; } else { return false; } } } //Class main is end

class Rectangle { int i; int x,y;

Graphics g; int ballCheck=0; boolean display; Rectangle(int m ,int n) { x = m; y =n; } public void ppaint(Graphics g) { g.fillRect(x,y,40,10); } } class Ball { static int flag=3; static int flagx=1; static int flagy=2; static int Point = 0; static String over=""; static int life=1; int x,y,m; int x1,y1; Graphics g; Ball(int a1,int a2) { x1 = a1; y1 = a2; } public void bpaint(Graphics g) { //g.drawString(" y : "+y1,455,250); if(20>=x1||x1>=410||y1<=20||y1>=260) //checking boundaries { getflag(); } g.setColor(Color.white); g.fillOval(x1,y1,15,15); } public boolean over()

{ //System.out.println(""+y1); if(y1>290) return true; else return false; } public void move() { x1++; } public void move1() { x1--; } public void move2() { y1=y1+2; } public void move3() { y1=y1-2; } public void move4() { x1++; y1--; } public void getflag() { if(x1<=20) // check boundaries and ball motion { x1=20; flagx=1; } if(x1>=410) { x1=410; flagx=2; }

if(y1<=20) { y1=20; Point = Point +10; flagy=1; } if(y1>=260) { if(Bar.yy>=x1||x1<=(Bar.yy+50)) { System.out.print("/n /n true Bar.yy :"+Bar.yy+" Y1:"+y1); System.out.print(" /n/n/n/ncheck ok"); y1=260; flagy=2; } else { System.out.print("/n /n falseBar.yy :"+Bar.yy+" Y1:"+y1); if(Bar.yy>260 && Bar.yy<200) { flag=2; System.out.print("/n game over"); } else { if(Bar.yy>290) { } else { life=0; System.out.print(Bar.yy); over="LOSS GAME"; } } } //else1 end } } }//end class

class Bar { int ss; static int yy=0; int q; static int pp; Bar(int a) { yy=a+yy; } public void barpaint(Graphics g) { g.setColor(Color.gray); g.fillRect(yy,270,60,10); } } class Message { public void mess(Graphics g) { g.setColor(Color.black); g.fillRect(0,0,400,300); g.setColor(Color.red); g.setFont(DXBall1.ff); g.drawString("YOU HAVE WON THE GAME",160,180); g.drawString("Your Score is:"+DXBall1.score,160,200); } }

-------------------------------------------------(3) CALENDAR & CLOCK -------------------------------------------------import java.applet.*; import java.awt.*; import java.text.SimpleDateFormat; import java.util.*; public class sample extends Applet implements Runnable{ Button m100; //year decrement buttons.

Button m10; Button m1; Button p1; Button p10; Button p100; Button fontColor; Button backColor; TextField yearbox;

//year increment buttons.

//box for year

int day[] = new int[12]; int year, dayofweek; int lineinc = 16; int lindex; int FontIndex, BackIndex; String line = ""; //clock int width, height; Thread t = null; boolean threadSuspended; int hours=0, minutes=0, seconds=0; String timeString = ""; ///// Read Date from the computer to setup initial display ///// Calendar ReadTime = Calendar.getInstance(); int CurrentYear = ReadTime.get(Calendar.YEAR); public void init() { backColor = new Button("BackColor"); m100 = new Button("-100"); m10 = new Button("-10"); m1 = new Button("-1"); yearbox = new TextField(4); //box to put year in. p1 = new Button("+1"); p10 = new Button("+10"); p100 = new Button("+100"); fontColor = new Button("FontColor"); FlowLayout Buttons = new FlowLayout(FlowLayout.LEFT, 10, 7 ); setLayout(Buttons);

add ( fontColor ); add ( m100 ); add ( m10 ); add ( m1 ); add ( yearbox ); add ( p1 ); add ( p10 ); add ( p100 ); add ( backColor );

//Year buttons.

//clock width = getSize().width; height = getSize().height; } //clock public void start() { if ( t == null ) { t = new Thread( this ); t.setPriority( Thread.MIN_PRIORITY ); threadSuspended = false; t.start(); } else { if ( threadSuspended ) { threadSuspended = false; synchronized( this ) { notify(); } } } } public void stop() { threadSuspended = true; } void drawHand( double angle, int radius, Graphics g ) { angle -= 0.5 * Math.PI; int x = (int)( radius*Math.cos(angle) ); int y = (int)( radius*Math.sin(angle) ); g.drawLine( width*3+185, height*2-20, width*3+185 + x, height*2-20 + y ); } void drawWedge( double angle, int radius, Graphics g ) {

angle -= 0.5 * Math.PI; int x = (int)( radius*Math.cos(angle) ); int y = (int)( radius*Math.sin(angle) ); angle += 2*Math.PI/3; int x2 = (int)( 5*Math.cos(angle) ); int y2 = (int)( 5*Math.sin(angle) ); angle += 2*Math.PI/3; int x3 = (int)( 5*Math.cos(angle) ); int y3 = (int)( 5*Math.sin(angle) ); g.drawLine( width*3+185+x2, height*2-20+y2, width*3+185 + x, height*220 + y ); g.drawLine( width*3+185+x3, height*2-20+y3, width*3+185 + x, height*220 + y ); g.drawLine( width*3+185+x2, height*2-20+y2, width*3+185 + x3, height*220 + y3 ); } public void paint( Graphics g ) { //CLOCK g.fillOval(1040,190, 380, 380); g.setColor( Color.gray ); drawWedge( 2*Math.PI * hours / 12, width/5, g ); drawWedge( 2*Math.PI * minutes / 60, width/3, g ); drawHand( 2*Math.PI * seconds / 60, width/2, g ); g.setColor( Color.white ); g.drawString( timeString, 1210, height+280 ); //calendar Font font1 = new Font( "Courier", Font.PLAIN, 16 ); //Fixed width font needed Font font2 = new Font( "Courier", Font.BOLD, 16 ); switch ( BackIndex ) //Background Color settings { case 0: setBackground( Color.black ); break; case 1: setBackground( Color.blue ); break; case 2: setBackground( Color.cyan ); break; case 3: setBackground( Color.darkGray ); break; case 4: setBackground( Color.gray ); break; case 5: setBackground( Color.lightGray ); break; case 6: setBackground( Color.green ); break; case 7: setBackground( Color.magenta ); break; case 8: setBackground( Color.orange ); break; case 9: setBackground( Color.pink ); break;

case 10: setBackground( Color.red ); break; case 11: setBackground( Color.white ); break; case 12: setBackground( Color.yellow ); break; } switch ( FontIndex ) //Font Color settings { case 0: g.setColor( Color.black ); break; case 1: g.setColor( Color.blue ); break; case 2: g.setColor( Color.cyan ); break; case 3: g.setColor( Color.darkGray ); break; case 4: g.setColor( Color.gray ); break; case 5: g.setColor( Color.lightGray ); break; case 6: g.setColor( Color.green ); break; case 7: g.setColor( Color.magenta ); break; case 8: g.setColor( Color.orange ); break; case 9: g.setColor( Color.pink ); break; case 10: g.setColor( Color.red ); break; case 11: g.setColor( Color.white ); break; case 12: g.setColor( Color.yellow ); break; } ////////// Draw Frame around Months ////////// g.drawRect( 0, 0, 779, 679 ); // main box g.drawLine( 260, 40, 260, 680 ); // Center verticle lines g.drawLine( 520, 40, 520, 680 ); g.drawLine( 0, 40, 780, 40 ); // Lines around buttons g.drawLine( 0, 72, 780, 72 ); g.drawLine( 0, 200, 780, 200 ); // Horizontal lines around Months g.drawLine( 0, 232, 780, 232 ); g.drawLine( 0, 360, 780, 360 ); g.drawLine( 0, 392, 780, 392 ); g.drawLine( 0, 520, 780, 520 ); g.drawLine( 0, 552, 780, 552 ); g.setFont( font2 ); String Year = yearbox.getText(); year = Integer.parseInt( Year ); if ( year < 1 ) { g.drawString( " return;

Please enter a year!!", 20, 200 );

} lindex = 60; // initialize writing area each repaint

for ( int i = 0; i <= 11; i++ ) day[i] = 1; //initialize day of each Month to 1 ////////////////// Main program flow //////////////////////////// for ( int row= 0 ; row <= 3 ; ++row ) // 4 rows of Months 0-1-2 3-4-5 6-7-8 9-10-11 { g.setFont( font2 ); if ( row != 0 ) lindex += lineinc; switch (row) // Draw Month names { case 0: g.drawString( " ***** JANUARY ****** ***** FEBRUARY ***** ******* MARCH ******", 10, lindex ); break; case 1: g.drawString( " ****** APRIL ******* ******* MAY ******** ******* JUNE *******", 10, lindex ); break; case 2: g.drawString( " ******* JULY ******* ****** AUGUST ****** ***** SEPTEMBER ****", 10, lindex ); break; case 3: g.drawString( " ***** OCTOBER ****** ***** NOVEMBER ***** ***** DECEMBER *****", 10, lindex ); } lindex += 2*lineinc; //increment line space by 2. One blank line. g.drawString( " Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa", 10, lindex ); lindex += lineinc; for ( int week = 0 ; week <= 5 ; ++week ) //week loops. one line includes one week for 3 Months. { g.setFont( font1 ); line = " "; for ( int col = 0 ; col <= 2 ; ++col ) //3 Months in a row { if (week == 0) //1st week needs to know what day to start. firstweek( row*3 + col, year ); else otherweek( row*3 + col );

/* Column end */ //done with line, print it out.

g.drawString(line, 10, lindex); lindex += lineinc; line = " "; } } } // Week end // Row end // Paint end

/////////////////// first week of the Month ///////////////////// public void firstweek( int Month, int year ) { int dayofweek = firstday ( Month, year ); for ( int i = 0 ; i < dayofweek ; i++ ) line = line.concat(" "); do { line = line.concat( " " + String.valueOf( day[Month] ) ); //print day of Month with leading blanks. ++day[Month]; ++dayofweek; } while (dayofweek <= 6 ); if ( ((Month + 1) % 3) != 0 ) //if last day of week, print spaces between Month. line = line.concat(" "); } /////////////////// weeks 2 - 6 ///////////////////// public void otherweek( int Month ) { dayofweek = 0; //initialize day of week to 0. Sunday int daysinMonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; if (((year % 4) == 0) && (((year % 100) != 0) || ((year % 400) == 0))) daysinMonth[1] = 29; do { if ( day[Month] <= daysinMonth[ Month ] ) //check to see if days still left. {

//get starting day of week. //print blanks until 1st.

if ( day[Month] < 10 ) //if 1-9, 2 leading spaces needed. line = line.concat( " " + String.valueOf( day[Month] ) ); else //if 10-31, 1 leading space needed. line = line.concat( " " + String.valueOf( day[Month] ) ); ++day[Month]; ++dayofweek; } else { line = line.concat(" "); //if after last day of Month, print blanks. ++dayofweek; } } while ( dayofweek <= 6 ); if ( ((Month + 1) % 3) != 0 ) //if last day of week, print spaces between Month. line = line.concat(" "); } //end of otherweek ///////////////// first day of Month //////////////// public int firstday( int Month, int year ) { int yeardiff, days_since, dayofyear[]={ 0,31,59,90,120,151,181,212,243,273,304,334 }; yeardiff = year - 1; days_since = yeardiff * 365; days_since += ( ( yeardiff/4 ) - ( yeardiff/100 ) + ((yeardiff)/400) ) + dayofyear[ Month ]; if (((((year % 4) == 0) && (((year % 100) != 0) || ((year % 400) == 0)))) && ( Month > 1 )) days_since++; return ( ( days_since + 1 ) % 7 ); } ////////// Button and Mouse Activity /////////////// public boolean action(Event event, Object arg ) { if (event.target instanceof Button ) HandleButtons(arg); repaint(); return true; }

/////////////////// Button Handler ////////////////// protected void HandleButtons(Object label) { String NewYear; if ( label == "-100" ) year -= 100; else if ( label == "-10" ) year -= 10; else if ( label == "-1" ) year -= 1; else if ( label == "+1" ) year += 1; else if ( label == "+10" ) year += 10; else if ( label == "+100" ) year += 100; else if ( label == "Now" ) year = CurrentYear; NewYear = String.valueOf( year ); yearbox.setText( NewYear ); ////////////// Font and Background Color //////////// if ( label == "FontColor" ) { FontIndex++; if ( FontIndex == 13 ) FontIndex = 0; } if ( label == "BackColor" ) { BackIndex++; if ( BackIndex == 13 ) BackIndex = 0; } } //handle buttons public void run() { try { while (true) { // Here's where the thread does some work

Calendar cal = Calendar.getInstance(); hours = cal.get( Calendar.HOUR_OF_DAY ); if ( hours > 12 ) hours -= 12; minutes = cal.get( Calendar.MINUTE ); seconds = cal.get( Calendar.SECOND ); SimpleDateFormat formatter = new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() ); Date date = cal.getTime(); timeString = formatter.format( date ); // Now the thread checks to see if it should suspend itself if ( threadSuspended ) { synchronized( this ) { while ( threadSuspended ) { wait(); } } } repaint(); t.sleep( 1000 ); // interval given in milliseconds } } catch (InterruptedException e) { } } } // calendar class end

------------------------------------------(4) PAYSLIP SYSTEM ------------------------------------------import java.applet.*; import java.awt.*; import java.awt.event.*; public class Project extends Applet implements ActionListener,ItemListener{ Label CA = new Label ("COMIC ALLEY INCORPORATED"); Label pay = new Label ("PAYSLIP"); Label Name = new Label ("Name: "); TextArea t=new TextArea(30,45); Label Pos = new Label ("Position: "); Choice CPos= new Choice ();

Label CBran = new Label ("Company-Branch: "); CheckboxGroup CBra = new CheckboxGroup(); Checkbox MOA = new Checkbox(); Checkbox Mega = new Checkbox(); Checkbox Ortigas = new Checkbox(); Checkbox Rob = new Checkbox(); Checkbox Gway = new Checkbox(); Checkbox SM = new Checkbox(); Label HW= new Label ("Hours Work: "); Label Rate = new Label ("Rate: "); Label Bonus = new Label ("Bonus: "); Label Gross = new Label ("Gross: "); Label Deduction = new Label ("Deduction: "); Label Net = new Label ("Net Income: "); TextField txtName = new TextField ("Type your Name Here...", 50); TextField txtHW = new TextField ("Type Here...", 12); TextField txtRate = new TextField ("", 12); TextField txtBonus = new TextField ("", 12); TextField txtGross = new TextField ("", 12); TextField txtDedct = new TextField ("", 12); TextField txtNet = new TextField ("", 12); Button Sub = new Button ("SUBMIT"); Button Can = new Button ("CANCEL"); Font font = new Font ("Courier new", Font.BOLD , 12); Font Ffont = new Font ("Comic Sans", Font.BOLD , 30); Font Ffnt = new Font ( "",Font.BOLD , 20); int Medical,SSS,Tax; int G, T, N; public void init(){ setBackground (Color.PINK); setFont (font); setForeground (Color.black); add (CA); add (pay); add (Name); add (txtName); add (Pos); CPos= new Choice(); CPos.add("Store Manager"); CPos.add("Shift Manager"); CPos.add("Employee"); add (CPos);

add (CBran); CBra= new CheckboxGroup(); MOA=new Checkbox("Comic Alley-MOA",CBra,false); Mega=new Checkbox("Comic Alley-Megamall",CBra,false); Ortigas=new Checkbox("Comic Alley-Ortigas",CBra,false); Rob=new Checkbox("Comic Alley-Robinson",CBra,false); Gway=new Checkbox("Comic Alley-Gateway",CBra,false); SM=new Checkbox("Comic Alley-SM TAYTAY",CBra,false); add (MOA); add (Mega); add (Ortigas); add (Rob); add (Gway); add (SM); add (HW); add (txtHW); add (Rate); add (txtRate); add (Bonus); add (txtBonus); add (Gross); add (txtGross); add (Deduction); add (txtDedct); add (Net); add (txtNet); add(t); add(Sub); Sub.addActionListener(this); add(Can); Can.addActionListener(this); CPos.addItemListener(this); MOA.addItemListener(this); Mega.addItemListener(this); Ortigas.addItemListener(this); Rob.addItemListener(this); Gway.addItemListener(this); SM.addItemListener(this); }//END of INIT() public void paint (Graphics gr){

gr.setColor(Color.BLUE); gr.fillRect(450, 20, 750, 10); gr.setColor(Color.CYAN); gr.fillRect(450, 28, 650, 10); gr.setColor(Color.BLUE); gr.fillRect(20, 50, 10, 550); gr.setColor(Color.cyan); gr.fillRect(28, 50, 10, 450); gr.setColor(Color.GRAY); gr.fillRoundRect(75, 75, 802, 505, 80, 80); gr.setColor(Color.LIGHT_GRAY); gr.fillRoundRect(78, 79, 798, 499, 500, 500); gr.setColor( Color.PINK ); gr.fillRoundRect( 88, 89, 778, 479, 500, 500); CA.setFont(Ffont); CA.setForeground(Color.red); CA.setLocation(20, 20); pay.setFont(Ffnt); pay.setForeground(Color.WHITE); pay.setBackground(Color.gray); pay.setLocation(85,100); Name.setLocation(200, 130); txtName.setLocation(290, 130); Pos.setLocation(200, 160); CPos.setLocation(290, 160); CBran.setLocation(200, 190); MOA.setLocation(320,190); Mega.setLocation(320, 220); Ortigas.setLocation(320, 250); Rob.setLocation(500,190); Gway.setLocation(500, 220); SM.setLocation(500, 250); HW.setLocation(200, 290); txtHW.setLocation(290, 290); Rate.setLocation(200, 320); txtRate.setLocation(290, 320); Gross.setLocation(200, 350); txtGross.setLocation(290, 350); Bonus.setLocation(200, 380);

txtBonus.setLocation(290, 380); Deduction.setLocation(200, 410); txtDedct.setLocation(290, 410); Net.setLocation(200, 440); txtNet.setLocation(290, 440); Sub.setLocation(300, 470); Can.setLocation(410, 470); t.setLocation(900, 100); t.setBackground(Color.LIGHT_GRAY); }//END OF PAINT public void actionPerformed(ActionEvent e) { if(Sub.getActionCommand().equals("SUBMIT")) {//Start of (Sub.getActionCommand().equals("SUBMIT")) if(CPos.getSelectedItem().equals("Store Manager")) { txtRate.setText("500"); txtBonus.setText("1000"); } else if(CPos.getSelectedItem().equals("Shift Manager")) { txtRate.setText("350"); txtBonus.setText("700"); } else { txtRate.setText("150"); txtBonus.setText("400"); } if (e.getSource().equals(Sub)){ //Start of Computation of GROSS G=(Integer.parseInt(txtRate.getText()))*(Integer.parseInt(txtHW.getText())); txtGross.setText(String.valueOf(G)); }//End of Computation of GROSS //Deduction if(CPos.getSelectedItem().equals("Store Manager")) {//SM SSS=500; Medical=100; if(txtGross.equals(7000)) { Tax=1000; }

else if(txtGross.equals(6999)&&(txtGross.equals(4000))) { Tax=700; } else { Tax=500; } }//End-SM else if(CPos.getSelectedItem().equals("Shift Manager")) {//ShM SSS=300; Medical=100; if(txtGross.equals(7000)) { Tax=1000; } else if(txtGross.equals(6999)&&(txtGross.equals(4000))) { Tax=700; } else { Tax=500; } }//End-ShM else {//Emp SSS=125; Medical=100; if(txtGross.equals(7000)) { Tax=1000; } else if(txtGross.equals(6999)&&(txtGross.equals(4000))) { Tax=700; } else { Tax=500; } }//End-Emp }//END(Sub.getActionCommand().equals("SUBMIT"))

if (e.getSource().equals(Sub)){//Start of Computation of DEDUCTION T=SSS+Medical+Tax; txtDedct.setText(String.valueOf(T)); }//End of Computation of Deduction if (e.getSource().equals(Sub)){//Start of Computation of Net N=((Integer.parseInt(txtGross.getText()))+ (Integer.parseInt(txtBonus.getText())))-(Integer.parseInt(txtDedct.getText())); txtNet.setText(String.valueOf(N)); }//End of Computation of Net if (e.getSource().equals(Sub)){ //Start-TextAREA t.setText("Name: "+txtName.getText()+ "\nPosition: "+CPos.getSelectedItem()+ "\nCompany-Branch: "+CBra.getSelectedCheckbox().getLabel()+ "\nNumber of Hours Work: "+txtHW.getText()+ " hrs."+ "\n"+ "\nComputation of GROSS"+ "\nRate * Hours Work = Gross"+ "\n"+txtRate.getText()+" * "+txtHW.getText()+ "\nGROSS = "+txtGross.getText()+ "\nBonus = "+txtBonus.getText()+ "\n"+ "\nComputation of DEDUCTIONS"+ "\nSSS + Medical + Tax = Total Deductions"+ "\nSSS = "+SSS+ "\nMedical = "+Medical+ "\nTax = "+Tax+ "\nTOTAL DEDUCTIONS = "+txtDedct.getText()+ "\n"+ "\nComputation of NET INCOME"+ "\n( Gross + Bonus ) - Deduction = NET INCOME"+ "\nNET INCOME = "+txtNet.getText()); }//End-TextAREA if(Can.getActionCommand().equals("CANCEL")) {//Start-Cancel repaint(); }//End-Cancel }//End of Applet Event

public void itemStateChanged(ItemEvent e) {//Start-ItemChanged throw new UnsupportedOperationException("Not supported yet."); }//End-ItemChanged }//Class Name

-----------------------------------------------(5) CALCULATOR -----------------------------------------------import java.applet.*; import java.awt.*; import java.util.*; import java.text.*; public class Project extends Applet implements Runnable { int width, height; Thread t = null; boolean threadSuspended; int hours=0, minutes=0, seconds=0; String timeString = ""; public void init() { width = getSize().width; height = getSize ().height; setBackground( Color.blue ); //represents the background of the applet as a whole } public void start() { if ( t == null ) { t = new Thread( this

); t.setPriority( Thread.MIN_PRIORITY ); threadSuspended = false; t.start(); } else { if ( threadSuspended ){ threadSuspended = false; synchronized( this ){ notify(); } } } } public void stop() { threadSuspended = true; } public void run() { try { while (true) { Calendar cal = Calendar.getInstance(); //Here's where the thread does some work hours = cal.get( Calendar.HOUR_OF_DAY ); if ( hours > 12 )

hours -= 12; minutes = cal.get( Calendar.MINUTE ); seconds = cal.get( Calendar.SECOND ); //this declaration links itself to the info such as date and time displayed on the PC SimpleDateFormat formatter = new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() ); Date date = cal.getTime(); timeString = formatter.format( date ); if ( threadSuspended ) { // Now the thread checks to see if it should suspend itself synchronized( this ) { while ( threadSuspended ) { wait();

} } } repaint(); t.sleep( 1000 ); //this represents that interval should be given in milliseconds } } catch (InterruptedException e) { } } void drawHand( double angle, int radius, Graphics g ){ angle -= 0.5 * Math.PI; int x = (int)( radius*Math.cos(angle) ); int y = (int)( radius*Math.sin(angle) ); g.drawLine( width/2, height/2, width/2 + x, height/2 + y ); } void drawWedge( double angle, int radius, Graphics g ){ angle -= 0.5 * Math.PI; int x = (int)( radius*Math.cos(angle) );

int y = (int)( radius*Math.sin(angle) ); angle += 2*Math.PI/3; int x2 = (int)( 5*Math.cos(angle) ); int y2 = (int)( 5*Math.sin(angle) ); angle += 2*Math.PI/3; int x3 = (int)( 5*Math.cos(angle) ); int y3 = (int)( 5*Math.sin(angle) ); //represents the degree of turn for the line of hands g.drawLine( width/2+x2, height/2+y2, width/2 + x, height/2 + y ); //represents the first layer line of hands of the minute and hour g.drawLine( width/2+x3, height/2+y3, width/2 + x, height/2 + y ); //represents the second layer line of hands of the minute and hour g.drawLine( width/2+x2, height/2+y2, width/2 + x3, height/2 + y3 ); //represents the small lines connecting the

minute and hour hands } public void paint( Graphics g){ g.setColor( Color.black ); //represents the color of the hand lines drawWedge( 2*Math.PI * hours / 12, width/5, g ); //represents the 2 hour lines length drawWedge( 2*Math.PI * minutes / 60, width/3, g ); //represents the 2 minute lines length drawHand( 2*Math.PI * seconds / 60, width/5, g ); //represents the line for the second hand //changed the width of drawHand for second to /4 as it is too long if /2 g.setColor( Color.white ); //represents the color of numeric time g.drawString( timeString, 5, height-5 );

//this tells where the numeric time would be positioned } }

-----------------------------------------(6) TIC TAC TOE -----------------------------------------import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.lang.reflect.Method; import javax.swing.JButton; public class TicTacToe implements ActionListener { //actionlistener usually used in buttons; event like hyperlink String CPU, CPU1; final String VERSION = "3.0"; //declaring of variable that when version appears on code, it would display "3.0" //Setting up ALL the variables JFrame window = new JFrame("Tic-Tac-Toe " + VERSION); //title bar of window frame JMenuBar maMain = new JMenuBar(); //this is the Menu Bar Button that we seen above the applet JMenuItem maNewGame = new JMenuItem("New Game"), //'New Game' option on Menu bar maInstruction = new JMenuItem("Instructions"), //'Instructions' option on Menu bar maExit = new JMenuItem("Exit"), //'Exit' option on Menu bar maAbout = new JMenuItem("About"); //'About' option on Menu bar //this contain the name of the buttons in menu bar JButton ca = new JButton("Player vs Player"), //declaring of buttons on application caSetName = new JButton("Set Player Names"), //these are the options that will appear as buttons caQuit = new JButton("Quit"), //these are the options that will appear as buttons caCPU = new JButton("Player vs Computer"), //these are the options that will appear as buttons caContinue = new JButton("Continue..."), caTryAgain = new JButton("Try Again?"); JButton caEmpty[] = new JButton[10]; JPanel mbNewGame = new JPanel(), //declaring of all the panels that will be used in applet mbMenu = new JPanel(), mbMain = new JPanel(), mbTop = new JPanel(), mbBottom = new JPanel(), mbQuitNTryAgain = new JPanel(), mbPlayingField = new JPanel(); JLabel lblTitle = new JLabel("Tic-Tac-Toe"), //title of the game at the beginning page lblTurn = new JLabel(), //label for the turn of players lblStatus = new JLabel("", JLabel.CENTER), //label for status of scores lblMode = new JLabel("", JLabel.LEFT); JTextArea txtMessage = new JTextArea(); final int winCombo[][] = new int[][] { {1, 2, 3}, {1, 4, 7}, {1, 5, 9}, //winning positions for scoring {4, 5, 6}, {2, 5, 8}, {3, 5, 7}, {7, 8, 9}, {3, 6, 9}

/*Horizontal Wins*/ /*Vertical Wins*/ /*Diagonal Wins*/ }; final int X = 535, Y = 342, mainColorR = 190, mainColorG = 50, mainColorB = 50, //mainColorR - displays the color value of red //mainColorG - displays the color value of green //mainColorB - displays the color value of blue btnColorR = 70, btnColorG = 70, btnColorB = 70; //btnColorR - displays the color value of red for button, //btnColorG - displays the color value of green for button, //btnColorB - displays the color value of blue for button Color clrBtnWonColor = new Color(190, 190, 190); int turn = 1, //declaring of how many turns per player player1Won = 0, player2Won = 0, wonNumber1 = 1, wonNumber2 = 1, wonNumber3 = 1, option; boolean inGame = false, CPUGame = false, win = false; String message, Player1 = "Player 1", Player2 = "Player 2", //showing of text on which player's turn to move and the words Player 1 and 2 to appear on game tempPlayer2 = "Player 2"; public TicTacToe() { //Setting game properties and layout and sytle... //Setting window properties: window.setSize(X, Y); //size of window or button window.setLocation(350, 260); //window.setResizable(false); window.setLayout(new BorderLayout()); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //declaring of action for exit button //Setting Menu, Main, Top, Bottom Panel Layout/Backgrounds mbMenu.setLayout(new FlowLayout(FlowLayout.CENTER)); //position of Menu bar (if left, right or center) mbTop.setLayout(new FlowLayout(FlowLayout.CENTER)); //position of panel bar (continue, player vs player & etc) mbBottom.setLayout(new FlowLayout(FlowLayout.CENTER)); //position of lower panel mbNewGame.setBackground(new Color(mainColorB)); //represents the color of the space between continue, PVsP, PVsCPU & Set Player names mbMenu.setBackground(new Color(mainColorB)); //represents the color of the space on Menu bar mbMain.setBackground(new Color(mainColorR)); //declaration of bg color of main space of title page mbTop.setBackground(new Color(mainColorR)); //declaration of bg color for the part of continue, PVsP, PVsCPU & Set Player names mbBottom.setBackground(new Color(mainColorB)); //declaration of bg color for the part of Turn, Player 1 & Player 2 (3rd slide of game) //Setting up Panel QuitNTryAgain mbQuitNTryAgain.setLayout(new GridLayout(1, 2, 2, 2)); mbQuitNTryAgain.add(caTryAgain); //declaring of adding button for try again mbQuitNTryAgain.add(caQuit); //declaring of adding button for quit lblTitle.setForeground(Color.white); //Adding menu items to menu bar maMain.add(maNewGame); maMain.add(maInstruction); //instruction option maMain.add(maAbout); //about option maMain.add(maExit); // Menu Bar is Complete. this are the following button you can see in Menu Bar

//Adding buttons to NewGame panel mbNewGame.setLayout(new GridLayout(4, 1, 2, 10)); mbNewGame.add(caContinue); //button for continue mbNewGame.add(ca); //button for player vs player mbNewGame.add(caCPU); //button for player vs cpu mbNewGame.add(caSetName); //button to set name of players //Setting Button propertied caTryAgain.setEnabled(true); //declaring function of button 'try again' caContinue.setEnabled(true); //declaring function of button 'continue' //Setting txtMessage Properties txtMessage.setBackground(new Color(mainColorR)); txtMessage.setForeground(Color.white); txtMessage.setEditable(false); //Adding Action Listener to all the Buttons and Menu Items maNewGame.addActionListener(this); //declaring of the functions for each button; putting animation/events on buttons maExit.addActionListener(this); //this option is to call method maInstruction.addActionListener(this); //to put action for instruction button maAbout.addActionListener(this); //to put action for about button ca.addActionListener(this); //to put action for pvp button caCPU.addActionListener(this); //to put action for pvcpu button caQuit.addActionListener(this); //to put action for quit button caSetName.addActionListener(this); //to put action for set name button caContinue.addActionListener(this); //to put action for continue button caTryAgain.addActionListener(this); //to put action for try again button //Setting up the playing field mbPlayingField.setLayout(new GridLayout(3, 3, 2, 2)); mbPlayingField.setBackground(Color.black); //bg color of the playing field for(int i=1; i<=9; i++) { caEmpty[i] = new JButton(); caEmpty[i].setBackground(new Color(btnColorR, btnColorG, btnColorB)); //color of playing field buttons caEmpty[i].addActionListener(this); //declaring of event on buttons mbPlayingField.add(caEmpty[i]);//Playing Field is complete } //Adding everything needed to pnlMenu and pnlMain lblMode.setForeground(Color.white); //font color of label mbMenu.add(lblMode); //label on menu tab (1v1) mbMenu.add(maMain); mbMain.add(lblTitle); //label title Tik-Tac-Toe //Adding to window and Showing window window.add(mbMenu, BorderLayout.NORTH); window.add(mbMain, BorderLayout.CENTER); window.setVisible(true); } public static void main(String[] args) { new TicTacToe();// Calling the class construtor. // PROGRAM STARTS HERE! } //start of all method public void showGame() { // Shows the Playing Field // *IMPORTANT*- Does not start out brand new (meaning just shows what it had before) clearPanelSouth(); mbMain.setLayout(new BorderLayout()); //creating of layout for main mbTop.setLayout(new BorderLayout()); //creating of layout for top

mbBottom.setLayout(new BorderLayout()); //creating of layout for bottom mbTop.add(mbPlayingField); //linking playing field on the top panel mbBottom.add(lblTurn, BorderLayout.WEST); //this is the position of the information in the playing field mbBottom.add(lblStatus, BorderLayout.CENTER); //same as above mbBottom.add(mbQuitNTryAgain, BorderLayout.EAST); mbMain.add(mbTop, BorderLayout.CENTER); mbMain.add(mbBottom, BorderLayout.SOUTH); mbPlayingField.requestFocus(); inGame = true; checkTurn(); checkWinStatus(); } public void newGame() { // Sets all the game required variables to default // and then shows the playing field. // (Basically: Starts a new 1v1 Game) caEmpty[wonNumber1].setBackground(new Color(btnColorR, btnColorG, btnColorB)); caEmpty[wonNumber2].setBackground(new Color(btnColorR, btnColorG, btnColorB)); caEmpty[wonNumber3].setBackground(new Color(btnColorR, btnColorG, btnColorB)); for(int i=1; i<10; i++) { {//this represent the row and column of the playing field caEmpty[i].setText(""); caEmpty[i].setEnabled(true); } turn = 1; win = false; showGame(); }} public void quit() { //method to quit inGame = false; lblMode.setText(""); caContinue.setEnabled(false); clearPanelSouth(); setDefaultLayout(); mbTop.add(mbNewGame); mbMain.add(mbTop); } public void checkWin() { // checks if there are 3 symbols in a row vertically, diagonally, or horizontally. // then shows a message and disables buttons. If the game is over then it asks // if you want to play again. for(int i=0; i<8; i++) { if( !caEmpty[winCombo[i][0]].getText().equals("") && caEmpty[winCombo[i][0]].getText().equals(caEmpty[winCombo[i][1]].getText()) && // if {1 == 2 && 2 == 3} caEmpty[winCombo[i][1]].getText().equals(caEmpty[winCombo[i][2]].getText())) { /* The way this checks the if someone won is: First: it checks if the btnEmpty[x] is not equal to an empty string- x being the array number inside the multi-dementional array winCombo[checks inside each of the 7 sets][the first number] Secong: it checks if btnEmpty[x] is equal to btnEmpty[y]- x being winCombo[each set][the first number] y being winCombo[each set the same as x][the second number] (So basically checks if the first and second number in each set is equal to each other) Third: it checks if btnEmtpy[y] is eual to btnEmpty[z]- y being the same y as last time and z being winCombo[each set as y][the third number] Conclusion: So basically it checks if it is equal to the btnEmpty is equal to each set of numbers

*/ win = true; wonNumber1 = winCombo[i][0]; wonNumber2 = winCombo[i][1]; wonNumber3 = winCombo[i][2]; caEmpty[wonNumber1].setBackground(clrBtnWonColor); caEmpty[wonNumber2].setBackground(clrBtnWonColor); caEmpty[wonNumber3].setBackground(clrBtnWonColor); break; } } if(win || (!win && turn>9)) { //using if else if statement to determine pop up for winner if(win) { if(caEmpty[wonNumber1].getText().equals("X")) { //message pop-up: this tells or gives pop up if player 1 won message = Player1 + " has won"; player1Won++; //lets scoring update } else { message = Player2 + " has won"; //message pop-up: this tells if player 2 won player2Won++; //lets scoring update } } else if(!win && turn>9) message = "Both players have tied!\nBetter luck next time."; //message pop-up: this tells if both players are tied showMessage(message); for(int i=1; i<=9; i++) { caEmpty[i].setEnabled(false); } caTryAgain.setEnabled(true); //try again button will enable or show up once game is finished checkWinStatus(); //this command will link with the scoring to update the score of given winner once game ends } else checkTurn(); //if game is not finish, it will continue by checking which player's turn it is to make a move } public void AI() { //this is a method for player vs computer option Method doMove; int computerButton; if(turn <= 9) { turn++; computerButton = CPU.doMove( //option of the buttons being empty since start of the game caEmpty[1], caEmpty[2], caEmpty[3], caEmpty[4], caEmpty[5], caEmpty[6], caEmpty[7], caEmpty[8], caEmpty[9]); if(computerButton == 0) Random(); else { caEmpty[computerButton].setText("O"); //setting the character 'o' as the player mark of computer caEmpty[computerButton].setEnabled(false); } checkWin(); //will check winnings of computer 'if won the game' and link with the scoring to update the score of given winner once game ends } }

public void Random() { //command moves of the computer int random; if(turn <= 9) { random = 0; while(random == 0) { random = (int)(Math.random() * 10); } if(CPU.doRandomMove(caEmpty[random])) { caEmpty[random].setText("O"); caEmpty[random].setEnabled(false); } else { Random(); } } } public void checkTurn() { //method for turns of player that will play String whoTurn; if(!(turn % 2 == 0)) { whoTurn = Player1 + " [X]"; //setting of x being player1 character } else { whoTurn = Player2 + " [O]"; //setting of o being player2 character } lblTurn.setText("Turn: " + whoTurn); //on the bottom panel, this will display which player's turn to make a move lblTurn.setForeground(Color.white); } public void askUserForPlayerNames() { //this is the command that will allow you to set player's name String temp; boolean tempIsValid = false; temp = getInput("Enter player 1 name:", Player1); //this will link the name you entered to player1 so that it will show for the rest of the game if(temp == null) {/*Do Nothing*/} else if(temp.equals("")) showMessage("Invalid Name!"); //this shows up if the name entered is not valid or is the same as name for Player2 else if(temp.equals(Player2)) { option = askMessage("Player 1 name matches Player 2's\nDo you want to continue?", "Name Match", JOptionPane.YES_NO_OPTION); //message pop-up fo the error and if to continue game if(option == JOptionPane.YES_OPTION) //declaring of action for the yes or no option tempIsValid = true; } else if(temp != null) { tempIsValid = true; } if(tempIsValid) { //this will command if player1 name is valid then will continue to player2 name Player1 = temp; tempIsValid = false; } temp = getInput("Enter player 2 name:", Player2); if(temp == null) {/*Do Nothing*/} else if(temp.equals("")) showMessage("Invalid Name!"); //same as well; if name for player2 is not valid or same as player1 name then this will appear else if(temp.equals(Player1)) { option = askMessage("Player 2 name matches Player 1's\nDo you want to continue?", "Name Match", JOptionPane.YES_NO_OPTION);

//message pop-up if name for player 2 matches with player1 and will be given option to change if(option == JOptionPane.YES_OPTION) tempIsValid = true; } else if(temp != null) { tempIsValid = true; } if(tempIsValid) { //if name is valid and will continue Player2 = temp; tempPlayer2 = temp; tempIsValid = false; } } public void setDefaultLayout() { mbMain.setLayout(new GridLayout(2, 1, 2, 5)); mbTop.setLayout(new FlowLayout(FlowLayout.CENTER)); mbBottom.setLayout(new FlowLayout(FlowLayout.CENTER)); } public void checkWinStatus() { lblStatus.setText(Player1 + ": " + player1Won + " | " + Player2 + ": " + player2Won); //how scoring will apear on bottom panel lblStatus.setForeground(Color.white); } public int askMessage(String msg, String tle, int op) { return JOptionPane.showConfirmDialog(null, msg, tle, op); //joptionpane function for confirming message pop-up } public String getInput(String msg, String setText) { return JOptionPane.showInputDialog(null, msg, setText); //joptionpane function for input message pop-up } public void showMessage(String msg) { JOptionPane.showMessageDialog(null, msg); //joptionpane function for message pop-up to show } public void clearPanelSouth() { //Removes all the possible panels //that pnlMain, pnlTop, pnlBottom //could have. mbMain.remove(lblTitle); mbMain.remove(mbTop); mbMain.remove(mbBottom); mbTop.remove(mbNewGame); mbTop.remove(txtMessage); mbTop.remove(mbPlayingField); mbBottom.remove(lblTurn); mbBottom.remove(mbQuitNTryAgain); } public void actionPerformed(ActionEvent click) { //declares action that will appear once click button or panel for the playing field Object source = click.getSource(); for(int i=1; i<=9; i++) { if(source == caEmpty[i] && turn < 10) { if(!(turn % 2 == 0)) caEmpty[i].setText("X"); //if player1 turn then this is the command for the 'x' character to show as pressed else caEmpty[i].setText("O"); //if player2 turn then this is the command for the 'o' character to show as pressed caEmpty[i].setEnabled(false);

mbPlayingField.requestFocus(); turn++; checkWin(); if(CPUGame && win == true) AI(); } } if(source == maNewGame || source == maInstruction || source == maAbout) { //declaring of action for the menu tab clearPanelSouth(); setDefaultLayout(); if(source == maNewGame) {//NewGame mbTop.add(mbNewGame); } else if(source == maInstruction || source == maAbout) { if(source == maInstruction) {// Instructions that would appear message = "Instructions:\n\n" + "Your goal is to be the first player to get 3 X's or O's in a\n" + "row. (horizontally, diagonally, or vertically)\n" + Player1 + ": X\n" + Player2 + ": O\n"; } else {//About message = "About:\n\n" + "Title: Tic-Tac-Toe\n" + "Creator: Blmaster\n" + "Version: " + VERSION + "\n"; message = "About:\n\n" + "Title: Tic-Tac-Toe\n" + "Creator: GROUP 2\n" + "Version: Tic-Tac-toe 3.0 \n"; } txtMessage.setText(message); mbTop.add(txtMessage); } mbMain.add(mbTop); } else if(source == ca || source == caCPU) { if(inGame) { option = askMessage("If you start a new game," + //this option will appear when you will start a new game and not continue your old game "your current game will be lost..." + "\n" + "Are you sure you want to continue?", "Quit Game?" ,JOptionPane.YES_NO_OPTION //option of yes or no will appear on message pop-up ); if(option == JOptionPane.YES_OPTION) inGame = false; } if(!inGame) { caContinue.setEnabled(true); if(source == ca) {// 1 v 1 Game Player2 = tempPlayer2; player1Won = 0; player2Won = 0; lblMode.setText("1 v 1"); //text that would appear on the menu tab CPUGame = false; newGame(); } else {// 1 v CPU Game Player2 = "Computer"; player1Won = 0; player2Won = 0; lblMode.setText("1 v CPU");

CPUGame = true; newGame(); } } } else if(source == caContinue) { checkTurn(); showGame(); } else if(source == caSetName) { askUserForPlayerNames(); } else if(source == maExit) { option = askMessage("Are you sure you want to exit?", "Exit Game", JOptionPane.YES_NO_OPTION); //message pop-up if will be exiting game if(option == JOptionPane.YES_OPTION) System.exit(0); } else if(source == caTryAgain) { newGame(); caTryAgain.setEnabled(false); } else if(source == caQuit) { quit(); } mbMain.setVisible(false); mbMain.setVisible(true); } //-------------------END OF ACTION PERFORMED METHOD-------------------------// } /* LAYOUT OF THE GAME: THE WINDOW: (mbMenu/mbMain) mbMenu: (THE MENU) mbMain: (mbTop/mbBottom) mbTop: (mbPlayingField/INSTRUCTIONS/ABOUT/NEW GAME) mbBottom:(STATUS BAR/BACK BUTTON) */

------------------------------------------(7) POCKETCALCU ------------------------------------------package javaapplication2; import java.awt.*; import java.applet.Applet; public class PocketCalc extends Applet { TextField txtDisp; public final int OP_NONE = 0; public final int OP_ADD = 1; public final int OP_SUB = 2; public final int OP_MUL = 3;

public final int OP_DIV = 4; public final int OP_NEG = 5; public final int OP_SQRT = 6; public final int OP_EQ = 7; public final int OP_C = 8; public final int OP_AC = 9; public final int DECSEP = -1; String msDecimal; int mnOp = OP_NONE; boolean mbNewNumber = true; boolean mbDecimal = false; double mdReg = 0.0; public void init() { CalcButton btn0, btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9; CalcButton btnDecSep, btnNeg, btnSqrt, btnPlus, btnMinus; CalcButton btnTimes, btnDiv, btnEqual, btnClear, btnAllClear; setLayout(null); setFont(new Font("Century Gothic", Font.BOLD, 13)); setBackground(new Color(0xFF, 0x00, 0xFF)); btn0 = new CalcButton("0", OP_NONE, 0); add(btn0); btn0.reshape(64, 144, 96, 24); btn1 = new CalcButton("1", OP_NONE, 1); add(btn1); btn1.reshape(64, 112, 40, 24); btn2 = new CalcButton("2", OP_NONE, 2); add(btn2); btn2.reshape(120, 112, 40, 24); btn3 = new CalcButton("3", OP_NONE, 3); add(btn3); btn3.reshape(176, 112, 40, 24); btn4 = new CalcButton("4", OP_NONE, 4); add(btn4); btn4.reshape(64, 80, 40, 24); btn5 = new CalcButton("5", OP_NONE, 5); add(btn5);

btn5.reshape(120, 80, 40, 24); btn6 = new CalcButton("6", OP_NONE, 6); add(btn6); btn6.reshape(176, 80, 40, 24); btn7 = new CalcButton("7", OP_NONE, 7); add(btn7); btn7.reshape(64, 48, 40, 24); btn8 = new CalcButton("8", OP_NONE, 8); add(btn8); btn8.reshape(120, 48, 40, 24); btn9 = new CalcButton("9", OP_NONE, 9); add(btn9); btn9.reshape(176, 48, 40, 24); btnDecSep = new CalcButton("", OP_NONE, DECSEP); add(btnDecSep); btnDecSep.reshape(176, 144, 40, 24); btnNeg = new CalcButton("+/-", OP_NEG, 0); add(btnNeg); btnNeg.reshape(8, 48, 40, 24); btnSqrt = new CalcButton("Sqrt", OP_SQRT, 0); add(btnSqrt); btnSqrt.reshape(8, 80, 40, 24); btnPlus = new CalcButton("+", OP_ADD, 0); add(btnPlus); btnPlus.reshape(232, 112, 40, 56); btnMinus = new CalcButton("-", OP_SUB, 0); add(btnMinus); btnMinus.reshape(288, 112, 40, 24); btnTimes = new CalcButton("", OP_MUL, 0); add(btnTimes); btnTimes.reshape(232, 80, 40, 24); btnDiv = new CalcButton("", OP_DIV, 0); add(btnDiv); btnDiv.reshape(288, 80, 40, 24);

btnEqual = new CalcButton("=", OP_EQ, 0); add(btnEqual); btnEqual.reshape(288, 144, 40, 24); btnClear = new CalcButton("C", OP_C, 0); add(btnClear); btnClear.reshape(8, 112, 40, 24); btnAllClear = new CalcButton("AC", OP_AC, 0); add(btnAllClear); btnAllClear.reshape(8, 144, 40, 24); txtDisp = new TextField("0", 80); txtDisp.setEditable(false); add(txtDisp); txtDisp.reshape(64, 8, 268, 27); String sOneTenth = (new Double(0.1)).toString(); msDecimal = sOneTenth.substring(sOneTenth.length()-2).substring(0, 1); } public static void main(String args[]) { Frame frm = new Frame("Tamira's Calculator"); PocketCalc ex1 = new PocketCalc(); ex1.init(); frm.add("Center", ex1); frm.pack(); frm.resize(350, 210); frm.show(); } public void append(int nValue) { String sDigit; if(nValue == DECSEP) if(!mbDecimal) { if(mbNewNumber) { txtDisp.setText("0"); mbNewNumber = false; } mbDecimal = true; sDigit = msDecimal; }

else return; else sDigit = (new Integer(nValue)).toString(); if(mbNewNumber) { txtDisp.setText(sDigit); mbNewNumber = false; } else txtDisp.setText(txtDisp.getText() + sDigit); repaint(); } public void doOp(int nNewOp) { double dDisp; dDisp = (new Double(txtDisp.getText())).doubleValue(); switch(nNewOp) { case OP_NEG: case OP_SQRT: case OP_C: case OP_AC: switch(nNewOp) { case OP_NEG: txtDisp.setText((new Double(-dDisp)).toString()); break; case OP_SQRT: txtDisp.setText((new Double(Math.sqrt(dDisp))).toString()); mbNewNumber = true; mbDecimal = false; break; case OP_C: mbNewNumber = true; mbDecimal = false; txtDisp.setText("0"); break; case OP_AC: mnOp = OP_NONE; mbNewNumber = true; mbDecimal = false; mdReg = 0.0; txtDisp.setText("0");

break; } break; case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV: case OP_EQ: switch(mnOp) { case OP_ADD: mdReg = mdReg + dDisp; break; case OP_SUB: mdReg = mdReg - dDisp; break; case OP_MUL: mdReg = mdReg * dDisp; break; case OP_DIV: mdReg = mdReg / dDisp; break; case OP_EQ: case OP_NONE: mdReg = dDisp; break; } mnOp = nNewOp; mbNewNumber = true; mbDecimal = false; txtDisp.setText((new Double(mdReg)).toString()); break; } } } class CalcButton extends Button { int mnOp; int mnValue; CalcButton(String sText, int nOp, int nValue) { super(sText); mnOp = nOp; mnValue = nValue;

} public boolean action(Event evt, Object arg) { PocketCalc par = (PocketCalc)getParent(); if(mnOp == par.OP_NONE) par.append(mnValue); else { par.doOp(mnOp); } return true; } }

----------------------------------------(8) GAME ----------------------------------------A. MAIN FINALE APPLET import java.awt.*; import java.util.*; import java.applet.*; import java.net.*;

public class Main extends Applet implements Runnable { // sa image Image img; MediaTracker tr; // Declaration of the variable private int speed; // Thread

boolean isStoped = true; // Deklaration der Objektreferenzen private Player player; // Refference for the object private Ball redball; // Refference for the red ball private Ball blueball; // Refference for the blue ball

// Thread Thread th; // Audioclip inatach nmin sa classes AudioClip shotnoise; // eto ung initialization sa tunog ng gun AudioClip hitnoise; // eto ung initialization sa tunog ng miss AudioClip outnoise; // eto ung initialization sa tunog ng error Font f = new Font ("Serif", Font.BOLD, 20); Cursor c; // Variable sa double buffering private Image dbImage; private Graphics dbg; // Init - Method public void init () { c = new Cursor (Cursor.CROSSHAIR_CURSOR); this.setCursor (c); Color superblue = new Color (0, 0, 255); // sets the backgound color pero ayaw nming gmitin to.. peace^^V img=getImage(getCodeBase(),"grino.jpg"); //font setFont (f); // Speeds the ball in the best limit hnggang 15 lng if (getParameter ("speed") != null) { speed = Integer.parseInt(getParameter("speed")); } else speed = 15; // di2 nkapaloob ung source kung saan nmin inaste ang audioclip na mula sa classes hitnoise = getAudioClip (getCodeBase() , "gun.au"); // Variable for the Cursor

hitnoise.play(); hitnoise.stop(); shotnoise = getAudioClip (getCodeBase() , "miss.au"); shotnoise.play(); shotnoise.stop(); outnoise = getAudioClip (getCodeBase() , "error.au"); outnoise.play(); outnoise.stop(); // Initializing the object player = new Player (); redball = new Ball (10, 190, 250, 1, -1, 4, Color.red, outnoise, player); blueball = new Ball (10, 190, 150, 1, 1, 3, Color.blue, outnoise, player); } // Start - Method public void start () { //Threads th = new Thread (this); th.start (); } // Stop - Method magsstop ang applet di2 public void stop () { th.stop(); } // pra sa mouse event public boolean mouseDown (Event e, int x, int y) { if (!isStoped) { // Test kung mahihit ang ball if (redball.userHit (x, y)) { // kapg nahit ang red ball tu2nog ito mula sa source na ipinaste nmin sa classes hitnoise.play(); redball.ballWasHit (); }

// kapg nahit ang blue ball tu2nog ito mula sa source na ipinaste nmin sa classes if (blueball.userHit (x, y)) { // di2 tutunog hitnoise.play(); //di2 rin tutunog kpg na hit ang bola blueball.ballWasHit (); } else { shotnoise.play(); } } else if (isStoped && e.clickCount == 2) { isStoped = false; init (); } return true; } // Implementing the Run method public void run () { // implementing the thread Thread.currentThread().setPriority(Thread.MIN_PRIORITY); while (true) { if (player.getLives() >= 0 && !isStoped) { redball.move(); blueball.move(); } repaint(); try {

// Stops the Threads for milliseconds Thread.sleep (speed); } catch (InterruptedException ex) { // do nothing } // This is for the ThreadPriority for maximum priority Thread.currentThread().setPriority(Thread.MAX_PRIORITY); } } // Paint - Method public void paint (Graphics g) { // pra sa backgound tr=new MediaTracker(this); img=getImage(getCodeBase(),"grino.jpg"); tr.addImage(img,0); g.drawImage(img,0,0,this); if (player.getLives() >= 0) { // Sets the color g.setColor (Color.yellow); // di2 ung location ng score at lives sa taas na bahagi g.drawString ("Score: " + player.getScore(), 10, 40); g.drawString ("Lives: " + player.getLives(), 300, 40); redball.DrawBall(g); blueball.DrawBall(g); if (isStoped) { g.setColor (Color.yellow); g.drawString ("Doubleclick on Applet to start Game!", 40, 200); } } else if (player.getLives() < 0) {

g.setColor (Color.yellow); // location kung saan ilalagay ung drawstring kpg na gameover na g.drawString ("Game over!", 130, 100); g.drawString ("You scored " + player.getScore() + " Points!", 90, 140); if (player.getScore() < 300) g.drawString ("Galingan mo pa!", 100, 190); else if (player.getScore() < 600 && player.getScore() >= 300) g.drawString ("Hindi na masama..:D", 100, 190); else if (player.getScore() < 900 && player.getScore() >= 600) g.drawString ("Hmmmm.. Pwede na..:D", 100, 190); else if (player.getScore() < 1200 && player.getScore() >= 900) g.drawString ("Galing mo!!", 90, 190); else if (player.getScore() < 1500 && player.getScore() >= 1200) g.drawString ("Whoah!! Idol.. hahaha!", 90, 190); else if (player.getScore() >= 1500) g.drawString ("Yesssss!! Panalo..!!",100, 190); g.drawString ("Doubleclick on the Applet, to play again!", 20, 220); isStoped = true; } } // Update - Method public void update (Graphics g) { // Initializing the DoubleBuffers if (dbImage == null) { dbImage = createImage (this.getSize().width, this.getSize().height); dbg = dbImage.getGraphics (); } dbg.setColor (getBackground ()); dbg.fillRect (0, 0, this.getSize().width, this.getSize().height); dbg.setColor (getForeground()); paint (dbg); // Stopped the variable

g.drawImage (dbImage, 0, 0, this); } } B. CLASS HTML <html> <body background="http://www.dfsm.org/layouts/skinny-layouts/yellowbackground-skinny-1.jpg"> <h1><u><div align="center">Shot the ball!</div></u></h1> </p> <H3><HR WIDTH="100%">Applet HTML Page<HR WIDTH="100%"></H3> <p align = center> <APPLET codebase="classes" code="Main.class" width=380 height=380></APPLET> </p> <HR WIDTH="100%"><FONT SIZE=-1><I>Generated by NetBeans IDE</I></FONT> <param name = "speed" value = 15> </body> </html> C. BALL FINALE APPLET import java.applet.*; import java.awt.*; import java.util.*; import java.net.*; public class Ball { //di2 nakaploob ang funtion ng bola na kung saan di2 nklahad ung itsura at position ng dlwang bola sa applet private int pos_x; private int pos_y; private int x_speed; // Variable for die X // Variable for die Y

private int y_speed; private int radius; private int first_x; private int first_y; private int maxspeed; // Declaration of the constant (kung ilalagay sa html 380 x 380 ang size) private final int x_leftout = 10; private final int x_rightout = 370; private final int y_upout = 45; private final int y_downout = 370; Color color; // AudioClip out AudioClip out; // Refference in the player object Player player; // Randomize the flow of the objcet which is the ball ^^ Random rnd = new Random (); //initialization public Ball (int radius, int x, int y, int vx, int vy, int ms, Color color, AudioClip out, Player player) { // Initializing the variable this.radius = radius; pos_x = x; pos_y = y; first_x = x; first_y = y; x_speed = vx; y_speed = vy; maxspeed = ms; this.color = color; // Start x - Position // Start y - Position

this.out = out; this.player = player; } // Move - Method pra sa bola public void move () { pos_x += x_speed; pos_y += y_speed; isOut(); } public void ballWasHit () { // Position ng bola pos_x = first_x; pos_y = first_y; x_speed = (rnd.nextInt ()) % maxspeed; } public boolean userHit (int maus_x, int maus_y) { double x = maus_x - pos_x; double y = maus_y - pos_y; // for the distance double distance = Math.sqrt ((x*x) + (y*y)); if (distance < 15) { player.addScore (10*Math.abs(x_speed) + 10); return true; } else return false; } private boolean isOut ()

{ // Ball im Linken Aus if (pos_x < x_leftout) { // Sets x - Position pos_x = first_x; pos_y = first_y; // Audioclips out.play(); x_speed = (rnd.nextInt ()) % maxspeed; player.looseLife(); return true; } else if (pos_x > x_rightout) { // Sets der x - Position pos_x = first_x; pos_y = first_y; //Audioclips out.play(); x_speed = (rnd.nextInt ()) % maxspeed; player.looseLife(); return true; } else if (pos_y < y_upout) { // Sets the x - Position pos_x = first_x; pos_y = first_y;

// Audioclips out.play(); x_speed = (rnd.nextInt ()) % maxspeed; player.looseLife(); return true; } else if (pos_y > y_downout) { // Sets x - Position pos_x = first_x; pos_y = first_y; // Audioclips out.play(); x_speed = (rnd.nextInt ()) % maxspeed; player.looseLife(); return true; } else return false; } public void DrawBall (Graphics g) { g.setColor (color); g.fillOval (pos_x - radius, pos_y - radius, 2 * radius, 2 * radius); } } ------------------------------------------(9) GRADING SYSTEM -------------------------------------------

import java.applet.Applet; import java.awt.*; import java.awt.Graphics.*; import java.awt.event.*;

public class Main extends Applet implements ActionListener { Image ama;

Graphics graphics;

int txt;;

Label titleLabel = new Label("

AMA Grade calculator

");

Label prelimq1Label = new Label("Prelim Quiz 1: ",Label.LEFT); TextField prelimq1Field = new TextField(10);

Label prelimq2Label = new Label("Prelim Quiz 2: ",Label.LEFT); TextField prelimq2Field = new TextField(10);

Label prelimcsLabel = new Label("Prelim CS: TextField prelimcsField = new TextField(10);

",Label.LEFT);

Label prelimexLabel = new Label("Prelim Exam: TextField prelimexField = new TextField(10);

",Label.LEFT);

//-----------------lines breaks-------------------------------Label ln1 = new Label("______________________________________",Label.LEFT); Label ln2 = new Label("______________________________________",Label.LEFT); Label ln3 = new Label("______________________________________",Label.LEFT); Label ln4 = new Label("______________________________________",Label.LEFT); Label ln5 = new Label("______________________________________",Label.LEFT);

//-------------------------midterm--------------------

Label midtermq1Label = new Label("Midterm Quiz 1: ",Label.LEFT); TextField midtermq1Field = new TextField(10);

Label midtermq2Label = new Label("Midterm Quiz 2: TextField midtermq2Field = new TextField(10);

",Label.LEFT);

Label midtermcsLabel = new Label("Midterm CS:

",Label.LEFT);

TextField midtermcsField = new TextField(10);

Label midtermexLabel = new Label("Midterm TextField midtermexField = new TextField(10);

Exam: ",Label.LEFT);

//----------------------finals-----------------

Label finalq1Label = new Label("Final Quiz 1: ",Label.LEFT); TextField finalq1Field = new TextField(10);

Label finalq2Label = new Label("Final Quiz 2: ",Label.LEFT); TextField finalq2Field = new TextField(10);

Label finalcsLabel = new Label("Final CS:

",Label.LEFT);

TextField finalcsField = new TextField(10);

Label finalexLabel = new Label("Final Exam:

",Label.LEFT);

TextField finalexField = new TextField(10);

Button computeButton = new Button(" Compute "); Button clearButton = new Button(" Clear ");

Label prelimgLabel = new Label("Prelim Grade: TextField prelimgField = new TextField(10);

",Label.RIGHT);

Label midtermgLabel = new Label("Midterm Grade: ",Label.RIGHT); TextField midtermgField = new TextField(10);

Label finalgLabel = new Label("Final Grade: TextField finalgField = new TextField(10);

",Label.RIGHT);

Label gradeLabel = new Label("Total Grade: ",Label.RIGHT); TextField gradeField = new TextField(10);

Label statusLabel = new Label("Status: ",Label.RIGHT); TextField statusField = new TextField("enter the data",20);

public void init()

{ //begin init------------------------------ama = getImage(getCodeBase(),"baloons.jpg");

setBackground(Color.black); setForeground(Color.red); add(titleLabel);

add(prelimq1Label); add(prelimq1Field); prelimq1Field.setForeground(Color.blue);

add(prelimq2Label); add(prelimq2Field); prelimq2Field.setForeground(Color.blue);

add(prelimcsLabel); add(prelimcsField); prelimcsField.setForeground(Color.blue);

add(prelimexLabel); add(prelimexField); prelimexField.setForeground(Color.blue);

add(ln1);

//-------------------------------------------------------------add(midtermq1Label); add(midtermq1Field); midtermq1Field.setForeground(Color.red);

add(midtermq2Label); add(midtermq2Field); midtermq2Field.setForeground(Color.red);

add(midtermcsLabel); add(midtermcsField); midtermcsField.setForeground(Color.red);

add(midtermexLabel); add(midtermexField); midtermexField.setForeground(Color.red);

add(ln2); //----------------------------------------------add(finalq1Label); add(finalq1Field); finalq1Field.setForeground(Color.black);

add(finalq2Label); add(finalq2Field); finalq2Field.setForeground(Color.black);

add(finalcsLabel); add(finalcsField); finalcsField.setForeground(Color.black);

add(finalexLabel); add(finalexField); finalexField.setForeground(Color.black);

add(ln3);

add(computeButton); computeButton.addActionListener(this); add(clearButton); clearButton.addActionListener(this); add(ln4); add(prelimgLabel); add(prelimgField); prelimgField.setForeground(Color.blue);

add(midtermgLabel); add(midtermgField); midtermgField.setForeground(Color.red);

add(finalgLabel); add(finalgField); finalgField.setForeground(Color.black); add(ln5); add(gradeLabel);

add(gradeField); gradeField.setForeground(Color.black);

add(statusLabel); add(statusField); statusField.setForeground(Color.black);

} // end init

public void paint(Graphics g) { g.drawImage(ama,0,0,this);

public void actionPerformed(ActionEvent Grade) {

//declare object strings String strprelimq1 = new String(prelimq1Field.getText()); String strprelimq2 = new String(prelimq2Field.getText()); String strprelimcs = new String(prelimcsField.getText()); String strprelimex = new String(prelimexField.getText());

String strmidtermq1 = new String(midtermq1Field.getText()); String strmidtermq2 = new String(midtermq2Field.getText()); String strmidtermcs = new String(midtermcsField.getText()); String strmidtermex = new String(midtermexField.getText());

String strfinalq1 = new String(finalq1Field.getText()); String strfinalq2 = new String(finalq2Field.getText()); String strfinalcs = new String(finalcsField.getText()); String strfinalex = new String(finalexField.getText());

if (Grade.getSource()==computeButton)

{ if (strprelimq1.equals("")) { prelimq1Field.setText("0"); } if (strprelimq2.equals("")) { prelimq2Field.setText("0"); } if (strprelimcs.equals("")) { prelimcsField.setText("0");

} if (strprelimex.equals("")) { prelimexField.setText("0"); }

//---------------midterm------------------------

if (strmidtermq1.equals("")) { midtermq1Field.setText("0"); } if (strmidtermq2.equals("")) { midtermq2Field.setText("0"); } if (strmidtermcs.equals("")) { midtermcsField.setText("0"); } if (strmidtermex.equals("")) { midtermexField.setText("0"); } //--------------finals---------------------------

if (strfinalq1.equals("")) { finalq1Field.setText("0"); } if (strfinalq2.equals("")) { finalq2Field.setText("0"); } if (strfinalcs.equals("")) { finalcsField.setText("0"); } if (strfinalex.equals("")) { finalexField.setText("0"); }

// Converting input to values int prelimq1 = Integer.parseInt(prelimq1Field.getText()); int prelimq2 = Integer.parseInt(prelimq2Field.getText()); int prelimcs = Integer.parseInt(prelimcsField.getText()); int prelimex = Integer.parseInt(prelimexField.getText());

int midtermq1 = Integer.parseInt( midtermq1Field.getText()); int midtermq2 = Integer.parseInt( midtermq2Field.getText()); int midtermcs = Integer.parseInt( midtermcsField.getText()); int midtermex = Integer.parseInt( midtermexField.getText());

int finalq1 = Integer.parseInt(finalq1Field.getText()); int finalq2 = Integer.parseInt(finalq2Field.getText()); int finalcs = Integer.parseInt(finalcsField.getText()); int finalex = Integer.parseInt(finalexField.getText());

// Calculations

double prelimg = (prelimq1*0.2) +(prelimq2*0.2) + (prelimcs*0.1)+(prelimex*0.5);

double midtermg = (midtermq1*0.2) +(midtermq2*0.2) + (midtermcs*0.1)+ (midtermex*0.5);

double finalg = ( finalq1*0.2) +( finalq2*0.2) + ( finalcs*0.1)+( finalex*0.5);

double grade = (prelimg * 0.3) + (midtermg * 0.3) + (finalg * 0.4); // Output grade prelimgField.setText("" + Math.round(prelimg)); midtermgField.setText("" + Math.round(midtermg)); finalgField.setText("" + Math.round(finalg));

gradeField.setText("" + Math.round(grade));

if (grade<75) { statusField.setText("Failed"); } else { statusField.setText("Passed"); }

if (grade > 100) { statusField.setText("NOT VALID!"); }

} // end if computeButton

if (Grade.getSource()==clearButton) { gradeField.setText("");

prelimq1Field.setText(""); prelimq2Field.setText(""); prelimcsField.setText(""); prelimexField.setText("");

midtermq1Field.setText(""); midtermq2Field.setText(""); midtermcsField.setText(""); midtermexField.setText("");

finalq1Field.setText(""); finalq2Field.setText(""); finalcsField.setText(""); finalexField.setText("");

prelimgField.setText("none"); midtermgField.setText("none"); finalgField.setText("none");

statusField.setText("nothing..."); } // end if clearButton } // end actionperformed

} // end class

Vous aimerez peut-être aussi