Posted on Leave a comment

Remove all Occurrence

This is number 2 from handout #4 : string processing.

[code lang=”java”]/*
* RemoveAllOccurences
*/

import acm.program.*;

public class RemoveAllOccurences extends ConsoleProgram{
public void run(){
while(true){ // infinite loop
String str1 = readLine("Give me a string(q to exit): "); // q as a sentinel to break out of the loop
if(str1.equals("q"))
break;
String str2 = readLine("Give me a character to remove: "); // give me the char

int charIndex = 0; // get the first char only
char ch = str2.charAt(charIndex); //

println(removeAllOccurrence(str1,ch)); // call removeAllOccurence
}
}

// remove all occurrence of a char in a string
private String removeAllOccurrence(String str, char ch){
String result = ""; // declare a new String object result
int firstIndex = 0; // beginning of the string
int indexChar =str.indexOf(ch); // find the index of the first occurrence
while(indexChar!=-1){ //loop through the string str until we find all occurrence
result+=str.substring(firstIndex,indexChar); //iterate
firstIndex = indexChar+1; // skip the char
indexChar = str.indexOf(ch, firstIndex); // get the next index of the next substring
}
return result+str.substring(firstIndex); //add the end of the result string and return it
}
}[/code]

Posted on Leave a comment

BreakOut somewhat finish

This is a ridiculous game that I was able to build just by following Stanford’s CS106a. This is almost a complete game. The main part is done .It just needs a little polishing. I am moving on to the next assignment for now.

[code lang=”java”]

/*
* File: Breakout.java
* ——————-
* Name:
* Section Leader:
*
* This file will eventually implement the game of Breakout.
*/

import acm.graphics.*;
import acm.program.*;
import acm.util.*;

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

