How to find out whether a shape has touch another shape? - java

I have a working class where I can move a circle around the screen using the keyboard while there are other circles moving across the screen at different speeds.
I reached this point, and I'm trying to figure out how to make it so that I can find out whether my shape has touched another shape, but that's the part I'm stuck at, as I don't have many ideas about how to make it work. I have tried various methods, but most of them don't work.
public class Test extends Panel implements Runnable, KeyListener, MouseMotionListener {
static final int left = 37;
static final int right = 39;
static final int down = 40;
static final int up = 38;
static boolean leftPress = false;
static boolean rightPress = false;
static boolean upPress = false;
static boolean downPress = false;
/*****/
static int upperLeftX;
static int upperLeftY;
static int lowerLeftX;
static int lowerLeftY;
static int upperRightX;
static int upperRightY;
static int lowerRightX;
static int lowerRightY;
int eUpperLeftX;
int eUpperLeftY;
int eLowerLeftX;
int eLowerLeftY;
int eUpperRightX;
int eUpperRightY;
int eLowerRightX;
int eLowerRightY;
/*****/
static boolean eat = false;
static boolean eaten = false;
static int mouseLocationX;
static int mouseLocationY;
static String mouseLocation = "";
/**/
int x1_;
int y1_;
int eSize;
int eRandSpawn;
int sleep;
Color eColor;
/**/
static int x1 = 250;
static int y1 = 250;
static int size = 30;
static JFrame frame = new JFrame("Fishy");
static Test panel = new Test(500, 500, 9);
// static Test time1 = new Test(1000);
// static Test time2 = new Test(500);
// static Test time3 = new Test(250);
// static Test time4 = new Test(Methods.randNum(6,20),Methods.randNum(0, 450));
// static Test time5 = new Test(Methods.randNum(6,20),Methods.randNum(0, 450));
static Test eFish[] = new Test[20];
/** CONSTRUCTOR **/
public Test() {
sleep = Methods.randNum(6, 50);
y1_ = Methods.randNum(0, 450);
eRandSpawn = Methods.randNum(1, 2);
eColor = Methods.randColor();
eSize = Methods.randNum(5, 120);
if (eRandSpawn == 1) {
x1_ = -100;
} else {
x1_ = 600;
}
eUpperLeftX = x1_;
eUpperLeftY = y1_;
eLowerLeftX = x1_;
eLowerLeftY = y1_ + eSize;
eUpperRightX = x1_ + eSize;
eUpperRightY = y1_;
eLowerRightX = x1_ + eSize;
eLowerRightY = x1_ + eSize;
}
/** CONSTRUCTOR **/
public Test(int width, int length, int minusBy) {
super(width, length, minusBy);
}
/** MAIN **/
public static void main(String args[]) throws InterruptedException {
for (int i = 0; i < 20; i++) {
eFish[i] = new Test();
}
Thread time[] = new Thread[20];
for (int i = 0; i < 20; i++) {
time[i] = new Thread(eFish[i]);
}
// Thread time1_ = new Thread(time1);
// Thread time2_ = new Thread(time2);
// Thread time3_ = new Thread(time3);
// Thread time4_ = new Thread(time4);
// Thread time5_ = new Thread(time5);
frame.add(panel);
frame.addKeyListener(panel);
panel.addMouseMotionListener(panel);
Frame.showFrame(frame);
// time1_.start();
// time2_.start();
// time3_.start();
// time4_.start();
// time5_.start();
for (int i = 0; i < 20; i++) {
time[i].start();
}
while (true) {
if (upPress) {
y1--;
}
if (downPress) {
y1++;
}
if (leftPress) {
x1--;
}
if (rightPress) {
x1++;
}
if (upPress || downPress || leftPress || rightPress) {
upperLeftX = x1;
upperLeftY = y1;
lowerLeftX = x1;
lowerLeftY = y1 + size;
upperRightX = x1 + size;
upperRightY = y1;
lowerRightX = x1 + size;
lowerRightY = x1 + size;
Thread.sleep(6);
frame.repaint();
}
for (int i = 0; i < 20; i++) {
if (eat) {
size++;
eFish[i].eRandSpawn = Methods.randNum(1, 2);
if (eFish[i].eRandSpawn == 1) {
eFish[i].y1_ = Methods.randNum(0, 450);
eFish[i].x1_ = -100;
eFish[i].sleep = Methods.randNum(6, 50);
eFish[i].eSize = Methods.randNum(5, 120);
eFish[i].eColor = Methods.randColor();
} else {
eFish[i].y1_ = Methods.randNum(0, 450);
eFish[i].x1_ = 600;
eFish[i].sleep = Methods.randNum(6, 50);
eFish[i].eSize = Methods.randNum(5, 120);
eFish[i].eColor = Methods.randColor();
}
eFish[i].eUpperLeftX = eFish[i].x1_;
eFish[i].eUpperLeftY = eFish[i].y1_;
eFish[i].eLowerLeftX = eFish[i].x1_;
eFish[i].eLowerLeftY = eFish[i].y1_ + eFish[i].eSize;
eFish[i].eUpperRightX = eFish[i].x1_ + eFish[i].eSize;
eFish[i].eUpperRightY = eFish[i].y1_;
eFish[i].eLowerRightX = eFish[i].x1_ + eFish[i].eSize;
eFish[i].eLowerRightY = eFish[i].x1_ + eFish[i].eSize;
}
eat = false;
}
}
}
/** PAINT **/
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.CYAN);
g.fillRect(0, 0, 501, 501);
g.setColor(Color.BLACK);
mouseLocation = String.format("%s,%s,%s", x1, y1, size);
g.drawString(mouseLocation, 100, 100);
g.setColor(Color.GREEN);
g.fillOval(x1, y1, size, size);
// g.drawOval(time4.x1_,time4.y1_,50,50);
// g.drawOval(time5.x1_,time5.y1_,50,50);
for (int i = 0; i < 20; i++) {
g.setColor(eFish[i].eColor);
g.fillOval(eFish[i].x1_, eFish[i].y1_, eFish[i].eSize, eFish[i].eSize);
}
/*
* for (int i = 0; i < 10; i++) { g.setColor(Methods.randColor()); g.drawRect(x1 + i, y1 + i, width - i * 2, height - i * 2);
*
* }
*/
// g.drawString(time1.time, 20, 50);
// g.drawString(time2.time, 20, 100);
// g.drawString(time3.time, 20, 150);
}
#Override
public void run() {
while (true) {
try {
Thread.sleep(sleep);
eUpperLeftX = x1_;
eUpperLeftY = y1_;
eLowerLeftX = x1_;
eLowerLeftY = y1_ + eSize;
eUpperRightX = x1_ + eSize;
eUpperRightY = y1_;
eLowerRightX = x1_ + eSize;
eLowerRightY = x1_ + eSize;
if (x1_ == -150) {
y1_ = Methods.randNum(0, 450);
x1_ = 600;
sleep = Methods.randNum(6, 50);
eSize = Methods.randNum(5, 120);
eColor = Methods.randColor();
}
if (x1_ == 650) {
y1_ = Methods.randNum(0, 450);
x1_ = -100;
sleep = Methods.randNum(6, 50);
eSize = Methods.randNum(5, 120);
eColor = Methods.randColor();
}
if (eRandSpawn == 1) {
x1_++;
} else {
x1_--;
}
frame.repaint();
} catch (InterruptedException e) {
}
}
}
#Override
public void keyPressed(KeyEvent e) {
if (up == e.getKeyCode()) {
upPress = true;
}
if (down == e.getKeyCode()) {
downPress = true;
}
if (left == e.getKeyCode()) {
leftPress = true;
}
if (right == e.getKeyCode()) {
rightPress = true;
}
}
#Override
public void keyReleased(KeyEvent e) {
if (up == e.getKeyCode()) {
upPress = false;
}
if (down == e.getKeyCode()) {
downPress = false;
}
if (left == e.getKeyCode()) {
leftPress = false;
}
if (right == e.getKeyCode()) {
rightPress = false;
}
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseMoved(MouseEvent e) {
mouseLocationX = e.getX();
mouseLocationY = e.getY();
mouseLocation = String.format("%s,%s", mouseLocationX, mouseLocationY);
frame.repaint();
}
}

