Java Applet Grid Game Flashing On Refresh/Keypress - java

I made a simple game on a grid in java that involves controlling a white square with the WASD keys. Whenever I press W,S,A, or D, the screen sometimes flickers before drawing the grid again. I am fairly new to coding, so the more you can dumb it down for me, the better.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/**
* DotGame.applet
*
* A simple game where the player controls a white circle with the WASD keys.
* - If the user moves his circle over a green circle, his score will go up by 1, and another red circle will spawn.
* - If the user moves his circle over a red circle, his score will go down by 1, and one less red circle will be generated.
* - There is no win condition, it is just a test game.
*
* #author -----------
* #version 11-9-2014
*/
public class DotGame extends Applet
implements KeyListener, MouseListener
{
int width,height;
int powerup = 1;
int click = 0;
int x,y;
final int size = 40;
int ox = size,oy = size;
int rx = 0, ry = 0;
int reddots = 0;
int red[][] = new int[1000][2];
String s = "";
int score = 0;
int DrawGrid = 0;
String sc = "";
int powerupdots = 1;
int yellow[][] = new int[1][2];
int powerupcounter = 0;
int shield = 0;
int blue[][] = new int[1][2];
public void init()
{
this.setSize(740,500);
width = 640;
height = 480;
setBackground( Color.black );
x = width/2;
y = height/2;
s = "CLICK TO START";
addMouseListener( this );
addKeyListener( this );
}
public void keyPressed( KeyEvent e ) { }
public void keyReleased ( KeyEvent e ) { }
public void keyTyped( KeyEvent e )
{
char c = e.getKeyChar();
String t = c+"";
//This will change the coordinates of the user-controlled circle by the size of the circle based on what button is pressed
if(powerupcounter > 0)
{
powerup = 2;
}
else if(powerupcounter == 0)
{
powerup = 1;
}
if( t.equalsIgnoreCase("w" )&& oy > 0+((powerup-1)*size))
{
oy = oy-(size*powerup);
}
else if( t.equalsIgnoreCase("s") && oy < height-(size*powerup))
{
oy = oy+(size*powerup);
}
else if( t.equalsIgnoreCase("a")&& ox > 0+((powerup-1)*size))
{
ox = ox-(size*powerup);
}
else if( t.equalsIgnoreCase("d") && ox < width-(size*powerup))
{
ox = ox+(size*powerup);
}
else if(t.equalsIgnoreCase("w" ) && oy == 0)
{
oy = height-(size*powerup);
}
else if(t.equalsIgnoreCase("s") && oy == height-size)
{
oy = 0+((powerup-1)*size);
}
else if(t.equalsIgnoreCase("a") && ox == 0)
{
ox = width-(size*powerup);
}
else if(t.equalsIgnoreCase("d") && ox == width-size)
{
ox = 0+((powerup-1)*size);
}
else if(t.equalsIgnoreCase("w") && oy == size && powerup ==2)
{
oy = height-size;
}
else if(t.equalsIgnoreCase("s") && oy == height -(size*powerup) && powerup ==2)
{
oy = 0;
}
else if(t.equalsIgnoreCase("a") && ox == size && powerup ==2)
{
ox = width-size;
}
else if(t.equalsIgnoreCase("d") && ox == width -(size*powerup) && powerup ==2)
{
ox = 0;
}
if(powerupcounter > 0)
{
powerupcounter--;
}
repaint();
e.consume();
}
public void mouseEntered( MouseEvent e) {}
public void mouseExited( MouseEvent e) {}
public void mousePressed( MouseEvent e) {}
public void mouseReleased( MouseEvent e) {}
public void mouseClicked( MouseEvent e)
{
if(click == 0)
{
randomYellow();
randomBlue();
DrawRandom();
x = e.getX();
y = e.getY();
s = "";
repaint();
e.consume();
click = 1;
}
}
public void CheckScore()
{
if(ox == rx && oy == ry)
{
score++;
reddots+=10;
DrawRandom();
}
}
public void DrawRandom()
{
//The reason we divide by the size and then multiply after it is an int is to
//make sure that the random circle drawn is in the same base as the size of the circle,
//so that the player's circle can move directly over it, and not be of by a fraction
//of the predetermined size.
rx = (int)(Math.random()*width/size)*size;
ry = (int)(Math.random()*height/size)*size;
while(rx == ox && ry == oy)
{
rx = (int)(Math.random()*width/size)*size;
ry = (int)(Math.random()*height/size)*size;
}
for(int y = 0 ; y < reddots ; y++)
{
red[y][0] = (int)(Math.random()*width/size)*size;
red[y][1] = (int)(Math.random()*height/size)*size;
while(red[y][0] == rx && red[y][1] == ry || red[y][0] == yellow[0][0] && red[y][1] == yellow[0][1]
|| red[y][0] == ox && red[y][1] == oy || red[y][0] == blue[0][0] && red[y][1] == blue[0][1])
{
red[y][0] = (int)(Math.random()*width/size)*size;
red[y][1] = (int)(Math.random()*height/size)*size;
}
}
}
public void randomYellow()
{
yellow[0][0] = (int)(Math.random()*width/size)*size;
yellow[0][1] = (int)(Math.random()*height/size)*size;
while(yellow[0][0] == rx && yellow[0][1] == ry)
{
yellow[0][0] = (int)(Math.random()*width/size)*size;
yellow[0][1] = (int)(Math.random()*height/size)*size;
}
}
public void randomBlue()
{
blue[0][0] = (int)(Math.random()*width/size)*size;
blue[0][1] = (int)(Math.random()*height/size)*size;
while(blue[0][0] == rx && blue[0][1] == ry || blue[0][0] == yellow[0][0] && blue[0][1] == yellow[0][1])
{
blue[0][0] = (int)(Math.random()*width/size)*size;
blue[0][1] = (int)(Math.random()*height/size)*size;
}
}
public void CheckDeath()
{
for(int y = 0 ; y < reddots ; y++)
{
if(ox == red[y][0] && oy == red[y][1] && shield == 0)
{
score--;
reddots--;
DrawRandom();
}
else if(ox == red[y][0] && oy == red[y][1] && shield !=0)
{
shield--;
DrawRandom();
}
}
}
public void CheckPowerup()
{
for(int y = 0 ; y < powerupdots ; y++)
{
if(ox == yellow[y][0] && oy == yellow[y][1])
{
powerupcounter += 10;
randomYellow();
}
}
}
public void CheckShield()
{
if(ox == blue[0][0] && oy == blue[0][1] && shield < 5)
{
shield++;
randomBlue();
}
else if(ox == blue[0][0] && oy == blue[0][1] && shield >= 5)
{
randomBlue();
}
}
public void CheckWin( Graphics g )
{
g.setColor(Color.black);
g.fillRect(0,0,width,height);
while(1 == 1)
{
g.drawString( "YOU WIN" , width/2, height/2);
}
}
public void paint( Graphics g )
{
CheckScore();
if(score == 20)
{
CheckWin(g);
}
CheckDeath();
CheckPowerup();
CheckShield();
DrawGrid(g);
g.setColor(Color.yellow);
g.fillRect(yellow[0][0],yellow[0][1],size+1,size+1);
g.setColor(Color.red);
for(int y = 0; y < reddots ; y++)
{
g.fillRect(red[y][0],red[y][1],size+1,size+1);
}
sc = ""+score;
//Draw user
g.setColor(Color.white);
g.fillRect(ox,oy,size+1,size+1);
//Draw shield around user if they have shields (max 5)
if(shield >= 1)
{
g.setColor(Color.blue);
g.fillRect(ox,oy,size+1,5);
g.fillRect(ox,oy,5,size+1);
g.fillRect(ox,oy+size-4,size+1,5);
g.fillRect(ox+size-4,oy,5,size+1);
}
//Draw green tile
g.setColor(Color.green);
g.fillRect(rx,ry,size+1,size+1);
//Draw shield tile
g.setColor(Color.blue);
g.fillRect(blue[0][0],blue[0][1],size+1,size+1);
g.setColor( Color.green );
g.drawString( s, x, y );
g.drawString( "Score : "+sc, 650, 20);
g.drawString( "Powerups : "+powerupcounter, 650, 40);
g.drawString( "Red Dots : "+reddots, 650,60);
g.drawString( "Shield : "+shield,650,80);
}
public void DrawGrid( Graphics g )
{
g.setColor(Color.orange);
for(int x = 0 ; x <= width ; x += size)
{
g.drawLine(x,0,x,height);
}
for(int y = 0 ; y <= height ; y+= size)
{
g.drawLine(0,y,width,y);
}
}
}