public class Breakout extends GraphicsProgram {

/** Width and height of application window in pixels */
public static final int APPLICATION_WIDTH = 400;
public static final int APPLICATION_HEIGHT = 600;

/** Dimensions of game board (usually the same) */
private static final int WIDTH = APPLICATION_WIDTH;
private static final int HEIGHT = APPLICATION_HEIGHT;

/** Dimensions of the paddle */
private static final int PADDLE_WIDTH = 60;
private static final int PADDLE_HEIGHT = 10;

/** Offset of the paddle up from the bottom */
private static final int PADDLE_Y_OFFSET = 30;

/** Number of bricks per row */
private static final int NBRICKS_PER_ROW = 10;

/** Number of rows of bricks */
private static final int NBRICK_ROWS = 10;

/** Separation between bricks */
private static final int BRICK_SEP = 4;

/** Width of a brick */
private static final int BRICK_WIDTH =
(WIDTH – (NBRICKS_PER_ROW – 1) * BRICK_SEP) / NBRICKS_PER_ROW;

/** Height of a brick */
private static final int BRICK_HEIGHT = 8;

/** Radius of the ball in pixels */
private static final int BALL_RADIUS = 10;

/** Offset of the top brick row from the top */
private static final int BRICK_Y_OFFSET = 70;

/** Number of turns */
private static final int NTURNS = 3;

/** copied from BouncingBall.java **/
private static final double INITIAL_SPEED = 3.0;

/** pause time */
private static final double PAUSE_TIME = 1000 /24;

/** middle space height*/
private static final double MID_SPACE = (HEIGHT +BRICK_Y_OFFSET + (NBRICK_ROWS*BRICK_HEIGHT))/2;
//private static final int NBRICKS_ROWS = 0;

/* Method: run() */
/** Runs the Breakout program. */
public void run() {

brick_count = NBRICKS_PER_ROW*NBRICK_ROWS; // number of bricks
setup(); //setup the game method call

int turns =NTURNS; // how many lives we have
while(turns>0){
moveBall();
//gameover();
if(ballHitsBottom(ball) || brick_count ==0){
gameover();
break;
}
if(turns != NTURNS){
setup();
}
turns–;
}
gameover();
}

// setup methods
private void setup(){
setup_bricks(); // setup the bricks
setup_paddle(); // paddle setup
setup_ball(); // ball setup
}

// gameover if the ball hits bottom or there is no more bricks
private void gameover(){
//return (ballHitsBottom() || noMoreBricks());
GLabel gameover = new GLabel("GAME OVER");
gameover.setColor(Color.RED);
add(gameover,(WIDTH-gameover.getWidth())/2,(MID_SPACE – gameover.getAscent())/2);
//return gameover;
}

private boolean ballHitsBottom(GOval ball){
return ball.getY() >= HEIGHT – ball.getHeight() ;
}

// create a brick
private void createbrick(Color color,double x, double y){
brick = new GRect(BRICK_WIDTH,BRICK_HEIGHT); // brick is a new GRect object
brick.setFilled(true); // it is filled
brick.setColor(Color.WHITE); // the color is white
brick.setFillColor(color); // set the fill color with color parameter
add(brick,x,y); // add the brick to the x , y parameter location
}
// setup the bricks

private void setup_bricks(){
int init_x = 0; // initial x , the left margin of the window

for (int i = 1; i <= NBRICKS_PER_ROW;i++) { // loop through the bricks per row
for (int j = 0;j < NBRICK_ROWS;j++){ // loop through the no. of rows
// compute the x position which starts at 0 then add a brick then a brick separator
int x = init_x+(j * BRICK_WIDTH)+ (j*BRICK_SEP);

//compute the y by adding offset and a brick plus separator
int y = BRICK_Y_OFFSET+(i * BRICK_HEIGHT)+(i*BRICK_SEP);

// colorize base on the row index i
if (i==1 || i==2){
createbrick(Color.RED,x,y);
} else if (i==3 || i==4){
createbrick(Color.ORANGE,x,y);
} else if (i==5 || i==6){
createbrick(Color.YELLOW,x,y);
} else if (i==7 || i==8){
createbrick(Color.GREEN,x,y);
} else if (i==9 || i==10){
createbrick(Color.CYAN,x,y);
}
}
}
}

// setup the paddle
private void setup_paddle(){
// put paddle in the middle
paddle = new GRect(getWidth()/2-PADDLE_WIDTH/2,getHeight()-PADDLE_Y_OFFSET,PADDLE_WIDTH,PADDLE_HEIGHT);
paddle.setFilled(true);
paddle.setFillColor(Color.BLUE);
paddle.setColor(Color.BLUE);
add(paddle);
addMouseListeners(); //adds mouse listeners
}

//track the paddle
public void mouseMoved(MouseEvent e){
paddle.setLocation(e.getX(), getHeight()-PADDLE_Y_OFFSET);
if ((e.getX()+PADDLE_WIDTH)>getWidth()){
paddle.setLocation(getWidth()-PADDLE_WIDTH, getHeight()-PADDLE_Y_OFFSET);

}
}

// setup the ball in the middle of the screen
private void setup_ball(){
double startX = (WIDTH – BALL_RADIUS)/2;
double startY = (HEIGHT +BRICK_Y_OFFSET +(BRICK_HEIGHT*NBRICK_ROWS))/2;
ball = new GOval(BALL_RADIUS, BALL_RADIUS);
ball.setFilled(true);
ball.setFillColor(Color.BLACK);
add(ball,startX,startY);
}

/*
* move the ball
*/
private void moveBall(){
double low_vel = 1.0; // low velocity of the ball
double high_vel = 3.0; // high velocity of the ball
double chance = 0.5; // randomize the chance by half
vx = rgen.nextDouble(low_vel, high_vel); // random x velocity
if (rgen.nextBoolean(chance)){ // half the chance of ball going left or right
vx = -vx; // change to the opposite direction
}
vy = INITIAL_SPEED; //set the initial speed

waitForClick(); //wait for a click to start the game
//while(isBallOnScreen(ball)){ //keep moving till ball disappears
while(!ballHitsBottom(ball) || brick_count!=0){
ball.move(vx, vy); // move by setting vx,vy
checkForCollisions(); //check if ball hits something
pause(PAUSE_TIME); //pause animation
}
}

/**
* isBallOnScreen
* check for the ball location
* @param ball
* @return
*/
private boolean isBallOnScreen(GOval ball){
return ball.getX() <= WIDTH-(BALL_RADIUS*2) || ball.getX() >= 0 || ball.getY() <=HEIGHT || ball.getY() >=0;
}

private void checkForCollisions(){
collider = getCollidingObject(); //get the colliding object
if(collider != null){
bounceClip.play();
if (collider == paddle){ // if its a paddle go the opposite direction
/*if(collider.){
vy = -vy;
vx = -vx;
} else {*/
vy = -vy;
//}

} else { // if its a brick go the opposite ,remove the brick and subtract brick count
vy = -vy; // bounce
remove(collider);
brick_count–;
}
}

// top
if (ball.getY() <= 0){
vy = -vy;
}

// if ball hits right side
if (ball.getX() >= WIDTH-(BALL_RADIUS) ){
vx = -vx;
}
// if ball hits top

// if ball hits left side
if (ball.getX() <= 0 ){
vx = -vx;
}
}

/**
* getcollidingobject
* gets the colliding object by testing all four bounding corners of the ball which is just a GRect
* @return
*/
private GObject getCollidingObject(){
if (getElementAt(ball.getX(), ball.getY()) != null){
return (getElementAt(ball.getX(), ball.getY()));
}

if (getElementAt(ball.getX()+2*(BALL_RADIUS), ball.getY()) != null){
return (getElementAt(ball.getX()+2*(BALL_RADIUS), ball.getY()));
}

if (getElementAt(ball.getX(),ball.getY()+2*(BALL_RADIUS)) !=null ){
return (getElementAt(ball.getX(),ball.getY()+2*(BALL_RADIUS)));
}

if (getElementAt(ball.getX()+2*(BALL_RADIUS),ball.getY()+2*(BALL_RADIUS)) != null){
return (getElementAt(ball.getX()+2*(BALL_RADIUS),ball.getY()+2*(BALL_RADIUS)));
}

return null;

}
/* Private instance variables */
private int brick_count; // count the number of bricks
private GRect brick; // the brick object
private GObject collider; // the object the ball collided
private GRect paddle; // the paddle
private GOval ball; // the ball
private double vx, vy; // the velocity in x and y
private RandomGenerator rgen = RandomGenerator.getInstance(); // random generator
AudioClip bounceClip = MediaTools.loadAudioClip("bounce.au");

}
[/code]