public boolean madeContact(Ellipse a, Ellipse b) {
//Center of ellipse
int ax = a.getX(), ay = a.getY(), bx = b.getX(), by = b.getY();
//Radii
int arx = a.getRadiusX(), ary = a.getRadiusY();
int brx = b.getRadiusX(), bry = b.getRadiusY();
//Has hit x, y
boolean hitx = Math.abs(ax - bx) < arx+brx;
boolean hity = Math.abs(ay - by) < ary+bry;
return hitx && hity;
}

Related

Faulty code from book on viewing bubble sort

I am running example code from this book, Data Structures and Algorithms in Java (2nd Edition) - LaFore, that is not behaving as expected. In the third chapter there is example code for running a visual on bubble sorts. But the only button that works for the applet is "New" and "Step". I am trying to fix the code in IntelliJ but the breakpoints are getting a cancel feature. I am not sure if this means the code is never even run. How can I get the breakpoints to show up. Also look at the image.
BubbleSort.java
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.EventObject;
public class BubbleSort extends Applet
implements Runnable, ActionListener
{
public void init()
{
thePersonGroup = new groupBS(groupSize, order);
setLayout(new FlowLayout(2));
newButton = new Button("New");
add(newButton);
newButton.addActionListener(this);
sizeButton = new Button("Size");
add(sizeButton);
sizeButton.addActionListener(this);
drawButton = new Button("Draw");
add(drawButton);
drawButton.addActionListener(this);
runButton = new Button("Run");
add(runButton);
runButton.addActionListener(this);
stepButton = new Button("Step");
add(stepButton);
stepButton.addActionListener(this);
aWidth = thePersonGroup.getAppletWidth();
aHeight = thePersonGroup.getAppletHeight();
offscreenImage = createImage(aWidth, aHeight);
offscreenGraphics = offscreenImage.getGraphics();
thePersonGroup.setDrawMode(2);
runFlag = false;
}
public void paint(Graphics g)
{
thePersonGroup.draw(offscreenGraphics);
g.drawImage(offscreenImage, 0, 0, this);
}
public void update(Graphics g)
{
paint(g);
}
public void actionPerformed(ActionEvent actionevent)
{
if(actionevent.getSource() == newButton)
{
runFlag = false;
order = order != 1 ? 1 : 2;
thePersonGroup = new groupBS(groupSize, order);
} else
if(actionevent.getSource() == sizeButton)
{
runFlag = false;
groupSize = groupSize != 10 ? 10 : 100;
thePersonGroup = new groupBS(groupSize, order);
} else
if(actionevent.getSource() == drawButton)
{
runFlag = false;
thePersonGroup.setDrawMode(2);
} else
if(actionevent.getSource() == runButton)
runFlag = true;
else
if(actionevent.getSource() == stepButton)
{
runFlag = false;
thePersonGroup.sortStep();
thePersonGroup.setDrawMode(1);
}
repaint();
}
public void run()
{
for(Thread thread = Thread.currentThread(); runner == thread;)
if(runFlag && !thePersonGroup.getDone())
{
thePersonGroup.sortStep();
repaint();
thePersonGroup.setDrawMode(1);
int i = groupSize != 10 ? 75 : 250;
try
{
Thread.sleep(i);
}
catch(InterruptedException _ex) { }
}
}
public void start()
{
if(runner == null)
{
runner = new Thread(this);
runner.start();
}
}
public void stop()
{
runner = null;
}
public BubbleSort()
{
groupSize = 10;
order = 1;
}
private Image offscreenImage;
private Graphics offscreenGraphics;
private int aWidth;
private int aHeight;
private Thread runner;
private int groupSize;
private groupBS thePersonGroup;
private boolean runFlag;
private int order;
private Button newButton;
private Button sizeButton;
private Button drawButton;
private Button runButton;
private Button stepButton;
}
groupBS.java
import java.awt.Color;
import java.awt.Graphics;
class groupBS
{
public groupBS(int i, int j)
{
aSize = i;
initOrder = j;
theArray = new personBS[aSize];
if(aSize == 100)
{
barWidth = 2;
barSeparation = 1;
} else
{
barWidth = 20;
barSeparation = 10;
}
outer = aSize - 1;
inner = 0;
comps = 0;
swaps = 0;
swapFlag = false;
doneFlag = false;
drawMode = 2;
if(initOrder == 1)
{
for(int k = 0; k < aSize; k++)
{
int i1 = (int)(Math.random() * 199D);
int k1 = (int)(Math.random() * 254D);
int i2 = (int)(Math.random() * 254D);
int k2 = (int)(Math.random() * 254D);
newColor = new Color(k1, i2, k2);
theArray[k] = new personBS(i1, newColor);
}
return;
}
for(int l = 0; l < aSize; l++)
{
int j1 = 199 - (199 * l) / aSize;
int l1 = 255 - j1;
int j2 = 85 * (l % 3);
int l2 = j1;
newColor = new Color(l1, j2, l2);
theArray[l] = new personBS(j1, newColor);
}
}
public void setDrawMode(int i)
{
drawMode = i;
}
public int getAppletWidth()
{
return 370;
}
public int getAppletHeight()
{
return 320;
}
public boolean getDone()
{
return doneFlag;
}
public void arrowText(Graphics g, Color color, String s, int i, int j, boolean flag, boolean flag1)
{
int k = 35 + i * (barWidth + barSeparation);
int l = 230 + (j + 1) * 13;
g.setColor(color);
if(flag1)
g.drawString(s, k, l);
if(flag)
{
g.drawLine(k + barWidth / 2, 232, k + barWidth / 2, l - 13);
g.drawLine(k + barWidth / 2, 232, (k + barWidth / 2) - 3, 237);
g.drawLine(k + barWidth / 2, 232, k + barWidth / 2 + 3, 237);
}
}
public void drawOneBar(Graphics g, int i)
{
int j = theArray[i].getHeight();
int k = 35 + i * (barWidth + barSeparation);
int l = 230 - j;
Color color = theArray[i].getColor();
g.setColor(Color.lightGray);
g.fillRect(k, 30, barWidth, 200);
g.setColor(color);
g.fill3DRect(k, l, barWidth, j, true);
}
public void draw(Graphics g)
{
if(drawMode != 2)
{
if(swapFlag)
{
drawOneBar(g, innerOld);
drawOneBar(g, innerOld + 1);
swapFlag = false;
}
} else
{
g.setColor(Color.lightGray);
g.fillRect(0, 0, 370, 320);
for(int i = 0; i < aSize; i++)
drawOneBar(g, i);
}
g.setColor(Color.lightGray);
g.fillRect(0, 0, 150, 32);
g.setColor(Color.black);
g.drawString("Comparisons = " + comps, 10, 28);
g.drawString("Swaps = " + swaps, 10, 15);
g.setColor(Color.lightGray);
g.fillRect(0, 230, 370, 65);
if(aSize == 10)
{
arrowText(g, Color.red, "outer", outer, 3, true, true);
arrowText(g, Color.blue, "inner", inner, 1, true, true);
arrowText(g, Color.blue, "inner+1", inner + 1, 1, true, true);
if(doneFlag)
arrowText(g, Color.black, "Sort is complete", inner, 2, false, true);
else
if(theArray[inner].getHeight() > theArray[inner + 1].getHeight())
arrowText(g, Color.blue, "Will be swapped", inner, 2, false, true);
else
arrowText(g, Color.blue, "Will not be swapped", inner, 2, false, true);
} else
{
arrowText(g, Color.red, "xxx", outer, 3, true, false);
arrowText(g, Color.blue, "xxx", inner, 1, true, false);
arrowText(g, Color.blue, "xxx", inner + 1, 1, true, false);
}
drawMode = 2;
}
public void sortStep()
{
if(doneFlag)
return;
comps++;
if(theArray[inner].getHeight() > theArray[inner + 1].getHeight())
{
swap(inner, inner + 1);
swapFlag = true;
swaps++;
}
innerOld = inner;
inner++;
if(inner > outer - 1)
{
inner = 0;
outer--;
if(outer == 0)
doneFlag = true;
}
}
public void swap(int i, int j)
{
personBS personbs = theArray[i];
theArray[i] = theArray[j];
theArray[j] = personbs;
}
private final int appletWidth = 370;
private final int appletHeight = 320;
private final int maxHeight = 200;
private final int topMargin = 30;
private final int leftMargin = 10;
private final int barLeftMargin = 35;
private final int textHeight = 13;
private int aSize;
private personBS theArray[];
private int barWidth;
private int barSeparation;
private int outer;
private int inner;
private int innerOld;
private boolean swapFlag;
private boolean doneFlag;
private int comps;
private int swaps;
private int initOrder;
Color newColor;
private int drawMode;
}
personBS.java
import java.awt.Color;
class personBS
{
public Color getColor()
{
return color;
}
public int getHeight()
{
return height;
}
public personBS(int i, Color color1)
{
height = i;
color = color1;
}
private int height;
private Color color;
}