My advice is to move as much of your calculation as possible into methods called from your keypress events, and keep your paint() method as short and direct as possible. Don't do math inside your paint() method if you can help it - use your keypress method to build the picture of everything you need to paint before you call repaint(), and make your paint() method's only job to be to draw the current state of the board. Also, don't redraw the whole board anytime you don't have to. For instance, when moving from the current square to an empty square, all you should draw is a black square over your previous position, and a new user square in the new position. When hitting a yellow or blue square, all you need to draw is the new yellow or blue square (and update the appropriate status messages). You only need to redraw the whole board when hitting a red or green square.

Related

Intersect function stops working after the first intersect

im making a game, but i ran into a problem while working with the function "intersect".
the senario looks like this; i've made a game where the player is a rectangle were the objective is to kill the enemy rectangle. The enemy "boss" rectangle has two "simulations" that simulate a movement and an attack these simulations are driven by vectors. The movement is horizantally back and forth and the attack is in a vertical maner, a charge type of deal. The boss also has a rectangular target area where if itersected the "boss" will charge across the screen.
now the problem comes when i tried to make it so that if the player intersects with the rectangular target area the "boss" will attack/charge. The boss attack/charge the first time the player intersects but not after that. I want the boss to follow the same pantern, is that he should only be able to go from side to side horizantaly and if Target area intersected; attack/charge verticaly.
( i will include some code bellow. sorry if my english is bad. )
first comes the main:
boss b;
Character C;
void setup(){
C = new Character();
b = new boss();
}
void draw(){
if (play) {
b.simulate(); //horizantal movement
}
if (b.start) {
b.sim(); //boss vertical attack
}
if (b.intersects(C)){
play = false;
b.start = true;
}
C.character(); //player
b.bounce(); //makes it bounce if horizantal. and stop if vertical
b.Display(); //boss
b.display(); //boss target area
}
Next comes the boss:
class boss {
int x = 10 ;
int y = 10 ;
boolean start = false;
int RW = 50;
int RH = 700;
boolean up = false;
boolean down = true;
boss() {
Location = new PVector( x+25, y ); //vector for the location of the boss
Velocity = new PVector( 5, 0 ); // vector for horizaltal movement
speed = new PVector( 0, 10 ); // vector for vertical down movement
speed2 = new PVector(0, -10); // vector for vertical up movement
}
void bounce() {
if ((Location.x == width) ||(Location.x == 0)) { //horizantal movement bounce on screen edge
Velocity.x = Velocity.x * -1;
}
if ((Location.y == 650) || (Location.y == 0)) {
start = false; //makes boss stop if reaches botton or top of the screen
play = true;
if (Location.y == 650) {
RH = -700;
up = true;
down = false; //specificly if it reaches top of screen
}
if (Location.y == 0) {
RH = 700;
down = true; //specificly if it reaches bottom of screen
up = false;
}
}
}
void simulate() {
Location.add(Velocity); //simulates horizantal movement
}
void sim() {
if (down) {
Location.add(speed); //simulates up and down attacking movemnet
}
if (up) {
Location.add(speed2);
}
}
boolean intersects(Character C) {
return Location.x < C.x + C.w && C.x < Location.x + RW &&
Location.y < C.y + C.h && C.y < Location.y + RH; //intersect between player and boss targeting area
}
void Display() {
rect( Location.x, Location.y, 50, 50 ); //boss
}
void display() {
rect( Location.x, Location.y+50, RW, RH ); //boss targeting area
}
}
if anything is unclear i will gladly clear up any confusion. :)
Thanks for sharing the code. It made it much easier.
When I comment this piece (not the if-condition the reset of start after the if)
if ((Location.y == 650) || (Location.y == 0)) {
// start = false;
then the boss starts going back up top and still calls intersects the Character when the co-ordinates match. However, post this the boss keeps bouncing up and down.
There is surely more work to be done on this to take account of the bullets fired and the hits to boss.
Hope this helps. :) It was fun debugging this code. I had never used PDE before this.
ok, here is the "edit"..
Now,
Good News: I can make it go in both directions only when it intersects
Bad News: It keeps going to the other side as long as it is intersecting. So if the Character is stationary then boss keeps intersecting and passing to the other side at least 8-10 times in the current speed.
Anyways, here is the summary. I added and isAttacking flag that tells the program to not stop the boss from crossing over if it has reached the bottom of the frame. The other thing I changed was the intersection condition. Now it just checks for intersection on the X-Axis. If you must compare intersection on the Y-Axis too then intersects is where you need to change & test.
After the long explanation :P Here is the code. Hope this is better.
Main
boss b;
Character C;
Inventory I;
Bullet B;
int previousKey = 0;
int lastKey;
int lastKeyCode;
void setup() {
C = new Character();
b = new boss();
I = new Inventory();
background(128, 128, 128);
size( 700, 700 );
strokeWeight( 10 );
frameRate( 30 );
}
void keyPressed() {
if (key == CODED) {
previousKey = keyCode;
if (keyCode == UP) {
C.MoveUP();
}
if (keyCode == LEFT) {
C.MoveLEFT();
}
if (keyCode == DOWN) {
C.MoveDOWN();
}
if (keyCode == RIGHT) {
C.MoveRIGHT();
}
}
if (key == 'w' || key == 'W') {
attack();
}
if ( key == 'q' || key == 'Q' ) {
if (I.Shoot == true) {
B = new Bullet(C.x, C.y);
this.Shoot();
}
} else if (key == 'e' || key == 'E') {
I.changePop();
}
if (keyPressed) {
if (key == 'a' || key == 'A') {
//play = false;
//b.start = true;
}
}
}
void attack() {
if (I.Attack == true) {
if (previousKey == UP) {
C.AttackUP();
}
if (previousKey == LEFT) {
C.AttackLEFT();
}
if (previousKey == DOWN) {
C.AttackDOWN();
}
if (previousKey == RIGHT) {
C.AttackRIGHT();
}
}
}
void Shoot() {
if (I.Shoot == true) {
if (previousKey == UP) {
B.ShootUP();
}
if (previousKey == LEFT) {
B.ShootLEFT();
}
if (previousKey == DOWN) {
B.ShootDOWN();
}
if (previousKey == RIGHT) {
B.ShootRIGHT();
}
}
}
boolean play = true;
void keyReleased() {
lastKey = 0;
lastKeyCode = 0;
}
void draw() {
background(128, 128, 128);
if (play) {
b.simulate();//side to side
}
if (b.start) {
b.sim(); //boss rush
}
if (b.intersects(C)) {
b.isAttacking = true;
play = false;
b.start = true;
} else {
b.isAttacking= false;
}
C.character();
b.bounce();
b.Display();//boss
b.display();//rush area
C.HPbar();
I.popUp();
if ( key == 'q' || key == 'Q' ) {
if (I.Shoot == true) {
B.bullet();
B.Simulate();
}
}
}
Enemies or Boss
class boss {
PVector Location;
PVector Velocity;
PVector speed;
PVector speed2;
int x = 10 ;
int y = 10 ;
boolean start = false;
int RW = 50;
int RH = 700;
boolean up = false;
boolean down = true;
boolean isAttacking = false;
boss() {
Location = new PVector( x+25, y );
Velocity = new PVector( 5, 0 );
speed = new PVector( 0, 10 );
speed2 = new PVector(0, -10);
}
void bounce() {
if ((Location.x == width) ||(Location.x == 0)) {
Velocity.x = Velocity.x * -1;
}
if ((Location.y == 650) || (Location.y == 0)) {
if (!isAttacking) {
start = false;
}
play = true;
if (Location.y == 650) {
RH = -700;
up = true;
down = false;
}
if (Location.y == 0) {
RH = 700;
down = true;
up = false;
}
}
}
void simulate() {
Location.add(Velocity);
}
void sim() {
//print("\n In Sim UP: [" + up + "] Down: [" + down + "] Location [" + Location + "]");
if (down) {
Location.add(speed);
}
if (up) {
Location.add(speed2);
}
}
boolean intersects(Character C) {
//print ("\nUP: [" + up + "] Down: [" + down + "] X: [" + (Location.x < (C.x + C.w) && (Location.x + RW) > C.x)
//+ "] Y: [" + (Location.y < (C.y + C.h) && (Location.y + RH) > C.y) + "]");
return Location.x < (C.x + C.w) && (Location.x + RW) > C.x;
//&&
// Location.y < (C.y + C.h) && (Location.y + RH) > C.y ;
}
void Display() {
pushStyle();
stroke(0);
fill(255, 0, 0);
rect( Location.x, Location.y, 50, 50 );
popStyle();
}
void display() {
pushStyle();
stroke(0);
strokeWeight(0);
fill(255, 0, 0, 20);
rect( Location.x, Location.y+50, RW, RH );
popStyle();
}
}