Posted on Leave a comment

Drawline.java solution

Mouse events with java.
[code lang=”java”]/*
* DrawLines.java
* draw lines in canvas
* ralph @today
*
*/

import acm.graphics.*;
import acm.program.*;
import java.awt.event.*;

public class Drawlines extends GraphicsProgram {

public void run(){
/* Tell Java that we’re ready for the mouse */
addMouseListeners();
}

public void mousePressed(MouseEvent e){
// start the line with a mousepressed event
line = new GLine(e.getX(),e.getY(),e.getX(),e.getY());
add(line);
}

public void mouseDragged(MouseEvent e){
/* end the line where we click */
line.setEndPoint(e.getX(), e.getY());
}

/* private instance variables */
private GLine line;
}[/code]

Posted on Leave a comment

Circles

I am so proud of myself that I figured it out how to fit the circles on the window. I was stuck for a while but I finally figured it out today.

[code lang=”java”]/**
* Circle.java – Make random circles
* @author rafiks
*/

import java.awt.Color;

import acm.graphics.*;
import acm.program.*;
import acm.util.*;

public class Circle extends GraphicsProgram {
// Constants
// number of circles
private static final int NUM_CIRCLES=15;

//minimum radius
private static final int MIN_RAD=20;

//max radius
private static final int MAX_RAD=200;

//seed for troubleshooting
//private static final int SEED=1;

public void run(){

//rgen.setSeed(SEED);

//for loop to generate the circles base on NUM_CIRCLES
for(int i=0;i<NUM_CIRCLES;i++){
//random radius set wit MIN_RAD and MAX_RAD
int radius = rgen.nextInt(MIN_RAD, MAX_RAD);
// set x so that it fits the window
int x = rgen.nextInt(radius,getWidth()-radius);
// set y so that it fits the window
int y = rgen.nextInt(radius,getHeight()-radius);
// set a random color
Color c = rgen.nextColor();
//draw the circle
drawCircle(x,y,radius,c);
}
}

/* Method to Draw a circle base on the parameters */
private void drawCircle(int x,int y,int radius,Color c){
GOval circle = new GOval(x,y,radius,radius);
circle.setFilled(true);
circle.setColor(c);
circle.setFillColor(c);
add(circle);
}

/** private instance variable */
private RandomGenerator rgen = RandomGenerator.getInstance();
}
[/code]

