my java applet on eclipe don't work it writes "applet intialized" but doesn't procced to "Applet started" and the applet doesn't start (just blank screen) and also there is no errors in the console window.
image: http://i.stack.imgur.com/pvalc.png
My code is about depth-first maze and the problem is in the genrate() function because when i comment it's call the program runs well
Maze.java :
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
public class Maze {
// Direction Variables
public static final int Direction_Up=1;
public static final int Direction_Down=2;
public static final int Direction_Right=3;
public static final int Direction_Left=4;
//
//
int width, height;
int SizeX,SizeY;
public int[] start={0,0},end={3,3};
int offset=2;
boolean[][] WallsVer = { { false,true, false ,false},
{ false,false, false ,false}, { false,false, false ,true}};
boolean[][] WallsHor ={ { true,false, false },
{ true,false, true }, { true,true, true }, { false,true, false}};
public Maze(int width, int height,int sizeX,int sizeY) {
// TODO Auto-generated constructor stub
this.width = width;
this.height = height;
SizeX = sizeX;
SizeY = sizeY;
}
//
public boolean CollisionCheck(int x,int y,int Direction){
switch(Direction){
case Direction_Up:
if(y == 0){
return false;
}else if(!WallsVer[y-1][x]){
return true;
}else{
return false;
}
case Direction_Down:
if(y==SizeY-1){
return false;
}else if(!WallsVer[y][x]){
return true;
}else{
return false;
}
case Direction_Right:
if(x==SizeX-1){
return false;
}else if(!WallsHor[y][x]){
return true;
}else{
return false;
}
case Direction_Left:
if(x == 0){
return false;
}else if(!WallsHor[y][x-1]){
return true;
}else{
return false;
}
}
return false;
}
public void update() {
}
public void paint(Graphics g) {
//draw border
g.setColor(Color.RED);
g.drawLine(0, 0, width, 0);
g.drawLine(0, height, width, height);
g.drawLine(0, 0, 0, height);
g.drawLine(width, 0, width, height);
//draw maze
g.setColor(Color.RED);
for(int j=0;j<SizeX;j++){
for(int i=0;i<(SizeY-1);i++){
if(WallsVer[i][j])
g.drawLine(j*100,(i+1)*100 , (j*100)+100,(i+1)*100 );
}
}
for(int j=0;j<(SizeX-1);j++){
for(int i=0;i<SizeY;i++){
if(WallsHor[i][j])
g.drawLine((j+1)*100, i*100,(j+1)*100, (i*100)+100);
}
}
}
public void generate(){
// horX = sizeX -1
// horY = sizeY
// verX = sizeX
// verY = sizeY -1
//set and initialize variables
int TotalCells=SizeX*SizeY, VistedCells=0;
int[] CurrentCell = start;
int[] AvaliableCells = new int[4];
int AvaliableCellsNum = 0;
int[][] stack= new int[TotalCells][2];
int stackPointer = 0;
boolean[][] map = new boolean[SizeX][SizeY];
//initialize walls
for(int j=0;j<SizeX;j++){
for(int i=0;i<(SizeY-1);i++){
WallsVer[i][j]= true;
}
}
for(int j=0;j<(SizeX-1);j++){
for(int i=0;i<SizeY;i++){
WallsHor[i][j] = true;
}
}
//initialize map
for(int j=0;j<(SizeX-1);j++){
for(int i=0;i<(SizeY-1);i++){
map[0][0]= false;
}
}
map[CurrentCell[0]][CurrentCell[1]] = true;
stack[stackPointer] = start;
VistedCells=1;
while(VistedCells < TotalCells){
// test all the walls and enter them in AvaliableCells
if(CurrentCell[0]!=0 && !map[CurrentCell[0]-1][CurrentCell[1]]){
AvaliableCells[AvaliableCellsNum] = Direction_Right;
AvaliableCellsNum++;
}
if(CurrentCell[0]!=3 && !map[CurrentCell[0]+1][CurrentCell[1]]){
AvaliableCells[AvaliableCellsNum] = Direction_Left;
AvaliableCellsNum++;
}
if(CurrentCell[1]!=0 && !map[CurrentCell[0]][CurrentCell[1]-1]){
AvaliableCells[AvaliableCellsNum] = Direction_Up;
AvaliableCellsNum++;
}
if(CurrentCell[1]!=3 && !map[CurrentCell[0]][CurrentCell[1]+1]){
AvaliableCells[AvaliableCellsNum] = Direction_Down;
AvaliableCellsNum++;
}
// randomization process
if(AvaliableCellsNum > 0){
Random RndGen = new Random();
int RndValue = RndGen.nextInt(AvaliableCellsNum);
AvaliableCellsNum = 0;
switch(AvaliableCells[RndValue]){
case Direction_Up:
WallsVer[CurrentCell[1]-1][CurrentCell[0]] = false;
CurrentCell[1]--;
map[CurrentCell[0]][CurrentCell[1]] = true;
stackPointer++;
stack[stackPointer] = CurrentCell;
VistedCells++;
break;
case Direction_Down:
WallsVer[CurrentCell[1]][CurrentCell[0]] = false;
CurrentCell[1]++;
map[CurrentCell[0]][CurrentCell[1]] = true;
stackPointer++;
stack[stackPointer] = CurrentCell;
VistedCells++;
break;
case Direction_Right:
WallsHor[CurrentCell[1]][CurrentCell[0]-1] = false;
CurrentCell[0]--;
map[CurrentCell[0]][CurrentCell[1]] = true;
stackPointer++;
stack[stackPointer] = CurrentCell;
VistedCells++;
break;
case Direction_Left:
WallsHor[CurrentCell[1]][CurrentCell[0]] = false;
CurrentCell[0]++;
map[CurrentCell[0]][CurrentCell[1]] = true;
stackPointer++;
stack[stackPointer] = CurrentCell;
VistedCells++;
break;
}
}else{
stack = popStack(stack,stackPointer);
CurrentCell = stack[stack.length-1];
}
}
end = CurrentCell;
}
private int[][] popStack(int[][] stack,int newlength){
int[][] temp = new int[newlength][2];
for(int i=0;i<newlength;i++){
temp[i] = stack[i];
}
return temp;
}
//getters and setters
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public int getSizeX() {
return SizeX;
}
public int getSizeY() {
return SizeY;
}
public int getStartX() {
return (start[0]*(width/SizeX))+offset;
}
public int getStartY() {
return (start[1]*(height/SizeY))+offset;
}
public int getEndX() {
return (end[0]*(width/SizeX))+offset;
}
public int getEndY() {
return (end[1]*(height/SizeY))+offset;
}
public int getBlockW() {
return (width/SizeX)-(2*offset);
}
public int getBlockH() {
return (height/SizeY)-(2*offset);
}
}
Related
I am trying to implement a Drawing Application in Android where the user should be able to select and move the drawn shapes.
Currently, I have statically drawn some rects and text on my Drawing Canvas.
I want to select (draw borders on the selected shape) and move the drawn shapes in onTouch events of the drawing canvas.
package com.android.graphics;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
public class CanvasView extends View {
public enum Mode {
DRAW,
TEXT,
ERASER;
}
public enum Drawer {
PEN,
LINE,
RECTANGLE,
CIRCLE,
ELLIPSE,
QUADRATIC_BEZIER,
QUBIC_BEZIER;
}
private Canvas canvas = null;
private Bitmap bitmap = null;
private List<Path> pathLists = new ArrayList<Path>();
private List<Paint> paintLists = new ArrayList<Paint>();
private final Paint emptyPaint = new Paint();
private int baseColor = Color.WHITE;
// for Undo, Redo
private int historyPointer = 0;
// Flags
private Mode mode = Mode.DRAW;
private Drawer drawer = Drawer.PEN;
private boolean isDown = false;
// for Paint
private Paint.Style paintStyle = Paint.Style.STROKE;
private int paintStrokeColor = Color.BLACK;
private int paintFillColor = Color.BLACK;
private float paintStrokeWidth = 3F;
private int opacity = 255;
private float blur = 0F;
private Paint.Cap lineCap = Paint.Cap.ROUND;
private PathEffect drawPathEffect = null;
// for Text
private String text = "";
private Typeface fontFamily = Typeface.DEFAULT;
private float fontSize = 32F;
private Paint.Align textAlign = Paint.Align.RIGHT; // fixed
private Paint textPaint = new Paint();
private float textX = 0F;
private float textY = 0F;
// for Drawer
private float startX = 0F;
private float startY = 0F;
private float controlX = 0F;
private float controlY = 0F;
public CanvasView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setup();
}
public CanvasView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setup();
}
public CanvasView(Context context) {
super(context);
this.setup();
}
private void setup() {
this.pathLists.add(new Path());
this.paintLists.add(this.createPaint());
this.historyPointer++;
this.textPaint.setARGB(0, 255, 255, 255);
}
private Paint createPaint() {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(this.paintStyle);
paint.setStrokeWidth(this.paintStrokeWidth);
paint.setStrokeCap(this.lineCap);
paint.setStrokeJoin(Paint.Join.MITER); // fixed
// for Text
if (this.mode == Mode.TEXT) {
paint.setTypeface(this.fontFamily);
paint.setTextSize(this.fontSize);
paint.setTextAlign(this.textAlign);
paint.setStrokeWidth(0F);
}
if (this.mode == Mode.ERASER) {
// Eraser
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
paint.setARGB(0, 0, 0, 0);
} else {
// Otherwise
paint.setColor(this.paintStrokeColor);
paint.setShadowLayer(this.blur, 0F, 0F, this.paintStrokeColor);
paint.setAlpha(this.opacity);
paint.setPathEffect(this.drawPathEffect);
}
return paint;
}
private Path createPath(MotionEvent event) {
Path path = new Path();
// Save for ACTION_MOVE
this.startX = event.getX();
this.startY = event.getY();
path.moveTo(this.startX, this.startY);
return path;
}
private void updateHistory(Path path) {
if (this.historyPointer == this.pathLists.size()) {
this.pathLists.add(path);
this.paintLists.add(this.createPaint());
this.historyPointer++;
} else {
// On the way of Undo or Redo
this.pathLists.set(this.historyPointer, path);
this.paintLists.set(this.historyPointer, this.createPaint());
this.historyPointer++;
for (int i = this.historyPointer, size = this.paintLists.size(); i < size; i++) {
this.pathLists.remove(this.historyPointer);
this.paintLists.remove(this.historyPointer);
}
}
}
private Path getCurrentPath() {
return this.pathLists.get(this.historyPointer - 1);
}
private void drawText(Canvas canvas) {
if (this.text.length() <= 0) {
return;
}
if (this.mode == Mode.TEXT) {
this.textX = this.startX;
this.textY = this.startY;
this.textPaint = this.createPaint();
}
float textX = this.textX;
float textY = this.textY;
Paint paintForMeasureText = new Paint();
// Line break automatically
float textLength = paintForMeasureText.measureText(this.text);
float lengthOfChar = textLength / (float) this.text.length();
float restWidth = this.canvas.getWidth() - textX; // text-align : right
int numChars = (lengthOfChar <= 0) ? 1 : (int) Math.floor((double) (restWidth / lengthOfChar)); // The number of characters at 1 line
int modNumChars = (numChars < 1) ? 1 : numChars;
float y = textY;
for (int i = 0, len = this.text.length(); i < len; i += modNumChars) {
String substring = "";
if ((i + modNumChars) < len) {
substring = this.text.substring(i, (i + modNumChars));
} else {
substring = this.text.substring(i, len);
}
y += this.fontSize;
canvas.drawText(substring, textX, y, this.textPaint);
}
}
private void onActionDown(MotionEvent event) {
switch (this.mode) {
case DRAW:
case ERASER:
if ((this.drawer != Drawer.QUADRATIC_BEZIER) && (this.drawer != Drawer.QUBIC_BEZIER)) {
// Oherwise
this.updateHistory(this.createPath(event));
this.isDown = true;
} else {
// Bezier
if ((this.startX == 0F) && (this.startY == 0F)) {
// The 1st tap
this.updateHistory(this.createPath(event));
} else {
// The 2nd tap
this.controlX = event.getX();
this.controlY = event.getY();
this.isDown = true;
}
}
break;
case TEXT:
this.startX = event.getX();
this.startY = event.getY();
break;
default:
break;
}
}
private void onActionMove(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (this.mode) {
case DRAW:
case ERASER:
if ((this.drawer != Drawer.QUADRATIC_BEZIER) && (this.drawer != Drawer.QUBIC_BEZIER)) {
if (!isDown) {
return;
}
Path path = this.getCurrentPath();
switch (this.drawer) {
case PEN:
path.lineTo(x, y);
break;
case LINE:
path.reset();
path.moveTo(this.startX, this.startY);
path.lineTo(x, y);
break;
case RECTANGLE:
path.reset();
float left = Math.min(this.startX, x);
float right = Math.max(this.startX, x);
float top = Math.min(this.startY, y);
float bottom = Math.max(this.startY, y);
path.addRect(left, top, right, bottom, Path.Direction.CCW);
break;
case CIRCLE:
double distanceX = Math.abs((double) (this.startX - x));
double distanceY = Math.abs((double) (this.startX - y));
double radius = Math.sqrt(Math.pow(distanceX, 2.0) + Math.pow(distanceY, 2.0));
path.reset();
path.addCircle(this.startX, this.startY, (float) radius, Path.Direction.CCW);
break;
case ELLIPSE:
RectF rect = new RectF(this.startX, this.startY, x, y);
path.reset();
path.addOval(rect, Path.Direction.CCW);
break;
default:
break;
}
} else {
if (!isDown) {
return;
}
Path path = this.getCurrentPath();
path.reset();
path.moveTo(this.startX, this.startY);
path.quadTo(this.controlX, this.controlY, x, y);
}
break;
case TEXT:
this.startX = x;
this.startY = y;
break;
default:
break;
}
}
private void onActionUp(MotionEvent event) {
if (isDown) {
this.startX = 0F;
this.startY = 0F;
this.isDown = false;
}
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Before "drawPath"
canvas.drawColor(this.baseColor);
if (this.bitmap != null) {
canvas.drawBitmap(this.bitmap, 0F, 0F, emptyPaint);
}
for (int i = 0; i < this.historyPointer; i++) {
Path path = this.pathLists.get(i);
Paint paint = this.paintLists.get(i);
canvas.drawPath(path, paint);
}
this.drawText(canvas);
this.canvas = canvas;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
this.onActionDown(event);
break;
case MotionEvent.ACTION_MOVE:
this.onActionMove(event);
break;
case MotionEvent.ACTION_UP:
this.onActionUp(event);
break;
default:
break;
}
// Re draw
this.invalidate();
return true;
}
public Mode getMode() {
return this.mode;
}
public void setMode(Mode mode) {
this.mode = mode;
}
public Drawer getDrawer() {
return this.drawer;
}
public void setDrawer(Drawer drawer) {
this.drawer = drawer;
}
public boolean canUndo() {
return this.historyPointer > 1;
}
public boolean canRedo() {
return this.historyPointer < this.pathLists.size();
}
public boolean undo() {
if (canUndo()) {
this.historyPointer--;
this.invalidate();
return true;
} else {
return false;
}
}
public boolean redo() {
if (canRedo()) {
this.historyPointer++;
this.invalidate();
return true;
} else {
return false;
}
}
public void clear() {
Path path = new Path();
path.moveTo(0F, 0F);
path.addRect(0F, 0F, 3000F, 3000F, Path.Direction.CCW);
path.close();
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.FILL);
if (this.historyPointer == this.pathLists.size()) {
this.pathLists.add(path);
this.paintLists.add(paint);
this.historyPointer++;
} else {
// On the way of Undo or Redo
this.pathLists.set(this.historyPointer, path);
this.paintLists.set(this.historyPointer, paint);
this.historyPointer++;
for (int i = this.historyPointer, size = this.paintLists.size(); i < size; i++) {
this.pathLists.remove(this.historyPointer);
this.paintLists.remove(this.historyPointer);
}
}
this.text = "";
// Clear
this.invalidate();
}
public int getBaseColor() {
return this.baseColor;
}
public void setBaseColor(int color) {
this.baseColor = color;
}
public String getText() {
return this.text;
}
public void setText(String text) {
this.text = text;
}
public Paint.Style getPaintStyle() {
return this.paintStyle;
}
public void setPaintStyle(Paint.Style style) {
this.paintStyle = style;
}
public int getPaintStrokeColor() {
return this.paintStrokeColor;
}
public void setPaintStrokeColor(int color) {
this.paintStrokeColor = color;
}
public int getPaintFillColor() {
return this.paintFillColor;
}
public void setPaintFillColor(int color) {
this.paintFillColor = color;
}
public float getPaintStrokeWidth() {
return this.paintStrokeWidth;
}
public void setPaintStrokeWidth(float width) {
if (width >= 0) {
this.paintStrokeWidth = width;
} else {
this.paintStrokeWidth = 3F;
}
}
public int getOpacity() {
return this.opacity;
}
public void setOpacity(int opacity) {
if ((opacity >= 0) && (opacity <= 255)) {
this.opacity = opacity;
} else {
this.opacity = 255;
}
}
public float getBlur() {
return this.blur;
}
public void setBlur(float blur) {
if (blur >= 0) {
this.blur = blur;
} else {
this.blur = 0F;
}
}
public Paint.Cap getLineCap() {
return this.lineCap;
}
public void setLineCap(Paint.Cap cap) {
this.lineCap = cap;
}
public PathEffect getDrawPathEffect() {
return drawPathEffect;
}
public void setDrawPathEffect(PathEffect drawPathEffect) {
this.drawPathEffect = drawPathEffect;
}
public float getFontSize() {
return this.fontSize;
}
public void setFontSize(float size) {
if (size >= 0F) {
this.fontSize = size;
} else {
this.fontSize = 32F;
}
}
public Typeface getFontFamily() {
return this.fontFamily;
}
public void setFontFamily(Typeface face) {
this.fontFamily = face;
}
public Bitmap getBitmap() {
this.setDrawingCacheEnabled(false);
this.setDrawingCacheEnabled(true);
return Bitmap.createBitmap(this.getDrawingCache());
}
public Bitmap getScaleBitmap(int w, int h) {
this.setDrawingCacheEnabled(false);
this.setDrawingCacheEnabled(true);
return Bitmap.createScaledBitmap(this.getDrawingCache(), w, h, true);
}
public void drawBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
this.invalidate();
}
public void drawBitmap(byte[] byteArray) {
this.drawBitmap(BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length));
}
public static byte[] getBitmapAsByteArray(Bitmap bitmap, CompressFormat format, int quality) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(format, quality, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
public byte[] getBitmapAsByteArray(CompressFormat format, int quality) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
this.getBitmap().compress(format, quality, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
public byte[] getBitmapAsByteArray() {
return this.getBitmapAsByteArray(CompressFormat.PNG, 100);
}
}
I need help with a project. For this project we have created moving rectangles that "freeze" when clicked on. We are also supposed to make frozen rectangles unfrozen if they collide with another. I have gotten the first step done but I can't seem to get the rectangles to unfreeze if they collide. I apologize if this doesn't make sense. I am new to Java and stack overflow. Here is my class code.
import edu.princeton.cs.introcs.StdDraw;
import java.util.Random;
import java.awt.Color;
public class MovingRectangle {
//canvas = canvasSize;
public int width; //width of rectangle
public int height; //height of rectangle
public double xVelocity; //x velocity
public double yVelocity; //y velocity
public int xPosition; //x starting position
public int yPosition; //y starting position
private boolean isFrozen; //the rectangle is still moving
// private int R, G, B;
Random rng = new Random();
public int R = rng.nextInt(256);
public int G = rng.nextInt(256);
public int B = rng.nextInt(256); //RGB variables
public int canvas;
public Color c;//canvas size
public MovingRectangle(int x, int y, int w, int h, double xv, double yv, int canvasSize) {
xPosition = x;
yPosition = y;
width = w;
height = h;
xVelocity = xv;
yVelocity = yv;
canvas = canvasSize;
isFrozen = false;
c =new Color(R,G,B);
}
//draws rectangle
public void draw() {
// Random rng = new Random();
// R = rng.nextInt(256);
// G = rng.nextInt(256);
// B = rng.nextInt(256);
// c = new Color(R,G,B);
StdDraw.setPenColor(c);
StdDraw.filledRectangle(xPosition, yPosition, width/2, height/2);
}
//pick a new random color
// public void color() {
// Random rng = new Random();
//
// R = rng.nextInt(256);
// G = rng.nextInt(256);
// B = rng.nextInt(256);
// c = new Color(R,G,B);
// }
//updates position every frame
public void move() {
if (isFrozen == false) {
xPosition += xVelocity;
yPosition += yVelocity;
// xPosition += 0;
// yPosition += 0;
//Check for hitting sides of canvas
if (xPosition > canvas) {
xVelocity *= -1;
//color();
}
if( xPosition < 0) {
xVelocity *= -1;
//color();
}
if (yPosition > canvas ) {
yVelocity *= -1;
//color();
}
if(yPosition <= 0) {
yVelocity*=-1;
//color();
}
}
}
public boolean ifColliding(MovingRectangle rectangle) {
int rightedge = rectangle.xPosition + rectangle.width/2;
int leftedge = rectangle.xPosition - rectangle.width/2;
int topedge = rectangle.yPosition + rectangle.height/2;
int bottomedge = rectangle.yPosition - height/2;
int rightedge2 = this.xPosition + this.width/2;
int leftedge2 = this.xPosition - this.width/2;
int topedge2 = this.yPosition + this.height/2;
int bottomedge2 = this.yPosition - this.height/2;
if(leftedge<rightedge2 && leftedge2<rightedge && topedge>bottomedge2 && bottomedge<topedge2) {
return true;
}
else {
return false;
}
}
public void freeze() {
if(StdDraw.mousePressed() && StdDraw.mouseX() <= xPosition+width && StdDraw.mouseX() >= xPosition-width && StdDraw.mouseY() <=yPosition+height &&StdDraw.mouseY() >= yPosition-height) {
xVelocity=0;
yVelocity=0;
c= new Color(100,0,0);
isFrozen= true;
}
}
public boolean isFrozen() {
return isFrozen;
}
public void winState() {
StdDraw.clear();
}
public void setFrozen(boolean val) {
isFrozen = false;
if (isFrozen == false) {
xPosition += xVelocity;
yPosition += yVelocity;
}
}
// public void stop() {
// isMoving = false;
// }
}
And my driver.
import edu.princeton.cs.introcs.StdDraw;
import java.util.Random;
import java.util.Scanner;
import java.awt.Color.*;
import edu.princeton.cs.introcs.StdDraw;
public class RectangleDriver {
public static final int canvas = 500;
public static void main(String[] args) {
//set canvas size
StdDraw.setCanvasSize(canvas,canvas);
StdDraw.setXscale(canvas, 0);
StdDraw.setYscale(0, canvas);
//assign variables
Random rng = new Random();
//make a rectangle
MovingRectangle[] rectangles = new MovingRectangle[5]; //(x, y, w, h, xv, yv, canvas);
for(int i =0;i<rectangles.length;i++) {
int x = rng.nextInt(canvas); //xPosition
int y = rng.nextInt(canvas); //yPosition
int w = rng.nextInt(100)+20; //width
int h = rng.nextInt(100)+20; //height
double xv = rng.nextInt(5)+2; //xVelocity
double yv = rng.nextInt(5)+2; //yVelocity
rectangles[i]= new MovingRectangle(x,y,w,h,xv,yv,canvas);
}
//while isMoving, the rectangles move
while (true) {
StdDraw.clear();
for(int i =0; i<rectangles.length;i++) {
rectangles[i].move();
rectangles[i].draw();
rectangles[i].freeze();
System.out.println(rectangles[i].isFrozen());
//for 0
if(rectangles[i].ifColliding(rectangles[1])){
if(rectangles[0].isFrozen()) {
rectangles[0].setFrozen(false);
}
}
if(rectangles[i].ifColliding(rectangles[2])){
if(rectangles[0].isFrozen()) {
rectangles[0].setFrozen(false);
}
}
if(rectangles[i].ifColliding(rectangles[3])){
if(rectangles[0].isFrozen()) {
rectangles[0].setFrozen(false);
}
}
if(rectangles[i].ifColliding(rectangles[4])){
if(rectangles[0].isFrozen()) {
rectangles[0].setFrozen(false);
}
}
//for 1
if(rectangles[1].ifColliding(rectangles[0])){
if(rectangles[1].isFrozen()) {
rectangles[1].setFrozen(false);
}
}
if(rectangles[1].ifColliding(rectangles[2])){
if(rectangles[1].isFrozen()) {
rectangles[1].setFrozen(false);
}
}
if(rectangles[1].ifColliding(rectangles[3])){
if(rectangles[1].isFrozen()) {
rectangles[1].setFrozen(false);
}
}
if(rectangles[1].ifColliding(rectangles[4])){
if(rectangles[1].isFrozen()) {
rectangles[1].setFrozen(false);
}
}
// for 2
if(rectangles[2].ifColliding(rectangles[0])){
if(rectangles[2].isFrozen()) {
rectangles[2].setFrozen(false);
}
}
if(rectangles[2].ifColliding(rectangles[1])){
if(rectangles[2].isFrozen()) {
rectangles[2].setFrozen(false);
}
}
if(rectangles[2].ifColliding(rectangles[3])){
if(rectangles[2].isFrozen()) {
rectangles[2].setFrozen(false);
}
}
if(rectangles[2].ifColliding(rectangles[4])){
if(rectangles[2].isFrozen()) {
rectangles[2].setFrozen(false);
}
}
//for 3
if(rectangles[3].ifColliding(rectangles[1])){
if(rectangles[3].isFrozen()) {
rectangles[3].setFrozen(false);
}
}
if(rectangles[3].ifColliding(rectangles[2])){
if(rectangles[3].isFrozen()) {
rectangles[3].setFrozen(false);
}
}
if(rectangles[3].ifColliding(rectangles[0])){
if(rectangles[3].isFrozen()) {
rectangles[3].setFrozen(false);
}
}
if(rectangles[3].ifColliding(rectangles[4])){
if(rectangles[3].isFrozen()) {
rectangles[3].setFrozen(false);
}
}
//for 4
if(rectangles[4].ifColliding(rectangles[1])){
if(rectangles[4].isFrozen()) {
rectangles[4].setFrozen(false);
}
}
if(rectangles[4].ifColliding(rectangles[2])){
if(rectangles[4].isFrozen()) {
rectangles[4].setFrozen(false);
}
}
if(rectangles[4].ifColliding(rectangles[3])){
if(rectangles[4].isFrozen()) {
rectangles[4].setFrozen(false);
}
}
if(rectangles[4].ifColliding(rectangles[0])){
if(rectangles[4].isFrozen()) {
rectangles[4].setFrozen(false);
}
}
}
if(rectangles[0].isFrozen()==true && rectangles[1].isFrozen()==true && rectangles[2].isFrozen()==true && rectangles[3].isFrozen()==true && rectangles[4].isFrozen()==true) {
StdDraw.clear();
StdDraw.text(250, 250, "You win!");
}
StdDraw.show(100);
}
}
}
I have a sprite that collides with obstacle, but i have a problem with the score in the top of my screen.
In the update of my class, The collisions are specified by an array, but when it collides with an object, the score is still growing and I can not stop it. this is my code:
private Array<Polen> polen;
private Score score;
public PlayState(GameStateManager gsm) {
super(gsm);
score = new Score(110, 310);
polen = new Array<Polen>();
for(int i = 1; i <= COUNT; i++){
polen.add(new Polen(i * (Polen.WIDTH)));
}
}
#Override
public void update(float dt) {
handleInput();
for(int i = 0; i < polen.size; i++){
Polen pol= polen.get(i);
if(pol.collides(aliado.getBounds())) {
pol.changeExplosion();
flagScore = 1;
}
if (pol.collides(aliado.getBounds())==false){
flagScore = 0;
}
}
if (flagScore == 1){
Score.count++;
flagScore=0;
//auxCount = Score.count +1;
}
score.update(dt);
updateGround();
cam.update();
}
Score Class:
public class Score {
private static final int MOVEMENT = 70;
private Vector3 position;
private Vector3 velocity;
private Rectangle bounds;
private Texture texture;
public Score(int x, int y){
position = new Vector3(x, y, 0);
velocity = new Vector3(0, 0, 0);
texture = new Texture("score0.png");
bounds = new Rectangle(x, y, ((texture.getWidth())), texture.getHeight());
}
public void update(float dt){//code for move the score for top of screen:
if(position.y > 0)
velocity.add(0, 0, 0);
velocity.scl(dt);
position.add(MOVEMENT * dt, velocity.y, 0);
if(position.y < 0)
position.y = 0;
velocity.scl(1/dt);
bounds.setPosition(position.x, position.y);
}
public Vector3 getPosition() {
return position;
}
public Texture getTexture() {
return texture;
}
public void setTexture(Texture texture) {
this.texture = texture;
}
public Vector3 getVelocity() {
return velocity;
}
public void setVelocity(Vector3 velocity) {
this.velocity = velocity;
}
public Rectangle getBounds(){
return bounds;
}
public void setBounds(Rectangle bounds) {
this.bounds = bounds;
}
public void dispose(){
texture.dispose();
}
}
In pol.changeExplosion() you should add a boolean to mark the object as done.
public class Polen {
private boolean exploded = false;
public void changeExplosion() {
// ...
exploded = true;
// ...
}
public boolean isExploded() {
return exploded;
}
}
Then, in your update function you can use this flag to determine if the score should stop being incremented.
for(int i = 0; i < polen.size; i++) {
Polen pol= polen.get(i);
if(pol.collides(aliado.getBounds()) && !pol.isExploded()) {
pol.changeExplosion();
flagScore = 1;
}
else if (!pol.collides(aliado.getBounds())) {
flagScore = 0;
}
}
I am working on a vertical number picker in custom view. Now, working on the "fling" event of picker in Action_up of onTouchEvent method but having no idea on it.
This is my code:
protected Paint textPaint;
private int textColor;
private float text_size;
private final int min_size;
private int mValue;
private int mMaxValue;
private int mMinValue;
private VelocityTracker mVelocityTracker;
private float lastDownEventY;
private int mMinimumFlingVelocity;
private int maximumFlingVelocity;
private int touchSlop;
private boolean scrollingY;
private OverScroller flingScrollerY;
private int itemheight;
public VerticalNumberPicker(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TunerRuler, 0, 0);
min_size = (int) dp2px(getResources(), 100);
try {
text_size = a.getDimension(R.styleable.VerticalNumberPicker_android_textSize, 0.0f);
textColor = a.getColor(R.styleable.VerticalNumberPicker_android_textColor, Color.parseColor("#FFFFFF"));
mValue = a.getInt(R.styleable.VerticalNumberPicker_nowvalue, 120);
mMinValue = a.getInt(R.styleable.VerticalNumberPicker_minvalue, 0);
mMaxValue = a.getInt(R.styleable.VerticalNumberPicker_maxvalue, 250);
} finally {
a.recycle();
}
ViewConfiguration configuration = ViewConfiguration.get(context);
touchSlop = configuration.getScaledTouchSlop();
mMinimumFlingVelocity = configuration.getScaledMinimumFlingVelocity();
maximumFlingVelocity = configuration.getScaledMaximumFlingVelocity();
flingScrollerY = new OverScroller(context);
itemheight = getHeight() / 3;
init(context);
}
private void init(Context context) {
Typeface custom_font = Typeface.createFromAsset(context.getAssets(), "fonts/Raleway-ExtraLight.ttf");
textPaint = new TextPaint();
textPaint.setColor(textColor);
textPaint.setTypeface(custom_font);
textPaint.setTextSize(text_size);
textPaint.setAntiAlias(true);
}
public boolean onTouchEvent(MotionEvent event) {
if(!isEnabled()) {
return false;
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(event);
int action = event.getActionMasked();
switch (action) {
case MotionEvent.ACTION_MOVE:
float currentMoveY = event.getY();
int deltaMoveY = (int) (lastDownEventY - currentMoveY);
if(scrollingY || (Math.abs(deltaMoveY) > touchSlop)) {
if(!scrollingY) {
deltaMoveY = 0;
//pressedItem = -1;
scrollingY = true;
getParent().requestDisallowInterceptTouchEvent(true);
}
lastDownEventY = currentMoveY;
if(deltaMoveY > 0) {
if(mValue + 1 > mMaxValue)
mValue = mMinValue;
else
mValue += 1;
}
else if(deltaMoveY < 0){
if(mValue - 1 < mMinValue)
mValue = mMaxValue;
else
mValue -= 1;
}
invalidate();
Log.i("move", "onTouchEvent: " + lastDownEventY + " " + deltaMoveY);
}
break;
case MotionEvent.ACTION_DOWN:
if(!flingScrollerY.isFinished()) {
flingScrollerY.forceFinished(true);
} else {
scrollingY = false;
}
lastDownEventY = event.getX();
invalidate();
Log.i("down", "onTouchEvent: ");
break;
case MotionEvent.ACTION_UP:
VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, maximumFlingVelocity);
int initialVelocityY = (int) velocityTracker.getYVelocity();
if(scrollingY && Math.abs(initialVelocityY) > mMinimumFlingVelocity) {
//flingY(initialVelocityY);
} else if (mValue != -1) {
float positionY = event.getY();
if(!scrollingY) {
int itemPos = getPositionOnScreen(positionY);
int relativePos = itemPos - 1;
if (relativePos == 0) {
//selectItem();
} else {
smoothScrollBy(relativePos);
}
} else if(scrollingY) {
//finishScrolling();
scrollingY = false;
}
}
mVelocityTracker.recycle();
mVelocityTracker = null;
Log.i("up", "onTouchEvent: ");
}
return true;
}
protected void onDraw(Canvas canvas) {
float textHeight = textPaint.descent() + textPaint.ascent();
canvas.drawText(String.valueOf(mValue), (getWidth() - textPaint.measureText(String.valueOf(mValue))) / 2.0f, (getHeight() - textHeight) / 2.0f, textPaint);
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//Paint.FontMetrics fm = textPaint.getFontMetrics();
//float textHeight = fm.top + fm.bottom + fm.ascent;
int width = (int) textPaint.measureText("444");
setMeasuredDimension(width, heightMeasureSpec);
}
private int getPositionOnScreen(float x) {
return (int) (x / itemheight);
}
private void smoothScrollBy(int i) {
int deltaMoveY = itemheight * i;
deltaMoveY = getRelativeInBound(deltaMoveY);
//previousScrollerY = Integer.MIN_VALUE;
flingScrollerY.startScroll(0, getScrollY(), 0, deltaMoveY);
invalidate();
}
private int getRelativeInBound(int y) {
int scrollY = getScrollY();
return getInBoundsY(scrollY + y) - scrollY;
}
private int getInBoundsY(int x) {
if(x < 0) {
x = 0;
} else if(x > ((itemheight) * (mMaxValue-mMinValue))) {
x = ((itemheight) * (mMaxValue-mMinValue));
}
return x;
}
private int measure(int measureSpec){
int result;
int mode = MeasureSpec.getMode(measureSpec);
int size = MeasureSpec.getSize(measureSpec);
if(mode == MeasureSpec.EXACTLY){
result = size;
}else{
result = min_size;
if(mode == MeasureSpec.AT_MOST){
result = Math.min(result, size);
}
}
return result;
}
public static float dp2px(Resources resources, float dp) {
final float scale = resources.getDisplayMetrics().density;
return dp * scale + 0.5f;
}
public int getValue() {
return mValue;
}
public void setValue(int value){
//this.mValue = value;
if(value > mMaxValue)
mValue = mMinValue;
else if(value < mMinValue)
mValue = mMaxValue;
else
mValue = value;
invalidate();
}
public int getMinValue() {
return mMinValue;
}
public void setMinValue(int minValue) {
if (mMinValue == minValue) {
return;
}
if (minValue < 0) {
throw new IllegalArgumentException("minValue must be >= 0");
}
mMinValue = minValue;
if (mMinValue > mValue) {
mValue = mMinValue;
}
invalidate();
}
public int getMaxValue() {
return mMaxValue;
}
public void setMaxValue(int maxValue) {
if (mMaxValue == maxValue) {
return;
}
if (maxValue < 0) {
throw new IllegalArgumentException("maxValue must be >= 0");
}
mMaxValue = maxValue;
if (mMaxValue < mValue) {
mValue = mMaxValue;
}
invalidate();
}
}
Can anyone give me some hints or examples to work on it?
I've tried to find similar questions, but I think I have a unique situation here.
I am programming a game in java, my main class creates a frame which adds a component class which is an extension of JPanel. Basically, I draw these ovals and they move around and do different things, and I want to implement a method inside of one my classes which will use an image instead of an oval. However, anytime I try to create and image from a file, the program will not run the overridden "paintComponent(Graphics g)" method.
My main:
package mikeengine;
import javax.swing.JFrame;
public class MikeEngine {
static final int fx = 1300;
static final int fy = 800;
static final int px = 1292;
static final int py = 767;
static interactivePanel levelPanel;
public static void pause() {
try {
Thread.sleep(10); // wait 10ms
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("MEngine");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(fx, fy);
frame.setResizable(false);
frame.setVisible(true);
levelPanel = new interactivePanel();
addship();
frame.getContentPane().add(levelPanel);
levelPanel.requestFocusInWindow();
while (true) {
pause();
levelPanel.move();
levelPanel.repaint();
}
}
static void addship() {
PlayerShip ship = new PlayerShip(100, 25, 25, px, 0, py, 0);
ship.setGraphic("C:/Users/asdf/Documents/NetBeansProjects/mikeEngine/src/mikeengine/res/right-arrow.jpg");
levelPanel.addObject(ship);
for (int i = 0; i < 5; i++) {
PlayerShip ship2 = new PlayerShip((int) (Math.random() * 1000) + 100, (int) (Math.random() * 1000) + 100, 25, px, px / 2, py, 0);
ship2.setMovement((int) (Math.random() * 10) / 5, (int) (Math.random() * 10) / 2);
levelPanel.addObject(ship2);
}
}
}
now, if I comment out the line:
ship.setGraphic("C:/Users/asdf/Documents/NetBeansProjects/mikeEngine/src/mikeengine/res/right-arrow.jpg");
everything renders perfectly.
I don't even paint the image that is going to be created. The image variable is just part of a class and it is currently just being created and doing nothing, so I don't understand how it affects the paintcomponentMethod(), if the paintComponent() isn't even told to try to paint the image ever.
The "PlayerShip" class extends the abstract "OnScreenObject" class (you really shouldn't need to see the code for PlayerShip, it only overrides one irrelevant method).
OnScreenObject looks like so:
package mikeengine;
import java.awt.Color;
import java.awt.Image;
import javax.swing.ImageIcon;
public abstract class OnScreenObject {
private ImageIcon graphic;
Image g;
protected int xmin;
protected int ymin;
protected int xsize;
protected int ysize;
protected int rise;
protected int run;
protected int containerYMax;
protected int containerYMin;
protected int containerXMax;
protected int containerXMin;
protected boolean visible;
protected boolean allowedOffscreen;
protected boolean isSelected;
protected Color color;
OnScreenObject(int x, int y, int sizeX, int sizeY, int cxMax, int cxMin, int cyMax, int cyMin) {
xmin = x;
ymin = y;
xsize = sizeX;
ysize = sizeY;
containerXMax = cxMax;
containerXMin = cxMin;
containerYMax = cyMax;
containerYMin = cyMin;
//
rise = 0;
run = 0;
visible = true;
allowedOffscreen = false;
isSelected = false;
}
public int getXMin() {
return xmin;
}
public int getYMin() {
return ymin;
}
public int getXMax() {
return xmin + xsize;
}
public int getYMax() {
return ymin + ysize;
}
public int getXSize() {
return xsize;
}
public int getYSize() {
return ysize;
}
public Color getColor() {
return color;
}
public boolean getAllowedOffscreen() {
return allowedOffscreen;
}
public boolean getVisible() {
return visible;
}
public int getRun() {
return run;
}
public ImageIcon getGraphic() {
return graphic;
}
public boolean isWithin(int x, int y) {
return x >= xmin && x <= getXMax() && y >= ymin && y <= getYMax();
}
public void setXMin(int x) {
xmin = x;
}
public void setYMin(int y) {
ymin = y;
}
public void setXSize(int x) {
xsize = x;
}
public void setYSize(int y) {
ysize = y;
}
public void setGraphic(String setto) {
try{
graphic = new ImageIcon("setto");
g=graphic.getImage();
System.out.println("tried");
} catch(Exception e){
System.out.println("caught:" + e);
}
}
public void setAllowedOffscreen(boolean allowed) {
allowedOffscreen = allowed;
}
public void setMovement(int riseM, int runM) {
rise = riseM * -1;//rise means to go up, and negative will move it up
run = runM;
}
public void nudge(boolean horizontal, int amount) {
if (horizontal) {
run += amount;
} else {
rise += amount;
}
}
public void setVisible(boolean vis) {
visible = vis;
}
public void setColor(Color c) {
color = c;
}
public boolean checkCollide(OnScreenObject other) {
if (other.getYMax() < getYMin()) { //if other object is above this
return false;
}
if (other.getYMin() > getYMax()) {//if other object is below this
return false;
}
if (other.getXMax() < getXMin()) {//if other is to the left
return false;
}
if (other.getXMin() > getXMax()) {//if other is to the right
return false;
}
return true;
}
public void move() {
if (!allowedOffscreen) {
checkEdge();
}
xmin += run;
ymin += rise;
}
protected abstract void checkEdge();
}
The interactivePanel class is the one that extends JPanel:
package mikeengine;
import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.JPanel;
public class interactivePanel extends JPanel {
ArrayList<OnScreenObject> objects;
IClick myClick;
Ipress myType;
PlayerShip currentShip;
interactivePanel() {
objects = new ArrayList<>();
myClick = new IClick();
myType = new Ipress();
this.addMouseListener(myClick);
this.addKeyListener(myType);
}
#Override
public void paintComponent(Graphics g) {
System.out.println("painting");
paintBackground(g);
paintObjects(g);
checkClick();
checkPress();
}
public void move() {
System.out.println("here2");
checkDeadShip();//also sets current ship
moveObjects();//also removes invisible
checkCollisions();
} // end method move
private void checkClick() {
if (!myClick.getClicked()) {
return;
}
for (int i = 0; i < objects.size(); i++) {
OnScreenObject current = objects.get(i);
if (current.isWithin(myClick.getX(), myClick.getY())) {
System.out.println("CLICKED");
}
}
}
private void paintBackground(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
}
private void paintObjects(Graphics g) {
for (int i = 0; i < objects.size(); i++) {
OnScreenObject current = objects.get(i);
g.setColor(current.getColor());
g.fillOval(current.getXMin(), current.getYMin(), current.getXSize(), current.getYSize());
}
}
public void addObject(OnScreenObject toAdd) {
objects.add(toAdd);
}
private void checkPress() {
if (myType.getDown()) {
objects.get(0).nudge(false, 3);
}
if (myType.getUp()) {
objects.get(0).nudge(false, -3);
}
if (myType.getLeft()) {
objects.get(0).nudge(true, -3);
}
if (myType.getRight()) {
objects.get(0).nudge(true, 3);
}
if (myType.getSpace()) {
fire();
}
}
private void fire() {
OnScreenObject shotBullet = new Bullet(currentShip.getXMax(), ((currentShip.getYMax() - currentShip.getYMin()) / 2) + currentShip.getYMin(), 5, getWidth(), 0, getHeight(), 0);
int shipBonus = 0;
if (currentShip.getRun() > 0) {
shipBonus = currentShip.getRun();
}
shotBullet.setMovement(0, shipBonus + 5);
addObject(shotBullet);
}
private void checkCollisions() {
for (int i = 0; i < objects.size() - 1; i++) {
for (int j = 0; j < objects.size(); j++) {
if (j != i) {
OnScreenObject current = objects.get(i);
OnScreenObject next = objects.get(j);
if (current.checkCollide(next)) {
objects.remove(i);
if (i < j) {
objects.remove(j - 1);
} else {
objects.remove(j);
}
}
}
}
}
}
private void checkDeadShip() {
if (objects.size() > 0) {
try {
currentShip = (PlayerShip) objects.get(0);
} catch (Exception e) {
System.out.println("GAME OVER!");
}
}
}
private void moveObjects() {
for (int i = 0; i < objects.size(); i++) {
OnScreenObject current = objects.get(i);
current.move();
if (!current.getVisible()) {
objects.remove(i);
}
}
}
}
if I do not have that line commented out, the
System.out.println("painting"); inside of my public void paintComponent(Graphics g) is never run, which is why I assume that paintComponent isn't running.
(I cant post images since I don't have 10 rep, but its just a JFrame with the beige empty panel look when it is not commented out).
EDIT:
In your setGraphic() method, replace the line
graphic = new ImageIcon("setto");
with this:
graphic = new ImageIcon(this.getClass()
.getResource(setto));