Minesweeper draw number of nearby mines

I need to do a Minesweeper game. I have most of the methods down, but I cannot figure out a way to draw the number of mines around a given tile. I have a method that returns the number of mines around that tile, but no such method to actually display that number inside the tile in the game.
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Insets;
import java.net.URL;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class MyPanel extends JPanel {
private static final long serialVersionUID = 3426940946811133635L;
private static final int GRID_X = 25;
private static final int GRID_Y = 25;
private static final int INNER_CELL_SIZE = 29;
private static final int TOTAL_COLUMNS = 9;
private static final int TOTAL_ROWS = 10; //Last row has only one cell
public int x = -1;
public int y = -1;
public int mouseDownGridX = 0;
public int mouseDownGridY = 0;
private ImageIcon icon;
private static char minefield[][];
public Color[][] colorArray = new Color[TOTAL_COLUMNS][TOTAL_ROWS];
public MyPanel() { //This is the constructor... this code runs first to initialize
if (INNER_CELL_SIZE + (new Random()).nextInt(1) < 1) { //Use of "random" to prevent unwanted Eclipse warning
throw new RuntimeException("INNER_CELL_SIZE must be positive!");
}
if (TOTAL_COLUMNS + (new Random()).nextInt(1) < 2) { //Use of "random" to prevent unwanted Eclipse warning
throw new RuntimeException("TOTAL_COLUMNS must be at least 2!");
}
if (TOTAL_ROWS + (new Random()).nextInt(1) < 3) { //Use of "random" to prevent unwanted Eclipse warning
throw new RuntimeException("TOTAL_ROWS must be at least 3!");
}
for (int x = 0; x < TOTAL_COLUMNS; x++) { //Top row
colorArray[x][0] = Color.LIGHT_GRAY;
}
for (int y = 0; y < TOTAL_ROWS; y++) { //Left column
colorArray[0][y] = Color.LIGHT_GRAY;
}
for (int x = 1; x < TOTAL_COLUMNS; x++) { //The rest of the grid
for (int y = 1; y < TOTAL_ROWS; y++) {
colorArray[x][y] = Color.LIGHT_GRAY;
}
}
minefield = new char [TOTAL_COLUMNS][TOTAL_ROWS];
}
Random rando = new Random();
public static int mines = 10;
public int flags = 10;
public static int flagged = 0;
public void paintComponent(Graphics g) {
super.paintComponent(g);
//Compute interior coordinates
Insets myInsets = getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
int x2 = getWidth() - myInsets.right - 1;
int y2 = getHeight() - myInsets.bottom - 1;
int width = x2 - x1;
int height = y2 - y1;
//Paint the background
g.setColor(Color.LIGHT_GRAY);
g.fillRect(x1, y1, width + 1, height + 1);
//Draw the grid minus the bottom row (which has only one cell)
//By default, the grid will be 10x10 (see above: TOTAL_COLUMNS and TOTAL_ROWS)
g.setColor(Color.BLACK);
for (int y = 0; y <= TOTAL_ROWS - 1; y++) {
g.drawLine(x1 + GRID_X, y1 + GRID_Y + (y * (INNER_CELL_SIZE + 1)), x1 + GRID_X + ((INNER_CELL_SIZE + 1) * TOTAL_COLUMNS), y1 + GRID_Y + (y * (INNER_CELL_SIZE + 1)));
}
for (int x = 0; x <= TOTAL_COLUMNS; x++) {
g.drawLine(x1 + GRID_X + (x * (INNER_CELL_SIZE + 1)), y1 + GRID_Y, x1 + GRID_X + (x * (INNER_CELL_SIZE + 1)), y1 + GRID_Y + ((INNER_CELL_SIZE + 1) * (TOTAL_ROWS - 1)));
}
//Paint cell colors
for (int x = 0; x < TOTAL_COLUMNS; x++) {
for (int y = 0; y < TOTAL_ROWS; y++) {
if ((x == 0) || (y != TOTAL_ROWS - 1)) {
Color c = colorArray[x][y];
g.setColor(c);
g.fillRect(x1 + GRID_X + (x * (INNER_CELL_SIZE + 1)) + 1, y1 + GRID_Y + (y * (INNER_CELL_SIZE + 1)) + 1, INNER_CELL_SIZE, INNER_CELL_SIZE);
}
}
}
}
// Places the mines in the field
public void placeMines() {
int minesPlaced = 1;
while (minesPlaced <= mines) {
int x = rando.nextInt(TOTAL_COLUMNS);
int y = rando.nextInt(TOTAL_ROWS-1);
if (minefield[x][y] != '*') {
minefield[x][y] = '*';
minesPlaced++;
}
}
for (int i=0; i<9; i++) {
for (int j=0; j<9; j++) {
bombCheck(i, j);
if (bombCheck(i, j) == 1) {
System.out.println(i + "," + j); // for debugging purposes
}
}
}repaint();
}
//checks a tile, white if there were no mines
public void check (int x, int y) {
colorArray[x][y] = Color.WHITE ;
repaint();
}
// Checks whether this place in the field has a bomb (1) or not (0).
public int bombCheck(int x, int y) {
if (!(x == -1 || y == -1)) {
if (minefield[x][y] == '*') {
return 1;
}
else {
minefield[x][y] = 'c';
return 0;
}
}
else{
return 0;
}
}
// Checks for mines on the 8 other tiles around the target location and returns the number of mines there are.
public int minesAround(int x, int y) {
int mines = 0;
mines += bombCheck(x-1, y-1);
mines += bombCheck(x-1, y);
mines += bombCheck(x-1, y+1);
mines += bombCheck(x, y-1);
mines += bombCheck(x, y+1);
mines += bombCheck(x+1, y-1);
mines += bombCheck(x+1, y);
mines += bombCheck(x+1, y+1);
if (mines > 0) {
return mines;
}
else{
return 0;
}
}
//What I've come up with so far for drawing the number in the tile. Does not work.
public void draw (Graphics g, int n, int x, int y) {
super.paintComponent(g);
g.drawString("" + n + "", x, y);
}
//Recursive method
public void checkAround(int x, int y) {
int minx, miny, maxx, maxy;
check(x,y);
minx = (x <= 0 ? 0 : x - 1);
miny = (y <= 0 ? 0 : y - 1);
maxx = (x >= TOTAL_COLUMNS - 1 ? TOTAL_COLUMNS - 1 : x + 1);
maxy = (y >= TOTAL_ROWS - 2 ? TOTAL_ROWS - 2 : y + 1);
for (int i = minx; i < maxx; i ++) {
for (int j = miny; j <= maxy; j ++) {
if (bombCheck(i,j) == 0 && colorArray[i][j] != Color.WHITE) {
check(i,j);
if (minesAround(i,j) == 0) {
checkAround(i,j);
}
if (minesAround(i,j) == 1) {
draw(getGraphics(),1,i,j); // Does not work.
repaint();
}
}
}
}
}
//Flag
public int checkflag(int x, int y){
int status = 0;
if (!(x == -1 || y == -1)) {
if (colorArray[x][y] == Color.RED) {
status += 1;
}else {
status += 0;
}
}
return status;
}
//Resets field
public void reset() {
for (int i = 0; i < TOTAL_COLUMNS; i++) {
for (int j = 0 ;j < TOTAL_ROWS; j++) {
colorArray[i][j] = Color.LIGHT_GRAY;
minefield[i][j] = ' ';
MyMouseAdapter.f = 1;
repaint();
}
}
placeMines();
}
public int getGridX(int x, int y) {
Insets myInsets = getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
x = x - x1 - GRID_X;
y = y - y1 - GRID_Y;
if (x < 0) { //To the left of the grid
return -1;
}
if (y < 0) { //Above the grid
return -1;
}
if ((x % (INNER_CELL_SIZE + 1) == 0) || (y % (INNER_CELL_SIZE + 1) == 0)) { //Coordinate is at an edge; not inside a cell
return -1;
}
x = x / (INNER_CELL_SIZE + 1);
y = y / (INNER_CELL_SIZE + 1);
if (x == 0 && y == TOTAL_ROWS - 1) { //The lower left extra cell
return x;
}
if (x < 0 || x > TOTAL_COLUMNS - 1 || y < 0 || y > TOTAL_ROWS - 2) { //Outside the rest of the grid
return -1;
}
return x;
}
public int getGridY(int x, int y) {
Insets myInsets = getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
x = x - x1 - GRID_X;
y = y - y1 - GRID_Y;
if (x < 0) { //To the left of the grid
return -1;
}
if (y < 0) { //Above the grid
return -1;
}
if ((x % (INNER_CELL_SIZE + 1) == 0) || (y % (INNER_CELL_SIZE + 1) == 0)) { //Coordinate is at an edge; not inside a cell
return -1;
}
x = x / (INNER_CELL_SIZE + 1);
y = y / (INNER_CELL_SIZE + 1);
if (x == 0 && y == TOTAL_ROWS - 1) { //The lower left extra cell
return y;
}
if (x < 0 || x > TOTAL_COLUMNS - 1 || y < 0 || y > TOTAL_ROWS - 2) { //Outside the rest of the grid
return -1;
}
return y;
}
public ImageIcon getIcon() {
return icon;
}
public void setIcon(ImageIcon icon) {
this.icon = icon;
}
}
-
import java.awt.Color;
import java.awt.Component;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Random;
import javax.swing.JFrame;
public class MyMouseAdapter extends MouseAdapter {
public static int f = 1;
public void mousePressed(MouseEvent e) {
switch (e.getButton()) {
case 1: //Left mouse button
Component c = e.getComponent();
while (!(c instanceof JFrame)) {
c = c.getParent();
if (c == null) {
return;
}
}
JFrame myFrame = (JFrame) c;
MyPanel myPanel = (MyPanel) myFrame.getContentPane().getComponent(0);
Insets myInsets = myFrame.getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
e.translatePoint(-x1, -y1);
int x = e.getX();
int y = e.getY();
myPanel.x = x;
myPanel.y = y;
myPanel.mouseDownGridX = myPanel.getGridX(x, y);
myPanel.mouseDownGridY = myPanel.getGridY(x, y);
myPanel.repaint();
break;
case 3: //Right mouse button
Component c1 = e.getComponent();
while (!(c1 instanceof JFrame)) {
c = c1.getParent();
if (c == null) {
return;
}
}
JFrame myFrame1 = (JFrame)c1;
MyPanel myPanel1 = (MyPanel) myFrame1.getContentPane().getComponent(0); //Can also loop among components to find MyPanel
Insets myInsets1 = myFrame1.getInsets();
int x2 = myInsets1.left;
int y2 = myInsets1.top;
e.translatePoint(-x2, -y2);
int x3 = e.getX();
int y3 = e.getY();
myPanel1.x = x3;
myPanel1.y = y3;
myPanel1.mouseDownGridX = myPanel1.getGridX(x3, y3);
myPanel1.mouseDownGridY = myPanel1.getGridY(x3, y3);
break;
default: //Some other button (2 = Middle mouse button, etc.)
//Do nothing
break;
}
}
public void mouseReleased(MouseEvent e) {
switch (e.getButton()) {
case 1: //Left mouse button
Component c = e.getComponent();
while (!(c instanceof JFrame)) {
c = c.getParent();
if (c == null) {
return;
}
}
JFrame myFrame = (JFrame)c;
MyPanel myPanel = (MyPanel) myFrame.getContentPane().getComponent(0); //Can also loop among components to find MyPanel
Insets myInsets = myFrame.getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
e.translatePoint(-x1, -y1);
int x = e.getX();
int y = e.getY();
myPanel.x = x;
myPanel.y = y;
int gridX = myPanel.getGridX(x, y);
int gridY = myPanel.getGridY(x, y);
if ((myPanel.mouseDownGridX == -1) || (myPanel.mouseDownGridY == -1)) {
//Had pressed outside
//Do nothing
} else {
if ((gridX == -1) || (gridY == -1)) {
//Do nothing
}else if (gridX == 0 && gridY == 9) {
myPanel.reset();
} else {
if ((myPanel.mouseDownGridX != gridX) || (myPanel.mouseDownGridY != gridY)) {
//Released the mouse button on a different cell where it was pressed
//Do nothing
} else {
//Released the mouse button on the same cell where it was pressed
if (!(myPanel.mouseDownGridX == -1) || (myPanel.mouseDownGridY == -1)) {
if (!(myPanel.colorArray[gridX][gridY] == Color.RED)) {
if (myPanel.bombCheck(gridX, gridY) == 0) {
myPanel.checkAround(gridX, gridY);
}
else{
myPanel.colorArray[gridX][gridY] = Color.BLACK ;
System.out.println("You've Lost!");
myPanel.reset();
myPanel.repaint();
}
}
}
}
}
}
myPanel.repaint();
break;
case 3: //Right mouse button
Component c1 = e.getComponent();
while (!(c1 instanceof JFrame)) {
c = c1.getParent();
if (c == null) {
return;
}
}
JFrame myFrame1 = (JFrame)c1;
MyPanel myPanel1 = (MyPanel) myFrame1.getContentPane().getComponent(0); //Can also loop among components to find MyPanel
Insets myInsets1 = myFrame1.getInsets();
int x2 = myInsets1.left;
int y2 = myInsets1.top;
e.translatePoint(-x2, -y2);
int x3 = e.getX();
int y3 = e.getY();
myPanel1.x = x3;
myPanel1.y = y3;
int gridX1 = myPanel1.getGridX(x3, y3);
int gridY1 = myPanel1.getGridY(x3, y3);
int flags = 10;
if ((myPanel1.mouseDownGridX == -1) || (myPanel1.mouseDownGridY == -1)) {
//Had pressed outside
//Do nothing
} else {
if ((gridX1 == -1) || (gridY1 == -1)) {
//Is releasing outside
//Do nothing
} else {
if ((myPanel1.mouseDownGridX != gridX1) || (myPanel1.mouseDownGridY != gridY1)) {
}else{
if (!(myPanel1.colorArray[gridX1][gridY1] == Color.WHITE)) {
if (myPanel1.checkflag(gridX1, gridY1) == 0) {
if (!(f > flags)) {
if (myPanel1.bombCheck(gridX1, gridY1) == 1) {
MyPanel.flagged ++;
if (MyPanel.flagged == 10) {
System.out.println("You've Won! Congratulations!");
myPanel1.reset();
myPanel1.colorArray[gridX1][gridY1] = Color.LIGHT_GRAY ;
myPanel1.repaint();
}
}
myPanel1.colorArray[gridX1][gridY1] = Color.RED ;
myPanel1.repaint();
f ++;
}
}
else {
myPanel1.colorArray[gridX1][gridY1] = Color.LIGHT_GRAY ;
myPanel1.repaint();
f --;
}
}
}
}
}
break;
default: //Some other button (2 = Middle mouse button, etc.)
//Do nothing
break;
}
}
}
-
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame myFrame = new JFrame("Color Grid");
myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
myFrame.setLocation(400, 150);
myFrame.setSize(400, 400);
MyPanel myPanel = new MyPanel();
myFrame.add(myPanel);
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
myFrame.addMouseListener(myMouseAdapter);
myFrame.setVisible(true);
myPanel.placeMines();
}
}
This is only my first year studying Computer science, but if my intuition is correct, my draw method is drawing the number behind the tiles. These are just my thoughts, I have relatively little to no experience with Java.
In your paintComponent() add something like this:
Font f = new Font("Dialog", Font.PLAIN, 12); // choose a font for the numbers
g.setFont(f);
// Draw cell numbers
for (int x = 0; x < TOTAL_COLUMNS; x++) {
for (int y = 0; y < TOTAL_ROWS; y++) {
if (/* check if the (x,y) cell is uncovered */) {
int around = minesAround(x, y);
g.drawString(String.valueOf(around), /*cell x coord*/, /*cell y coord*/);
}
}
}
Alternatively, you can use an image for each cell number instead of using a string.