Drawing and dragging lines using paintComponent without inflicting with any other GUI components within a JPanel [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
For my binary tree program, I have been using JTextFields as nodes and I have managed to make it so when I click left button and select two of the JTextFields, it will draw a line between them. The problem is if I want to drag the JtextField around, I want the line to be following as well between two of the midpoints of the JTextField. I don't know if it's possible with using only paintComponent or not. I did try it but it's like a one off thing and it will leave a trail of all the previously drawn lines.
Here, is the code so far, there are other classes so some of the bits won't work. The code has been fiddled around a bit as well for testing.
public class BinaryTreeMainPnl extends JPanel {
public static Graphics g1;
public int Width = 75;
public int Height = 45;
public String tempNode1 = "";
public int tempNode1Pos = 0;
public int tempNode2Pos = 0;
public String tempNode2 = "";
public static boolean leftBtnSelected;
public static boolean rightBtnSelected;
private static int x1, y1 = 50;
private static int x2, y2 = 500;
JToggleButton leftBtn = new JToggleButton("Left");
JToggleButton rightBtn = new JToggleButton("Right");
JTextField[] myArray = new JTextField[60];
ArrayList<String> nodeNames = new ArrayList<String>();
JFrame MainFrame;
JTextField txtFld1 = new JTextField("Enter Questions here");
JButton btn1 = new JButton("Submit");
public BinaryTreeMainPnl(JFrame frame) {
super();
setSize(800, 700);
MainFrame = frame;
readInput();
leftBtn.setFont(new Font("Arial", Font.BOLD, 15));
leftBtn.setForeground(Color.blue);
leftBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
rightBtn.setSelected(false);
leftBtnSelected = leftBtn.getModel().isSelected();
rightBtnSelected = false;
System.out.println(leftBtnSelected);
System.out.println(rightBtnSelected);
}
});
add(leftBtn);
rightBtn.setFont(new Font("Arial", Font.BOLD, 15));
rightBtn.setForeground(Color.green);
rightBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
leftBtn.setSelected(false);
rightBtnSelected = rightBtn.getModel().isSelected();
leftBtnSelected = false;
System.out.println(leftBtnSelected);
System.out.println(rightBtnSelected);
}
});
add(rightBtn);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
updateLine(g);
}
public void readInput() {
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
identifyNodeNames(txtFld1.getText());
displayNodes(nodeNames);
new TreeSorting().treeSort(nodeNames);
}
});
this.add(txtFld1);
this.add(btn1);
}
public void displayNodes(ArrayList<String> nodeNames) {
for (int i = 0; i < nodeNames.size(); i++) {
String currentSetText = nodeNames.get(i);
myArray[i] = new JTextField(currentSetText);
myArray[i].setEditable(false);
}
for (int i = 0; i < nodeNames.size(); i++) {
int I = i;
myArray[I].addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent evt) {
int x = evt.getX() + myArray[I].getX();
int y = evt.getY() + myArray[I].getY();
myArray[I].setBounds(x, y, myArray[I].getWidth(), myArray[I].getWidth());
System.out.println(myArray[I] + "dragged");
}
});
myArray[I].addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent evt) {
if (leftBtnSelected) {
if (tempNode1.equals("")) {
tempNode1 = myArray[I].getText();
System.out.println(tempNode1 + "clicked");
} else {
tempNode2 = myArray[I].getText();
System.out.println(tempNode2 + "Clicked as well");
leftBtn.setSelected(false);
leftBtnSelected = false;
x1 = 40;
y1 = 40;
x2 = 400;
y2 = 400;
updateLine(g1);
System.out.println("asdasd");
}
}
if (rightBtnSelected) {
}
}
public void moveComponent(MouseEvent evt) {
}
});
System.out.println("I " + I);
System.out.println(myArray[I].getText());
add(myArray[I]);
}
MainFrame.revalidate();
}
public int findMidPoint(JTextField temp) {
Point p = temp.getLocation();
Dimension d = temp.getSize();
return p.x + (d.width) / 2;
}
int coun = 0;
public void updateLine(Graphics g) {
g.drawLine(x1, x2, y1, y2);
x1 = x1 + 10;
y1 = y1 + 10;
y2 = y2 + 10;
x2 = x2 + 10;
System.out.println("Line Updated" + coun);
coun++;
}
public void identifyNodeNames(String answer) {
int arrayCounter = 0;
int lastNodePosition = 0;
for (int i = 0; i < answer.length(); i++) {
char c = answer.charAt(i);
if (c == ',') {
nodeNames.add(arrayCounter, answer.substring(lastNodePosition, i + 1).replaceAll(",", "").replaceAll(" ", ""));
lastNodePosition = i + 1;
arrayCounter++;
}
if (i == answer.length() - 1) {
nodeNames.add(arrayCounter, answer.substring(lastNodePosition, answer.length()).replaceAll(" ", ""));
}
}
}
}
import java.util.ArrayList;
public class TreeSorting {
public static int arrayLength;
String[][] Child;
String root = "";
boolean nodeSorted = false;
int parentCounter = 1;
public void treeSort(ArrayList<String> passedQuestions) {
// declaring nodes
arrayLength = passedQuestions.size();
System.out.println(arrayLength + "ARRAY LENGTH");
Child = new String[arrayLength][3];
for (int i = 0; i < arrayLength; i++) {
Child[i][0] = passedQuestions.get(i);
}
//initially calling the mainprocess with parentCounter 1;
root = Child[0][0];
mainProcess(1);
}
public void mainProcess(int parentCounter) {
if (parentCounter < Child.length) {
System.out.println(parentCounter);
sortingTree(Child[parentCounter][0], root, 0); //where the next node is passed on the tree is sorted recursively
for (int i = 0; i < Child.length; i++) {
System.out.println(Child[i][0]);
System.out.println(Child[i][1] + "," + Child[i][2]);
}
}
}
public void sortingTree(String CurrentNode, String PreviousNode, int PreviousPosition) {
nodeSorted = false;// node is not sorted in the beginning
if (isAfter(CurrentNode.toLowerCase(), PreviousNode.toLowerCase())) {
System.out.println(Child[PreviousPosition][2]);
if (Child[PreviousPosition][2] == null) { //checks if the right of the node is empty, if found empty the node is placed there.
Child[PreviousPosition][2] = CurrentNode;
nodeSorted = true; // if the node finds a position in the array node is sorted.
} else {
sortingTree(CurrentNode, Child[PreviousPosition][2], getPositionInArray(Child[PreviousPosition][2]));
//if the array position was not empty, the loop will process again this time with the item found in the filled position.
}
} else if (Child[PreviousPosition][1] == null) { // if the left of the node is empty, the item will be placed there
Child[PreviousPosition][1] = CurrentNode;
nodeSorted = true;
} else {
sortingTree(CurrentNode, Child[PreviousPosition][1], getPositionInArray(Child[PreviousPosition][1]));
//if the array position was not empty, the loop will process again this time with the item found in the filled position.
}
if (nodeSorted) { // if the node finds a position in the array, the nodeCounter increments and the next node in the question is processed.
parentCounter++;
mainProcess(parentCounter);
}
}
public int getPositionInArray(String node) {
int position = 0;
loop:
for (int i = 0; i < Child.length; i++) {
if (Child[i][0].equals(node)) {
position = i;
break loop;
}
}
return position;
}
public boolean isAfter(String CurrentNode, String PreviousNode) {
int loopLength = determineLoopLength(CurrentNode, PreviousNode);
boolean result = false;
String tempCheck = "";
loop:
for (int i = 0; i < loopLength; i++) {
if ((int) CurrentNode.charAt(i) > (int) PreviousNode.charAt(i)) {
result = true;
break loop;
}
if ((int) CurrentNode.charAt(i) < (int) PreviousNode.charAt(i)) {
result = false;
break loop;
} else if (CurrentNode.charAt(i) == PreviousNode.charAt(i) && CurrentNode.length() > PreviousNode.length()) {
System.out.println("I'm here");
tempCheck = tempCheck + CurrentNode.charAt(i) + "";
if (i == loopLength - 1 && tempCheck.equals(PreviousNode)) {
result = true;
break loop;
}
}
}
return result;
}
public int determineLoopLength(String CurrentNode, String PreviousNode) {
int loopLength = 0;
if (CurrentNode.length() < PreviousNode.length()) {
loopLength = CurrentNode.length();
}
if (PreviousNode.length() < CurrentNode.length()) {
loopLength = PreviousNode.length();
} else {
loopLength = CurrentNode.length();
}
return loopLength;
}
}
WTF, been working on this,.....
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class DragMyFields extends JPanel {
private static final int PREF_W = 1000;
private static final int PREF_H = 800;
private static final int COLS = 8;
private static final int DELTA_Y = 120;
private static final int MAX_DEPTH = 3;
private MySimpleTreeNode<JTextField> treeRoot = new MySimpleTreeNode<>();
private MyMouse myMouse = new MyMouse();
public DragMyFields() {
setLayout(null); // this is *** BAD ***
// much better would be to create a custom layout
JTextField field = new JTextField(COLS);
field.addMouseListener(myMouse);
field.addMouseMotionListener(myMouse);
field.setSize(field.getPreferredSize());
int x = (PREF_W - field.getPreferredSize().width) / 2;
int y = DELTA_Y;
field.setLocation(x, y);
add(field);
treeRoot.setNode(field);
recursiveCreateTree(treeRoot, MAX_DEPTH, x, y);
}
private void recursiveCreateTree(MySimpleTreeNode<JTextField> node, int depth, int x, int y) {
if (depth == 0) {
return;
}
JTextField leftField = new JTextField(COLS);
JTextField rightField = new JTextField(COLS);
MySimpleTreeNode<JTextField> leftNode = new MySimpleTreeNode<>(leftField);
MySimpleTreeNode<JTextField> rightNode = new MySimpleTreeNode<>(rightField);
node.setLeft(leftNode);
node.setRight(rightNode);
int multiplier = 4;
for (int i = 0; i < MAX_DEPTH - depth; i++) {
multiplier *= 2;
}
int xL = x - getPreferredSize().width / multiplier;
int xR = x + getPreferredSize().width / multiplier;
y += DELTA_Y;
leftField.setSize(leftField.getPreferredSize());
rightField.setSize(rightField.getPreferredSize());
leftField.setLocation(xL, y);
rightField.setLocation(xR, y);
leftField.addMouseListener(myMouse);
leftField.addMouseMotionListener(myMouse);
rightField.addMouseListener(myMouse);
rightField.addMouseMotionListener(myMouse);
add(leftField);
add(rightField);
recursiveCreateTree(leftNode, depth - 1, xL, y);
recursiveCreateTree(rightNode, depth - 1, xR, y);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
recursiveDraw(g, treeRoot);
}
private void recursiveDraw(Graphics g, MySimpleTreeNode<JTextField> node) {
MySimpleTreeNode<JTextField> left = node.getLeft();
MySimpleTreeNode<JTextField> right = node.getRight();
Point p = getNodeCenter(node);
if (left != null) {
Point p2 = getNodeCenter(left);
g.drawLine(p.x, p.y, p2.x, p2.y);
recursiveDraw(g, left);
}
if (right != null) {
Point p2 = getNodeCenter(right);
g.drawLine(p.x, p.y, p2.x, p2.y);
recursiveDraw(g, right);
}
}
private Point getNodeCenter(MySimpleTreeNode<JTextField> node) {
JTextField field = node.getNode();
Point location = field.getLocation();
Dimension size = field.getSize();
return new Point(location.x + size.width / 2, location.y + size.height / 2);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class MyMouse extends MouseAdapter {
Component source = null;
private Point pressedP;
private Point pressedLoc;
private Point parentP;
#Override
public void mousePressed(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
source = e.getComponent();
parentP = source.getParent().getLocationOnScreen();
pressedLoc = source.getLocationOnScreen();
pressedP = e.getLocationOnScreen();
}
#Override
public void mouseReleased(MouseEvent e) {
moveComponent(e);
source = null;
pressedP = null;
pressedLoc = null;
}
#Override
public void mouseDragged(MouseEvent e) {
if (source == null) {
return;
}
moveComponent(e);
}
private void moveComponent(MouseEvent e) {
Point p = e.getLocationOnScreen();
int x = pressedLoc.x + p.x - pressedP.x - parentP.x;
int y = pressedLoc.y + p.y - pressedP.y - parentP.y;
Point newP = new Point(x, y);
source.setLocation(newP);
repaint();
}
}
private static void createAndShowGui() {
DragMyFields mainPanel = new DragMyFields();
JFrame frame = new JFrame("DragMyFields");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
}
class MySimpleTreeNode<T> {
private T node;
private MySimpleTreeNode<T> left;
private MySimpleTreeNode<T> right;
public MySimpleTreeNode() {
// default constructor
}
public MySimpleTreeNode(T node) {
this.node = node;
}
public void setNode(T node) {
this.node = node;
}
public T getNode() {
return node;
}
public MySimpleTreeNode<T> getLeft() {
return left;
}
public void setLeft(MySimpleTreeNode<T> left) {
this.left = left;
}
public MySimpleTreeNode<T> getRight() {
return right;
}
public void setRight(MySimpleTreeNode<T> right) {
this.right = right;
}
}

How to fix multiple threads running in java awt graphics

I am programming a game for a school project and when I run the code, it works sometimes and then ill run it again and the paddle or ball won't move and the print statements in my keylistener dont show up.
Now I am running two timers, one for the animation and one for a countdown, could this be an issue? It seems like multiple threads are running or when I close the jframe and then rerun the program is picking up where it left off?
public class LobPong extends JPanel implements KeyListener {
public static double xCoordinate;
public static double yCoordinate;
public static Timer timer;
static int xPaddleLeft;
private static int yPaddle = 800;
private static int score = 0;
private static int level = 1;
public static JLabel scoreLabel = new JLabel(" Score: 0 ");
public static JLabel timeLabel = new JLabel(" ");
public static JLabel levelLabel = new JLabel(" Level: ");
private static int life = 3;
private static int levelTime = 30000;
public static int dx, dy;
private static double times = 0;
public static void main(String[] args) {
JFrame LobPongApp = new JFrame();
LobPong canvas = new LobPong();
canvas.setBackground(Color.BLUE);
LobPongApp.add(canvas);
LobPongApp.setSize(800, 900);
LobPongApp.setTitle("Lob Pong");
LobPongApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
LobPongApp.setVisible(true);
canvas.setFocusable(true);
LobPongApp.addKeyListener(canvas);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillOval((int) xCoordinate, (int) yCoordinate, 50, 50);
g.fillRect(xPaddleLeft, yPaddle, 100, 10);
drawLife(g, getLife());
}
public LobPong() {
timer = new Timer(1, new timerCallBack());
timer.start();
setLayout(new FlowLayout());
scoreLabel.setOpaque(true);
timeLabel.setOpaque(true);
levelLabel.setOpaque(true);
scoreLabel.setBackground(Color.black);
timeLabel.setBackground(Color.black);
levelLabel.setBackground(Color.black);
scoreLabel.setForeground(Color.WHITE);
timeLabel.setForeground(Color.WHITE);
levelLabel.setForeground(Color.WHITE);
levelLabel.setText("Level: " + 1);
add(scoreLabel);
add(timeLabel);
add(levelLabel);
xPaddleLeft = 375; //debug
xCoordinate = 0;
yCoordinate = 0;
setTime(levelTime); //sets current level time (increases by 10 seconds every 2 levels)
}
public static void nextLevel(Graphics g, int levels) {
level += 1;
g.drawString("NEXT LEVEL!", 400, 400);
timer.stop();
//TODO call run() ?
}
public static void updateScore(int scoreAdd) {
score += scoreAdd;
scoreLabel.setText("Score: " + score);
}
public static int getScore() {
return score;
}
public static void updateLife(int x) {
life += x;
}
public static int getLife() {
return life;
}
public static void drawLife(Graphics g, int x) {
g.setColor(Color.RED);
for(int i = 0; i < (x * 10); i += 10) { //for loop to offset lives and draw enough balls per lives
g.fillOval(30 + i, 10, 10, 10);
}
}
public static void extraLife(boolean x) {
if (x == true) {
updateLife(1);
}
}
Timer timerDisplay = new Timer(1000, new TimerListener());
private static int totalTime;
public static void setTime(int time) {
totalTime = time;
}
public static int getTime() {
return totalTime;
}
protected class TimerListener implements ActionListener { //handles countdown timer
#Override
public void actionPerformed(ActionEvent arg0) {
setTime(getTime() - 1000);
LobPong.timeLabel.setText("Time Remaining: " + getTime()/1000 + " ");
if(getTime() <= 0) {
timerDisplay.stop();
timer.stop();
}
}
}
public void keyPressed(KeyEvent arg0) {
int key = arg0.getKeyCode();
System.out.println("testing");
if(key == 37) {
if (xPaddleLeft > 0) {
xPaddleLeft -= 50;
System.out.println("TEST"); //debug
}
}
if(key == 39) {
if (xPaddleLeft < (getWidth() - 50)) {
xPaddleLeft += 50;
}
}
if(key == KeyEvent.VK_ENTER) {
dx = 2;
timer.start();
timerDisplay.start();
System.out.println("start"); //debug
}
repaint();
}
boolean horizontal = true; //handles horizontal movement
boolean vertical = true; //handles vertical
double upwards;
public class timerCallBack implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
times += .01;
if (horizontal == true) { //check
xCoordinate += dx;
}
if(xCoordinate <= 0) { //check
horizontal = true;
}
if(xCoordinate >= getWidth()) { //check
horizontal = false;
}
if(horizontal == false) { //check
xCoordinate -= dx;
}
if(vertical == true) { //check
dy = (int) times;
yCoordinate += dy;
}
if (vertical == false) { //check
dy = (int) (upwards - times);
yCoordinate -= dy;
}
if(dy == 0) { //check
vertical = true;
times = 0;
}
if(yCoordinate == getHeight()) { //check
updateLife(-1);
if (getLife() == 0) {
timer.stop();
timerDisplay.stop();
//TODO you lose and print high score
}
extraLife(false);
xCoordinate = 0;
yCoordinate = 0;
dy = 0;
dx = 0;
vertical = true;
}
if(xCoordinate <= (xPaddleLeft + 100) && xCoordinate >= xPaddleLeft && (yCoordinate + 50) == yPaddle) {
upwards = times;
times = 0;
vertical = false;
updateScore(1);
repaint();
//TODO plus one point, paddle bounce physics, direction
}
repaint();
}
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}

How do I add a score counter to this snake game?

I want to be able to display the score to players, and have the score go up by 10 every time you get an apple. To do this though, I need to add extra space on the window to allow room for the score counter, but I can't find where to do that in my code.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JPanel;
public class Screen extends JPanel implements Runnable {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 800, HEIGHT = 900;
private Thread thread;
private boolean running = false;
private BodyPart b;
private ArrayList<BodyPart> snake;
private Apple apple;
private ArrayList<Apple> apples;
private Random r;
private int xCoor = 20, yCoor = 20;
private int size = 10;
private boolean right = true, left = false, up = false, down = false;
private int ticks = 0;
private Key key;
public Screen() {
setFocusable(true);
key = new Key();
addKeyListener(key);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
r = new Random();
snake = new ArrayList<BodyPart>();
apples = new ArrayList<Apple>();
start();
}
public void reset() {
snake.clear();
apples.clear();
xCoor = 20;
yCoor = 20;
size = 10;
running = true;
}
public void tick() {
if(snake.size() == 0) {
b = new BodyPart(xCoor, yCoor, 20);
snake.add(b);
}
if(apples.size() == 0) {
int xCoor = r.nextInt(40);
int yCoor = r.nextInt(40);
apple = new Apple(xCoor, yCoor, 20);
apples.add(apple);
}
for(int i = 0; i < apples.size(); i++) {
if(xCoor == apples.get(i).getxCoor() && yCoor == apples.get(i).getyCoor()) {
size++;
apples.remove(i);
i--;
}
}
for(int i = 0; i < snake.size(); i++) {
if(xCoor == snake.get(i).getxCoor() && yCoor == snake.get(i).getyCoor()) {
if(i != snake.size() - 1) {
reset();
}
}
}
if(xCoor < 0) xCoor = 40;
if(xCoor > 40) xCoor = 0;
if(yCoor < 0) yCoor = 40;
if(yCoor > 40) yCoor = 0;
ticks++;
if(ticks > 250000) {
if(right) xCoor++;
if(left) xCoor--;
if(up) yCoor--;
if(down) yCoor++;
ticks = 185000;
b = new BodyPart(xCoor, yCoor, 20);
snake.add(b);
if(snake.size() > size) {
snake.remove(0);
}
}
}
public void paint(Graphics g) {
g.clearRect(0, 0, WIDTH, HEIGHT);
g.setColor(new Color(20, 50, 0));
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.BLACK);
for(int i = 0; i < WIDTH / 20; i++) {
g.drawLine(i * 20, 0, i * 20, HEIGHT);
}
for(int i = 0; i < HEIGHT / 20; i++) {
g.drawLine(0, i * 20, WIDTH, i * 20);
}
for(int i = 0; i < snake.size(); i++) {
snake.get(i).draw(g);
}
for(int i = 0; i < apples.size(); i++) {
apples.get(i).draw(g);
}
}
public void start() {
running = true;
thread = new Thread(this, "Game Loop");
thread.start();
}
public void stop() {
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
while(running) {
tick();
repaint();
}
}
private class Key implements KeyListener {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_RIGHT && !left) {
up = false;
down = false;
right = true;
}
if(key == KeyEvent.VK_LEFT && !right) {
up = false;
down = false;
left = true;
}
if(key == KeyEvent.VK_UP && !down) {
left = false;
right = false;
up = true;
}
if(key == KeyEvent.VK_DOWN && !up) {
left = false;
right = false;
down = true;
}
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
Add a label on the jPanel
or add string inside your paint() method
g.drawString("Score: " + intScore, 10, 10);

How to check if the screen has not been touched

I have a game that displays circles randomly on the screen. The circles can be green or red at random. If you touch a red circle something happens; if you touch a green circle something happens; but what if you wanted to check if the green circle was displayed and a user did not click it? Here is my code:
public class DrawingView extends View{
public DrawingView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
RectF rectf = new RectF(0, 0, 200, 0);
private static final int w = 100;
public static int lastColor = Color.BLACK;
private final Random random = new Random();
private final Paint paint = new Paint();
private final int radius = 230;
private final Handler handler = new Handler();
public static int redColor = Color.RED;
public static int greenColor = Color.GREEN;
int randomWidth = 0;
int randomHeight = 0;
public static int addPoints = 0;
public static int savedScore;
public static List<String> a = new ArrayList<String>();
public static String[] savedScores = new String[a.size()];
Paint red;
public static int howManyPoints;
public static int highestScore = 0;
boolean isTouched;
Thread newThread = new Thread();
private final Runnable updateCircle = new Runnable() {
#Override
public void run() {
lastColor = random.nextInt(2) == 1 ? redColor : greenColor;
paint.setColor(lastColor);
if(lastColor == greenColor){
isTouched = false;
}
if(addPoints < 10){
handler.postDelayed(this, 850);
}
if(addPoints > 9 && addPoints < 30){
handler.postDelayed(this,700);
}
if(addPoints > 29){
handler.postDelayed(this, 600);
}
if(addPoints > 50){
handler.postDelayed(this, 450);
}
if(addPoints > 100){
handler.postDelayed(this, 400);
}
postInvalidate();
}
};
public void what(){
try {
newThread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(isTouched == false){
howManyPoints = addPoints;
handler.removeCallbacks(updateCircle);
lastColor = redColor;
addPoints = 0;
Intent i = new Intent(this.getContext(), YouFailed.class);
this.getContext().startActivity(i);
}
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
handler.post(updateCircle);
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
handler.removeCallbacks(updateCircle);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// your other stuff here
Paint back = new Paint();
back.setColor(Color.BLACK);
Rect background = new Rect();
background.set(0, 0, canvas.getWidth(),canvas.getHeight() );
canvas.drawRect(background, back);
Paint newPaint = new Paint();
newPaint.setColor(Color.BLUE);
newPaint.setTextSize(60);
canvas.drawText("Beta v2", 10, 60, newPaint);
if(random == null){
randomWidth =(int) (random.nextInt(Math.abs(getWidth()-radius/2)) + radius/2f);
randomHeight = (random.nextInt((int)Math.abs((getHeight()-radius/2 + radius/2f))));
}else {
randomWidth =(int) (random.nextInt(Math.abs(getWidth()-radius/2)) + radius/2f);
randomHeight = (random.nextInt((int)Math.abs((getHeight()-radius/2 + radius/2f))));
}
canvas.drawCircle(randomWidth, randomHeight, radius, paint);
what();
red = new Paint();
red.setColor(Color.BLUE);
red.setTextSize(150);
canvas.drawText("" + addPoints, 500, 1350, red);
}
#SuppressWarnings("deprecation")
#Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
int x = (int) event.getX();
int y = (int) event.getY();
if(isInsideCircle(x, y) == true){
//Do your things here
if(lastColor == redColor){
//saveScore();
howManyPoints = addPoints;
if(howManyPoints > highestScore){
highestScore = howManyPoints;
}
handler.removeCallbacks(updateCircle);
lastColor = redColor;
addPoints = 0;
Intent i = new Intent(this.getContext(), YouFailed.class);
this.getContext().startActivity(i);
}
if(lastColor == greenColor){
addPoints++;
isTouched = true;
}
}else {
}
}
return false;
}
public void saveScore() {
a.add("" + addPoints);
//if(Integer.parseInt(savedScores[1]) < addPoints){
//savedScores[2] = savedScores[1];
//int x = Integer.parseInt(savedScores[1]);
//x = addPoints;
//}
}
public boolean isInsideCircle(int x, int y){
if ((((x - randomWidth)*(x - randomWidth)) + ((y - randomHeight)*(y - randomHeight))) < ((radius)*(radius))){
return true;
}
return false;
}
}
Just add a boolean hasBeenClicked that is false and becomes true when the user touches it

Categories

Resources