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

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]

Posted on Leave a comment

Solution to ProgramHeirarchy – Assignment 2

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

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

public class ProgramHierarchy extends GraphicsProgram {
// width of the box
private static final int BOX_WIDTH = 175;

//height of the box
private static final int BOX_HEIGHT = 45;

public void run() {

//middle point of the window
double middle = getWidth()/2;

//height window middle
double height_center = getHeight()/2;

//middle of the box itself
double box_mid = BOX_WIDTH/2;

// half the box height
double box_half = BOX_HEIGHT/2;

// base of top square = height_center -40
double base_top= height_center -40 ;

//roof of bottom boxes
double roof_bottom = height_center + 40 ;

/*
* The boxes here
*/

// top rect
GRect top = new GRect(middle-box_mid,base_top -BOX_HEIGHT,BOX_WIDTH,BOX_HEIGHT);
add(top);

//left rect
GRect left = new GRect(middle/2 -box_mid,roof_bottom,BOX_WIDTH,BOX_HEIGHT);
add(left);

// mid rect
GRect mid = new GRect(middle-box_mid,roof_bottom,BOX_WIDTH,BOX_HEIGHT);
add(mid);

//right rect
GRect right = new GRect(middle + middle/2 – box_mid,roof_bottom,BOX_WIDTH,BOX_HEIGHT);
add(right);

/*
* the lines connecting here
*/

//leftLine
GLine leftLine = new GLine(middle/2,roof_bottom,middle,base_top);
add(leftLine);

//midline
GLine midLine = new GLine(middle,base_top,middle,roof_bottom);
add(midLine);

//rightLine
GLine rightLine = new GLine(middle,base_top,middle+middle/2,roof_bottom);
add(rightLine);

/*
* the labels
*/

// TopLabel
GLabel topLabel = new GLabel("Program");
topLabel.move(middle-topLabel.getWidth()/2, base_top+topLabel.getAscent()/2 -BOX_HEIGHT/2);
add(topLabel);

//LeftLabel
GLabel leftLabel = new GLabel("GraphicsProgram");
leftLabel.move(middle/2-leftLabel.getWidth()/2, roof_bottom+leftLabel.getAscent()/2+BOX_HEIGHT/2);
add(leftLabel);

//Middle Label
GLabel midLabel = new GLabel("ConsoleProgram");
midLabel.move(middle-midLabel.getWidth()/2, roof_bottom+midLabel.getAscent()/2 +BOX_HEIGHT/2);
add(midLabel);

//rightLabel
GLabel rightLabel = new GLabel("DialogProgram");
rightLabel.move(middle+middle/2-rightLabel.getWidth()/2, roof_bottom+rightLabel.getAscent()/2 +BOX_HEIGHT/2);
add(rightLabel);

}
}

[/code]

Posted on Leave a comment

My Pyramid solution for Assignment 2

[code lang=”java”]
/*
* File: Pyramid.java
* Name:
* Section Leader:
* ——————
* This file is the starter file for the Pyramid problem.
* It includes definitions of the constants that match the
* sample run in the assignment, but you should make sure
* that changing these values causes the generated display
* to change accordingly.
*/

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

public class Pyramid extends GraphicsProgram {

/** Width of each brick in pixels */
private static final int BRICK_WIDTH = 30;

/** Width of each brick in pixels */
private static final int BRICK_HEIGHT = 12;

/** Number of bricks in the base of the pyramid */
//private static final int BRICKS_IN_BASE = 14;
private static final int BRICKS_IN_BASE = 20;

public void run() {
// get the middle of the window
double middle = getWidth() /2 ;

// the starting base_width
double base_width = BRICKS_IN_BASE * BRICK_WIDTH;

// where we put the first block of the row
double start_base = middle – (base_width/2);

//getting to the bottom layer
double bottom = getHeight();

// cannot change the constant, so we’ll assign another variable for
// the columns, add 1 to get to the top
int blk_up = BRICKS_IN_BASE+1;

// the non static brick_base variable
int blck_side = BRICKS_IN_BASE;

// the first loop is for the column
for(int i=1;i<blk_up;i++){

// second loop is for the row
for(int j=0;j<blck_side;j++){

// y coordinate position for the bricks
double y = bottom -(i * BRICK_HEIGHT);

// x coordinate for the bricks
double x = start_base + (j * BRICK_WIDTH);

//draws the bricks
GRect myrect = new GRect(x,y,BRICK_WIDTH,BRICK_HEIGHT);
add(myrect);
}
// subtract 1 brick from the row
blck_side -=1;

// get a new base width
base_width = blck_side *BRICK_WIDTH;

//get the new position for the start of the new row
start_base = middle – (base_width/2);
}
// subtract 1 from the column
// I don’t think this is necessary
//blk_up-=1;
}
}

[/code]