Intersection of Rectangles for Java (Freeze Tag)

**Edited still not getting the right response **
I am not quite understanding how to figure out the intersection aspect of my project. So far I have determined the top, bottom, left and right but I am not sure where to go from there.
The main driver should call to check if my moving rectangles are intersecting and if the rectangle is froze the moving one intersecting with it should unfreeze it and change its color. I understand how to unfreeze it and change the color but for whatever the reason it isn't returning the value as true when they are intersecting and I know this code is wrong. Any helpful tips are appreciated.
*CLASS CODE*
import edu.princeton.cs.introcs.StdDraw;
import java.util.Random;
import java.awt.Color;
public class MovingRectangle {
Random rnd = new Random();
private int xCoord;
private int yCoord;
private int width;
private int height;
private int xVelocity;
private int yVelocity;
private Color color;
private boolean frozen;
private int canvas;
public MovingRectangle(int x, int y, int w, int h, int xv, int yv, int canvasSize) {
canvas = canvasSize;
xCoord = x;
yCoord = y;
width = w;
height = h;
xVelocity = xv;
yVelocity = yv;
frozen = false;
int c = rnd.nextInt(5);
if (c == 0) {
color = StdDraw.MAGENTA;
}
if (c == 1) {
color = StdDraw.BLUE;
}
if (c == 2) {
color = StdDraw.CYAN;
}
if (c == 3) {
color = StdDraw.ORANGE;
}
if (c == 4) {
color = StdDraw.GREEN;
}
}
public void draw() {
StdDraw.setPenColor(color);
StdDraw.filledRectangle(xCoord, yCoord, width, height);
}
public void move() {
if (frozen == false) {
xCoord = xCoord + xVelocity;
yCoord = yCoord + yVelocity;
}
else {
xCoord +=0;
yCoord +=0;
}
if (xCoord >= canvas || xCoord < 0) {
xVelocity *= -1;
this.setRandomColor();
}
if (yCoord >= canvas || yCoord < 0) {
yVelocity *= -1;
this.setRandomColor();
}
}
public void setColor(Color c) {
StdDraw.setPenColor(color);
}
public void setRandomColor() {
int c = rnd.nextInt(5);
if (c == 0) {
color = StdDraw.MAGENTA;
}
if (c == 1) {
color = StdDraw.BLUE;
}
if (c == 2) {
color = StdDraw.CYAN;
}
if (c == 3) {
color = StdDraw.ORANGE;
}
if (c == 4) {
color = StdDraw.GREEN;
}
}
public boolean containsPoint(double x, double y) {
int bottom = yCoord - height / 2;
int top = yCoord + height / 2;
int left = xCoord - width / 2;
int right = xCoord + width / 2;
if (x > left && x < right && y > bottom && y < top) {
color = StdDraw.RED;
return true;
} else {
return false;
}
}
public boolean isFrozen() {
if (frozen) {
return true;
} else {
return false;
}
}
public void setFrozen(boolean val) {
frozen = val;
}
public boolean isIntersecting(MovingRectangle r) {
int top = xCoord + height/2;
int bottom = xCoord - height/2;
int right = yCoord + width/2;
int left = yCoord - width/2;
int rTop = r.xCoord + r.height/2;
int rBottom = r.xCoord - r.height/2;
int rRight = r.yCoord + r.width/2;
int rLeft = r.yCoord - r.width/2;
if(right <= rRight && right >= rLeft || bottom <= rBottom && bottom
>= rTop){
return true;
} else {
return false;
}
}
}
Here is my main driver as well, because I might be doing something wrong here too.
import edu.princeton.cs.introcs.StdDraw;
import java.util.Random;
public class FreezeTagDriver {
public static final int CANVAS_SIZE = 800;
public static void main(String[] args) {
StdDraw.setCanvasSize(CANVAS_SIZE, CANVAS_SIZE);
StdDraw.setXscale(0, CANVAS_SIZE);
StdDraw.setYscale(0, CANVAS_SIZE);
Random rnd = new Random();
MovingRectangle[] recs;
recs = new MovingRectangle[5];
boolean frozen = false;
for (int i = 0; i < recs.length; i++) {
int xv = rnd.nextInt(4);
int yv = rnd.nextInt(4);
int x = rnd.nextInt(400);
int y = rnd.nextInt(400);
int h = rnd.nextInt(100) + 10;
int w = rnd.nextInt(100) + 10;
recs[i] = new MovingRectangle(x, y, w, h, xv, yv, CANVAS_SIZE);
}
while (true) {
StdDraw.clear();
for (int i = 0; i < recs.length; i++) {
recs[i].draw();
recs[i].move();
}
if (StdDraw.mousePressed()) {
for (int i = 0; i < recs.length; i++) {
double x = StdDraw.mouseX();
double y = StdDraw.mouseY();
if (recs[i].containsPoint(x, y)) {
recs[i].setFrozen(true);
}
}
}
for (int i = 0; i < recs.length; i++) {
//for 0
if(recs[0].isFrozen() && recs[0].isIntersecting(recs[1])){
recs[0].setFrozen(false);
}
if(recs[0].isFrozen() && recs[0].isIntersecting(recs[2])){
recs[0].setFrozen(false);
}
if(recs[0].isFrozen() && recs[0].isIntersecting(recs[3])){
recs[0].setFrozen(false);
}
//for 1
if(recs[1].isFrozen() && recs[1].isIntersecting(recs[2])){
recs[1].setFrozen(false);
}
if(recs[1].isFrozen() && recs[1].isIntersecting(recs[3])){
recs[1].setFrozen(false);
}
if(recs[1].isFrozen() && recs[1].isIntersecting(recs[4])){
recs[1].setFrozen(false);
}
//for 2
if(recs[2].isFrozen() && recs[2].isIntersecting(recs[0])){
recs[2].setFrozen(false);
}
if(recs[2].isFrozen() && recs[2].isIntersecting(recs[1])){
recs[2].setFrozen(false);
}
if(recs[2].isFrozen() && recs[2].isIntersecting(recs[3])){
recs[2].setFrozen(false);
}
if(recs[2].isFrozen() && recs[2].isIntersecting(recs[4])){
recs[2].setFrozen(false);
}
//for 3
if(recs[3].isFrozen() && recs[3].isIntersecting(recs[0])){
recs[3].setFrozen(false);
}
if(recs[3].isFrozen() && recs[3].isIntersecting(recs[1])){
recs[3].setFrozen(false);
}
if(recs[3].isFrozen() && recs[3].isIntersecting(recs[2])){
recs[3].setFrozen(false);
}
if(recs[3].isFrozen() && recs[3].isIntersecting(recs[4])){
recs[3].setFrozen(false);
}
//for 4
if(recs[4].isFrozen() && recs[4].isIntersecting(recs[0])){
recs[4].setFrozen(false);
}
if(recs[4].isFrozen() && recs[4].isIntersecting(recs[1])){
recs[4].setFrozen(false);
}
if(recs[4].isFrozen() && recs[4].isIntersecting(recs[3])){
recs[4].setFrozen(false);
}
if(recs[4].isFrozen() && recs[4].isIntersecting(recs[2]))
recs[4].setFrozen(false);
}
if (recs[0].isFrozen() && recs[1].isFrozen() &&
recs[2].isFrozen() && recs[3].isFrozen()
&& recs[4].isFrozen()) {
StdDraw.text(400, 400, "YOU WIN");
}
StdDraw.show(20);
}
}
}
Keep in mind you're using the OR operator here. So if right is less than rLeft, your intersector will return true. This isn't how it should work.
You need to check if right is INSIDE the rectangles bounds so to speak.
if(right <= rRight && right >= rLeft || the other checks here)
The above code checks if right is less than the rectangle's right, but also that the right is bigger than rectangle's left, which means it's somewhere in middle of the rectangle's left and right.
If this becomes too complicated you can simply use java's rectangle class, as it has the methods contains and intersects