Posted on Leave a comment

RobotFace with Methods

[code lang=”java”]/*
* File: RobotFace.java
* ———————
* This class is a blank one that you can change at will. Remember, if you change
* the class name, you’ll need to change the filename so that it matches.
* Then you can extend GraphicsProgram, ConsoleProgram, or DialogProgram as you like.
*/

import acm.program.*;
import acm.graphics.*;
import java.awt.*;

public class RobotFace extends GraphicsProgram {
private static final int HEAD_WIDTH=265;
private static final int HEAD_HEIGHT=400;
private static final int EYE_RADIUS=50;
private static final int MOUTH_WIDTH=200;
private static final int MOUTH_HEIGHT=50;

public void run() {
int middle_x = getWidth()/2;
int middle_y = getHeight()/2;
int leftEye_x = middle_x-HEAD_WIDTH/4-EYE_RADIUS/2;
int rightEye_x = middle_x+HEAD_WIDTH/4-EYE_RADIUS/2;

add(Head(middle_x,middle_y));
addEyes(leftEye_x,rightEye_x,middle_y);
add(Mouth(middle_x,middle_y));

}

//Head method
private GRect Head(int x,int y){
//Head
GRect myHead = new GRect(x-HEAD_WIDTH/2,y-HEAD_HEIGHT/2,HEAD_WIDTH, HEAD_HEIGHT);
myHead.setFilled(true);
myHead.setFillColor(Color.GRAY);
return myHead;

}

//Eyes method
private void addEyes( int left_eye,int right_eye ,int y){
//add left Eye
add(Eye(left_eye,y));

//add right eye
add(Eye(right_eye,y));

}

//Mouth method
private GRect Mouth(int x,int y){
GRect mouth = new GRect(x-MOUTH_WIDTH/2,y+HEAD_HEIGHT/4,MOUTH_WIDTH,MOUTH_HEIGHT);
mouth.setFilled(true);
mouth.setFillColor(Color.WHITE);
return mouth;

}

//individual Eye method
private GOval Eye(int x,int y){
//Eyes

GOval myEye = new GOval(x, y-HEAD_HEIGHT/4, EYE_RADIUS, EYE_RADIUS);
myEye.setFilled(true);
myEye.setFillColor(Color.YELLOW);
return myEye;

}

}

[/code]

Posted on Leave a comment

RobotFace solution

[code lang=”java”]
/*
* File: RobotFace.java
* ———————
* This class is a blank one that you can change at will. Remember, if you change
* the class name, you’ll need to change the filename so that it matches.
* Then you can extend GraphicsProgram, ConsoleProgram, or DialogProgram as you like.
*/

import acm.program.*;
import acm.graphics.*;
import java.awt.*;

public class RobotFace extends GraphicsProgram {
private static final int HEAD_WIDTH=265;
private static final int HEAD_HEIGHT=400;
private static final int EYE_RADIUS=50;
private static final int MOUTH_WIDTH=200;
private static final int MOUTH_HEIGHT=50;

public void run() {
int middle_x = getWidth()/2;
int middle_y = getHeight()/2;

//Head
GRect myHead = new GRect(middle_x-HEAD_WIDTH/2,middle_y-HEAD_HEIGHT/2,HEAD_WIDTH, HEAD_HEIGHT);
myHead.setFilled(true);
myHead.setFillColor(Color.GRAY);
add(myHead);

//Eyes

GOval leftEye = new GOval(middle_x-HEAD_WIDTH/4-EYE_RADIUS/2, middle_y-HEAD_HEIGHT/4, EYE_RADIUS, EYE_RADIUS);
leftEye.setFilled(true);
leftEye.setFillColor(Color.YELLOW);
add(leftEye);

GOval rightEye = new GOval(middle_x+HEAD_WIDTH/4-EYE_RADIUS/2, middle_y-HEAD_HEIGHT/4, EYE_RADIUS, EYE_RADIUS);
rightEye.setFilled(true);
rightEye.setFillColor(Color.YELLOW);
add(rightEye);

//Mouth

GRect mouth = new GRect(middle_x-MOUTH_WIDTH/2,middle_y+HEAD_HEIGHT/4,MOUTH_WIDTH,MOUTH_HEIGHT);
mouth.setFilled(true);
mouth.setFillColor(Color.WHITE);
add(mouth);
}
}