Ball going through paddle when increasing velocity

I am trying to create a Pong game and so far I have everything working for me other than the ball. At first I had the ball's x and y axis move up by one space each time. It was working fine until i decided to increase it to 2. I cant figure out what is wrong with my code and I need help.
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Pong extends JPanel implements KeyListener{
int x = 90;
int y = 90;
int rectytop = 30;
int rectytop2 = 30;
int rectybottom = rectytop + 100;
int rectybottom2 = rectytop2 + 100;
int border = 30;
boolean balldown = true;
boolean ballright = true;
boolean playerborderup = false;
boolean playerborderdown = false;
boolean balltouch1 = false;
boolean balltouch2 = false;
private void moveball() {
if (balldown == true){
y = y + 2;
}
if (y == getHeight()-border){
balldown = false;
}
if (balldown == false){
y = y - 2;
}
if (ballright == true){
x = x + 2;
}
if (x == getWidth()-border){
ballright = false;
}
if (ballright == false){
x = x - 2;
}
if (y == 0){
balldown = true;
}
if (x == 0){
ballright = true;
}
if (balltouch1 == false){
if (x == 75){
if(y < rectybottom && y > rectytop){
ballright = true;
}
}
}
if (balltouch2 == false){
if (x == 390 && y < rectybottom2 && y > rectytop2){
ballright = false;
}
}
}
#Override
public void paint(Graphics g){
super.paint(g);
//drawing ball and paddles
g.fillOval(x, y, 30, 30);
g.fillRect(45 , rectytop, 30, 100);
g.fillRect(425, rectytop2, 30, 100);
}
public static void main(String[] args) throws InterruptedException {
//making the window
JFrame f = new JFrame("Pong Game");
Pong game = new Pong();
f.setVisible(true);
f.setSize(500, 500);//1024, 724
f.setResizable(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.addKeyListener(game);
//game code
f.add(game);
while (true){
game.repaint();
game.moveball();
Thread.sleep(10);
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
//player one
if (e.getKeyCode() == KeyEvent.VK_W){
if (rectytop == 0){
playerborderup = true;
}
if (rectytop != 0){
playerborderup = false;
}
if (playerborderup == true){
rectytop = rectytop + 0;
rectybottom = rectytop + 100;
repaint();
}
if (playerborderup == false){
rectytop = rectytop - 5;
rectybottom = rectytop + 100;
repaint();
}
}
if (e.getKeyCode() == KeyEvent.VK_S){
if (rectytop == 585){
playerborderdown = true;
}
if (rectytop != 585){
playerborderdown = false;
}
if (playerborderdown == true){
rectytop = rectytop - 0;
rectybottom = rectytop + 100;
repaint();
}
if (playerborderdown == false){
rectytop = rectytop + 5;
rectybottom = rectytop + 100;
repaint();
}
}
//player two
if (e.getKeyCode() == KeyEvent.VK_UP){
if (rectytop2 == 0){
playerborderup = true;
}
if (rectytop2 != 0){
playerborderup = false;
}
if (playerborderup == true){
rectytop2 = rectytop2 + 0;
rectybottom2 = rectytop2 + 100;
repaint();
}
if (playerborderup == false){
rectytop2 = rectytop2 - 5;
rectybottom2 = rectytop2 + 100;
repaint();
}
}
if (e.getKeyCode() == KeyEvent.VK_DOWN){
if (rectytop2 == 585){
playerborderdown = true;
}
if (rectytop2 != 585){
playerborderdown = false;
}
if (playerborderdown == true){
rectytop2 = rectytop2 - 0;
rectybottom2 = rectytop2 + 100;
repaint();
}
if (playerborderdown == false){
rectytop2 = rectytop2 + 5;
rectybottom2 = rectytop2 + 100;
repaint();
}
}
}
#Override
public void keyReleased(KeyEvent e) {
}
}
Since you are moving by 2 every time, it may "skip" over some coordinates. Thus when you say
if (y == getHeight()-border){
balldown = false;
}
y might go from getHeight()-border + 1 to getHeight()-border - 1 and never meet this condition. Thus, change it to a range or a less than. Your new code should be
if (y <= getHeight()-border +1){
balldown = false; //change the +1 and -1 to have difference at least speed number
}
Note that you must do the same for the other ifs with ==, change
if (x == getWidth()-border){
ballright = false;
}
if (y == 0){
balldown = true;
}
if (x == 0){
ballright = true;
}
to
if (x <= getWidth()-border +1){
ballright = false;
}
if (y <= 1){
balldown = true;
}
if (x <= 1){
ballright = true;
}
Note that you can resolve the problem also by saying if the position is eer exactly one away from the border, temporarily decrement position by 1 instead of 2.
You are using if (x == 75) to detect collision with the left paddle. But if speed is 2 than the ball's x is always even and never equals 75. For a quick fix, check x against a range: if (x > 60 && x < 75)

How to create Breakout Game in Java

This question have been asked before. I have seen the answers but not quite works for me. I am creating a Breakout game. I have already created the ball, the paddle and the bricks. I have implemented how to make the ball bounce of the walls and first row of bricks.
I cannot figure out how to make the bricks disappear after they are hit by the ball. I am trying to store the bricks in an array, so I could just remove it from the array, when it is hit by the ball. Help is much appreciated.
Here is the code I have so far.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.io.*;
import sun.audio.*; //Used to play sounds
public class Breakout {
//Creating all the things we will need
public static JPanel display = new DisplayPanel();
public static JPanel controls = new JPanel();
public static JLabel scoreNum;
public static JLabel livesNum;
public static int xPos = 250, score = 0, lives = 3;
public static Boolean grabbed = false;
public static int cx, cy;
public static int bx, by, angle;
public static int[] bricks = new int[10];
public static Timer time = new Timer(20,new Ticker());
public static void main(String[] args)
{
Breakout bo = new Breakout();
}
public Breakout()
{
//This part should be quite familiar by now
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(650,550));
frame.setForeground(Color.black);
frame.setTitle("Breakout");
//Display panel data
display.setPreferredSize(new Dimension(500,550));
display.setBackground(Color.WHITE);
//Bricks
//Control components
JLabel title = new JLabel("BREAKOUT");
title.setHorizontalAlignment(SwingConstants.CENTER);
JLabel scoreLbl = new JLabel(" Score: ");
scoreNum = new JLabel(" "+score);
JLabel livesLbl = new JLabel(" Lives: ");
livesNum = new JLabel(" "+lives);
//Control panel data
controls.setPreferredSize(new Dimension(133,550)); //Not exact, to account for bordering
controls.setBackground(Color.LIGHT_GRAY);
controls.setLayout(new GridLayout(25,1)); //The no. of rows can control the button height
controls.add(title);
controls.add(scoreLbl);
controls.add(scoreNum);
controls.add(livesLbl);
controls.add(livesNum);
display.addMouseListener(new MouseSensor());
display.addMouseMotionListener(new MouseSensor());
frame.setLayout(new BorderLayout());
frame.add(controls,BorderLayout.WEST);
frame.add(display,BorderLayout.EAST);
frame.setVisible(true);
initBall();
beep();
time.start();
}
public static void initBall()
{
bx = 150 + (int)(Math.random() * (100));
by = 50 + (int)(Math.random() * (200));
angle = (int)(Math.random() * (2));
}
public static void beep()
{
//This program requires a sound file in the directory
//that you use for external files.
//You can use ANY sound that you give the name below,
//but the one I use is found here:
//http://www.soundjay.com/button/beep-2.wav
try {
AudioPlayer p = AudioPlayer.player;
AudioStream snd = new AudioStream(new FileInputStream("beep-2a.wav"));
p.start(snd); //This sequence is used to play sounds in JAVA
}
catch(IOException e) {}
}
public static class DisplayPanel extends JPanel
{
public void paintComponent (Graphics g)
{
int num_rows = 2;
int num_cols = 5;
int y_offset = 10;
int x_offset = 20;
int brick_height = 30;
int brick_width = 75;
int brick_sep = 20;
super.paintComponent(g);
g.setColor(Color.green);
for (int i = 0; i < num_rows; i++){
int y = y_offset + (i * (brick_height + brick_sep));
for (int j = 0; j < num_cols; j++){
int x = (x_offset) + (j * (brick_width + brick_sep));
g.fillRect (x, y, brick_width, brick_height );
}
}
if (grabbed)
g.setColor(Color.blue); //Highlight if active
else
g.setColor(Color.black);
g.fillRect(xPos-30,480,60,15); //Draw paddle at current location
if(lives > 0)
g.setColor(Color.red);
else
g.setColor(Color.white); //Ball is "invisible" if game over
g.fillOval(bx,by,14,14);
}
}
public static class MouseSensor extends MouseInputAdapter {
public MouseSensor() {}
public void mousePressed(MouseEvent e)
{
cx = e.getX();
cy = e.getY();
if ((cy > 470)&&(cy < 490)&&(cx > xPos-30)&&(cx < xPos+30))
grabbed = true; //If you click on the paddle, grab it!
display.repaint();
}
public void mouseReleased(MouseEvent e)
{
grabbed = false;
display.repaint();
}
public void mouseDragged(MouseEvent e)
{
cx = e.getX();
if (grabbed)
{
if (cx < 30)
cx = 30;
if (cx > 470)
cx = 470;
xPos = cx;
}
display.repaint(); //Move the grabbed paddle with the mouse
}
}
public static class Ticker implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
//Angle 0: upper right, Angle 1: upper left
//Angle 2: lower right, Angle 3: lower left
int d = 5; //Displacement: No. of pixels to move per tick of timer
if(angle == 0)
{ bx+=d; by-=d; } //Add to x, reduce y; moves upper right
else if (angle == 1)
{ bx-=d; by-=d; } //Reduce x, reduce y; moves upper left
else if (angle == 2)
{ bx+=d; by+=d; } //You get the idea
else if (angle == 3)
{ bx-=d; by+=d; } //Ditto
//Collision Detection
if (bx > 482) //Hitting the right wall
{
if (angle == 0) //If going upper-right...
angle = 1; //go upper-left after bouncing
else if (angle == 2) //If going lower-right...
angle = 3; //go lower-left after hitting right wall
}
else if (bx < 3) //Hitting left wall
{
if (angle == 1)
angle = 0;
else if (angle == 3)
angle = 2;
}
else if (by < 3) //Hitting top
{
if (angle == 0)
angle = 2;
else if (angle == 1)
angle = 3;
}
//Note; no detection at bottom, since that's how you lose
else if ((by > 460)&&(by < 480)) //Deflection height of paddle
{
if ((bx > (xPos-30))&&(bx < (xPos+30))) //Deflected by paddle
{
Toolkit.getDefaultToolkit().beep(); //Play sound
if (angle == 2)
angle = 0;
else if (angle == 3)
angle = 1;
score+= 10;//Modify this for your assignment (see notes)
scoreNum.setText(" "+score);
}
}
else if ((by < 90)&& (bx > 20) && (bx < 95))//Block 1
{
if (angle == 0)
angle = 2;
else if (angle == 1)
angle = 3;
}
else if ((by < 90)&& (bx > 115) && (bx < 190))//Block 2
{
if (angle == 0)
angle = 2;
else if (angle == 1)
angle = 3;
}
else if ((by < 90)&& (bx > 210) && (bx < 285))//Block 3
{
if (angle == 0)
angle = 2;
else if (angle == 1)
angle = 3;
}
else if ((by < 90)&& (bx > 305) && (bx < 380))//Block 4
{
if (angle == 0)
angle = 2;
else if (angle == 1)
angle = 3;
}
else if ((by < 90)&& (bx > 400) && (bx < 475))//Block 5
{
if (angle == 0)
angle = 2;
else if (angle == 1)
angle = 3;
}
else if (by > 530) //Missed; ball goes too low in y-value
{
lives--;
if (lives > 0)
{
livesNum.setText(" "+lives);
initBall();
}
else
{
time.stop();
livesNum.setText(" GAME OVER");
}
}
display.repaint();
}
}
}
here is the code where I created the bricks
g.setColor(Color.green);
for (int i = 0; i < num_rows; i++){
int y = y_offset + (i * (brick_height + brick_sep));
for (int j = 0; j < num_cols; j++){
int x = (x_offset) + (j * (brick_width + brick_sep));
g.fillRect (x, y, brick_width, brick_height );
}
What I want to do is disappear when i ball hits them, and for the ball to bounce off as well.
Here is the code from which the ball bounces of:
else if ((by < 90)&& (bx > 20) && (bx < 95))//Block 1
{
if (angle == 0)
angle = 2;
else if (angle == 1)
angle = 3;
}
else if ((by < 90)&& (bx > 115) && (bx < 190))//Block 2
{
if (angle == 0)
angle = 2;
else if (angle == 1)
angle = 3;
}
else if ((by < 90)&& (bx > 210) && (bx < 285))//Block 3
{
if (angle == 0)
angle = 2;
else if (angle == 1)
angle = 3;
}
else if ((by < 90)&& (bx > 305) && (bx < 380))//Block 4
{
if (angle == 0)
angle = 2;
else if (angle == 1)
angle = 3;
}
else if ((by < 90)&& (bx > 400) && (bx < 475))//Block 5
{
if (angle == 0)
angle = 2;
else if (angle == 1)
angle = 3;
}
I don't know how to make them disappear as they are hit by the ball.

Categories