[/code]

Posted on Leave a comment

Fibonacci.java – solution to HandOut#2

[code lang=”java”]/*
* File: Fibonacci.java
* ———————
* This class is a blank one that you can change at will. Remember, if you change
* the class name, you’ll need to change the filename so that it matches.
* Then you can extend GraphicsProgram, ConsoleProgram, or DialogProgram as you like.
*/

import acm.program.*;

public class Fibonacci extends ConsoleProgram {
//constant for the
private static final int MAX_TERM_VALUE=1000;

public void run() {
println("This Program lists the Fibonacci sequence.");
//we need three variables
//fibonacci 0 = 0
int term = 0;

//fibonacci(1) = 1
int term2 = 1;

//third variable to store the sum
int term3 =0;

//print the fibonacci(0) and (1)
println(term);
println(term2);

// loop until we finish the number in the MAX_TERM_VALUE
while (term < MAX_TERM_VALUE){
// term2(sum) = term plus term2
term3=term+term2;

//print the sum
println(term3);

//mv the next number to term
term=term2;

// and the sum to term2
term2=term3;
}
}
}[/code]

Posted on Leave a comment

FindRange.java solution – Assignment 2

[code lang=”java”]
/*
* File: FindRange.java
* Name:
* Section Leader:
* ——————–
* This file is the starter file for the FindRange problem.
*/

import acm.program.*;

public class FindRange extends ConsoleProgram {
private static final int SENTINEL = 0;

public void run() {
//the smallest number
int smallest = 0;

//the largest
int largest = 0;
//intro
println(&quot;The program finds the largest and smallest numbers.&quot;);

//get the first number
int number = readInt(&quot;? &quot;);
//if there is only one number – make it the smallest and th
// the largest
smallest=number;
largest=smallest;

//loop and a half for the second number
//keep looping until the sentinel is given
while(number!=SENTINEL){
//get the second digit
int number1 = readInt(&quot;? &quot;);

// breaking out of the loop
if(number1==SENTINEL){
break;
}

//find the smallest number
if(number1&lt;smallest ){
smallest=number1;
}

//find the largest number
if(number1&gt;largest){
largest=number1;
}
}

//if the first number is a 0
// else print the smallest and largest
if(number == SENTINEL){
println(&quot;Please enter a number not 0.&quot;);
} else {
println(&quot;smallest: &quot;+smallest);
println(&quot;largest: &quot;+largest);
}

}
}[/code]

Posted on Leave a comment

Hailstone solution -Assignment 2

[code lang=”java”]/*
* File: Hailstone.java
* Name:
* Section Leader:
* ——————–
* This file is the starter file for the Hailstone problem.
*/

import acm.program.*;

public class Hailstone extends ConsoleProgram {
public void run() {
//index for the number of loops to do
int index =0;

//query for the number
int number = readInt("Enter a number: ");

//loop until the number ==1
while(number!=1){
//increment the loop
index++;

//if number is even take half
if(number%2==0){
println(number+" is even so I take half: "+(number/=2));
} else {
//else if odd make it 3n+1
println(number+" is odd, so I make 3n +1: "+(number = (number*3)+1));
}
}
//print the number of loops
println("The process took "+index+" to reach 1.");
}
}

[/code]

Posted on Leave a comment

Solution to PythagoreanTheorem – Assignment 2

[code lang=”java”]
/*
* File: PythagoreanTheorem.java
* Name:
* Section Leader:
* —————————–
* This file is the starter file for the PythagoreanTheorem problem.
*/

import acm.program.*;

public class PythagoreanTheorem extends ConsoleProgram {
public void run() {
println("Enter values to compute Pythagorean Theorem.");
int a = readInt("a: ");
int b = readInt("b: ");
double c = Math.sqrt((a*a)+(b*b));
println("c= "+c);

}
}
[/code]