Finch robot programming - java

I am writing a program where I have to make my finch robot follow an object. I have written it so that the finch will begin by sensing objects around it once it has been tapped on the top. As soon as I tap the top and cover the sensors, a red light is supposed to turn on and it will follow the object in the direction of the covered sensor. While it is moving, it should be making a buzzing sound and have the light change from red to green. When I stop moving the object, the finch is supposed to turn it's nose back to red and wait until it is either tapped twice to end the program or until the object is moved for it to continue following. However, when I tap it, nothing happens.
Here is my code:
import edu.cmu.ri.createlab.terk.robot.finch.Finch;
public class FollowingAnObject
{
static Finch myF = new Finch();
public static void main(String[] args)
{
myF = new Finch();
}
public FollowingAnObject()
{
while (true)
{
//This begins the movement of the finch
if (myF.isTapped() == true && myF.isObstacleLeftSide() == true && myF.isObstacleRightSide() == true && myF.isObstacle() == true)
{
//LED colours are red, green and blue
myF.setLED(R,0,0);
myF.setWheelVelocities(velocityLeft, velocityRight);
//Triggers the RunAgain function to true so that the program does not stop in one run so that the Finch will continue to move
boolean RunAgain = true;
while(RunAgain)
{
//Calling the Move method for the Finch movements
Move();
//Inside the while, RunAgain loop , there is a conditional statement that makes the program terminate if the Finch has been tapped twice
if (myF.isTapped()==true && myF.isTapped()==true)
{
break;
}
}
}
}
}
// Method for all of the Finch movements
public static void Move()
{
if (myF.isObstacleRightSide() == false && myF.isObstacleLeftSide() == false && myF.isObstacle() == true)
{
MoveStraight();
}
else if (myF.isObstacleRightSide() == false && myF.isObstacleLeftSide() == true)
{
MoveLeft();
}
else if ( myF.isObstacleRightSide() == true && myF.isObstacleLeftSide() == false)
{
MoveRight();
}
else if (myF.isObstacleRightSide()==true && myF.isObstacleLeftSide()==true)
{
StopMoving();
}
}
//All of the variables have been declared
static int Buzz = 300;
static int BuzzDuration = 12;
static int R = 250;
static int G = 250;
static int velocityLeft = 150;
static int velocityRight = 150;
static int turnLeft = -50;
static int turnRight = -50;;
//If the finch is moving straight, the light will be green and both of the wheels will move at 150
public static void MoveStraight()
{
myF.setLED(0, G, 0);
myF.setWheelVelocities(velocityLeft, velocityRight);
myF.buzz(Buzz, BuzzDuration);
}
public static void MoveLeft()
{
//If the finch is moving left, the light will be green, the left wheel will move at -50 and the right wheel will move at 150
myF.setLED(0, G, 0);
myF.setWheelVelocities(turnLeft, velocityRight);
myF.buzz(Buzz, BuzzDuration);
}
public static void MoveRight()
//If the finch is moving right, the light will be green the left wheel will move at 150 and the right wheel will move at -50
{
myF.setLED(0, G, 0);
myF.setWheelVelocities(velocityLeft, turnRight);
myF.buzz(Buzz, BuzzDuration);
}
public static void StopMoving()
//if the Finch is not moving, the colour of the light will be red and the buzzing will stop
{
myF.setLED(R, 0 , 0);
myF.stopWheels();
myF.buzz(Buzz, BuzzDuration);
}
}

Your main method is empty. Java starts at main, so you need to start your new Finch in main.

Related

Making a action/variable change only happen once, everytime a key is pressed

I wrote code that is supposed to remove 25 HP (health points) each time a rectangle (created by pressing the m key) intersects another rectangle, the enemy. Currently, the enemy looses 25HP continuously after I've pressed the m key only once until I press the m key again outside of the enemy body.
This is my damage code for the enemy. It turns white when killed, that's why I have df1 etc. there.
void damage() {
//if (callMethod) {
HP -=25;
//callMethod = false;
System.out.println(" " + HP);
//}
if (HP == 0) {
df1 = 200;
df2 = 200;
df3 = 200;
}
}
This is the code for the m input.
void Fight() {
if (keyPressed) {
if (key == 'm'|| key == 'M') {
//villkor, flytta höger, X-led.
fill(255, 0, 0, 63);
noStroke();
rect(xF, yF, wF, hF);
xFF = xF;
yFF = yF;
wFF = wF;
hFF = hF;
}
}
}
Here I have my intersect code:
if (g.intersect(f)) {
f.damage();
}
I would appreciate any help I can get. Apologies for my bad English grammar :)
You can use another boolean variable that tracks whether the action was already taken.
Here's a small example:
boolean alreadyPressed = false;
void draw() {}
void mousePressed() {
if(!alreadyPressed){
background(random(255));
}
alreadyPressed = true;
}
You can then reset the boolean variable whenever you want to be eligible to detect the event again.

How can I make a recursion back-track over itself?

I'm having an issue and I'm not certain if it's recursion-based. I created a GUI maze that solves itself but the curser jumps over any recursion-traveled square instead of re-traveling the square. Even though it ultimately finds the goal, I want to show it's entire path but I can't stop the curser from jumping around.
I'm using Runnable to track the maze in real-time so I can see it bounce but without the recursion-travel keeping it bound, the recursive functions cease to work (it just bounces back and forth which, again, I don't quite understand.) I started java about three months ago in an accelerated program so I'm not sure if the issue is my understanding of recursion, or a simple addition to a method, or if I'll have to rewrite a large portion of code.
I included the whole code just in case but really it's an issue that's within the travel method or the visited method. Would the answer be to write an entirely new method that re-travels the changed "visited" string maze? I've been struggling with this for a bit and I just need some direction toward an answer.
import java.awt.*;
import javax.swing.*;
class extraCreditMaze extends JPanel implements Runnable { //uses Runnable to execute jPanel
private String [][] ratMaze = //string maze
{{"blocked","blocked","blocked","blocked","blocked","blocked","blocked","blocked"},
{"blocked","open","blocked","blocked","blocked","blocked","blocked","blocked"},
{"blocked","open","open","open","open","open","open","blocked"},
{"blocked","blocked","open","blocked","open","blocked","open","blocked"},
{"blocked","blocked","open","blocked","open","blocked","open","goal"},
{"blocked","open","open","open","blocked","open","open","blocked"},
{"blocked","blocked","blocked","open","open","open","blocked","blocked"},
{"blocked","blocked","blocked","blocked","blocked","blocked","blocked","blocked"}};
final private int SquareSize = 15;
final private int BoardSize = 17;
private boolean free = false;
int axisX = 1, axisY = 1;
public void paintComponent(Graphics color) //paint components for char
{
super.paintComponent(color);
for(int row = 0; row < ratMaze.length; row++)
{
for(int col = 0; col< ratMaze.length; col++)
{
if(row==axisX && col==axisY) //traveling curser = blue
{
color.setColor(Color.blue);
color.fillOval(col*15,row*15,15,15);
}
else if(ratMaze[row][col]=="blocked") //empty = black
{
color.setColor(Color.black);
color.fillRect(col*SquareSize,row*SquareSize,BoardSize,BoardSize);
}
else if(ratMaze[row][col]=="goal")
{
color.setColor(Color.red); //goal = red
color.fillOval(col*15,row*15,15,15);
}
else if(ratMaze[row][col]=="visited")
{
color.setColor(Color.green); //path traveled = green
color.fillOval(col*15,row*15,15,15);
}
else
{
color.setColor(Color.white); //empty space = white
color.fillRect(col*SquareSize,row*SquareSize,BoardSize,BoardSize);
}
}
}
}
public void run () //starts run at (1,1)
{
travel(1,1);
}
public boolean goal(int x, int y){ //method to check goal (true/false)
if(ratMaze[x][y]=="goal")
return true;
else
return false;
}
public void changedVisited(int x, int y) //method to change traveled
{
ratMaze[x][y] = "visited";
axisX = x;
axisY = y;
}
public boolean boundaries(int x, int y) //check boundaries
{
if(ratMaze[x][y]=="blocked")
return true;
else
return false;
}
public boolean visited(int x, int y) //check if visited
{
if(ratMaze[x][y]=="visited")
return true;
else
return false;
}
private void travel(int x, int y)
{
if(boundaries(x,y)) //makes sure it's within bounds
return;
if(visited(x,y)) //makes sure it hasn't already been visited
return;
if(goal(x,y)) //checks if it's the goal/changes boolean
{
free = true;
JOptionPane.showMessageDialog(this, "You did it, Dr. Cui!"); //fun message!
}
if(!free) //all recursion functions if free=false
{
changedVisited(x,y); //changes traveled block to "visited"
repaint(); //repaints visited
try {Thread.sleep(300); } catch (Exception e) { }//slows down the traveling curser
//I do not understand catch (Exception e)
travel(x-1,y); //recursive travel functions
travel(x+1,y);
travel(x,y-1);
travel(x,y+1);
}
}
}
public class runExtraCreditMaze {
public static void main (String [] args) { //JFrame panel and perimeters
JFrame output = new JFrame();
output.setSize(115, 150);
output.setTitle("The Rat Maze");
output.setLocationRelativeTo(null);
extraCreditMaze Maze = new extraCreditMaze();
output.setContentPane(Maze);
output.setVisible(true);
Thread runnable = new Thread(Maze); //Creates Runnable thread for Maze object
runnable.start(); //Starts Runnable thread of Maze object
}
}
Problem is, as you wrote with the "visited". You are missing an decision tree on what to do, when there is no valid move and you are not in the goal. You will need to allow your rat to back track itself. You will probably need to "free" the visited cells when returning from no valid move.
I will try to add some code samples when I get to IDE :)
update: this is very badly written, and it is a bit lagging. but it should work. It needs a bit of cleaning and verification... I reused your boolean variable, which is bad .. :) and switched the true/false. I will do a bit of cleaning up tomorrow just to leave a nicer answer, but I think you will manage to understand what is going on.
update2:I have cleaned it a bit. Important lessons here are as follows:
1) backtracking needs to be done when all 4 steps fails. When your rat have nowhere to go, you need to disqualify the cell from your shortest path (ratMaze[x][y]="open")
2) You need to change position of your rat, when you return from recursion call, but before you continue with next step into. You will also need to let your program know that you are returning from recursion (thus the isBacktracking)
private void repaintMaze(int x, int y) {
changedVisited(x, y); //changes traveled block to "visited"
repaint(); //repaints visited
isBacktracking = false;
try {
Thread.sleep(500);
} catch (Exception e) {
}
}
private boolean travel(int x, int y) {
if (goal(x, y)) //checks if it's the goal/changes boolean
{
JOptionPane.showMessageDialog(this, "You did it, Dr. Cui!");//fun message!
return true;
}
if (boundaries(x, y) || visited(x, y)) //makes sure it's within bounds
return false;
repaintMaze(x, y);
boolean result; //recursive travel functions
result = travel(x - 1, y);
if (result) {
return true;
}
if (isBacktracking) {
repaintMaze(x, y);
}
result = travel(x + 1, y);
if (result) {
return true;
}
if (isBacktracking) {
repaintMaze(x, y);
}
result = travel(x, y - 1);
if (result) {
return true;
}
if (isBacktracking) {
repaintMaze(x, y);
}
result = travel(x, y + 1);
if (result) {
return true;
}
if (isBacktracking) {
repaintMaze(x, y);
}
ratMaze[x][y] = "open";
isBacktracking = true;
return false;
}
you should also add exit on close to your JFrame :) It will stop the application once you click the X button on the window itself
output.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

How to create a simple user interface to declare variables?

I am working on my first java project, one that simulates the behaviour of a neutrophil catching a bacterium (So random/semirandom particle behaviour). At the beginning of this program I have several variables (such as the radii of the organisms, etc) and right now they are fixed to the value I hardcoded in there. I want to create a user interface so that before the program starts, a screen pops up in which you can type in the values you want to use, and it uses those to run to program. Now I have used a swing script to create such a window and that looks a bit like this:
Now I'm wondering how I could implement it such that I can take the values used in those text boxes and assign them to my variables in my program.
This is the program I am referring to:
package nanocourse;
import java.awt.Color;
import nano.*;
import java.util.Random;
import prescreen.PreScreen;
public class Exercise3_final {
public Exercise3_final() {
int xSize = 1000;
int ySize = 800;
Canvas myScreen = new Canvas(xSize, ySize);
Pen myPen = new Pen(myScreen);
Random random = new Random();
int frame=0; //how many frames have passed since start program
//properties bacterium
int xPosBacterium=random.nextInt(xSize); //random starting position of bacterium
int yPosBacterium=random.nextInt(ySize);
int K=1000; //how many points used to draw bacterium
double [] xValueBacterium = new double[K]; //
double [] yValueBacterium = new double[K];
double bacteriumRadiusInput=20;
double bacteriumRadius=bacteriumRadiusInput; //radius of bacterium
boolean bacteriumAlive=true;
//properties biomolecules
int amountBio=30000;
boolean [] bioExist = new boolean[amountBio];
int [] xPosBio = new int [amountBio];
int [] yPosBio = new int [amountBio];
int [] dXBio = new int [amountBio];
int [] dYBio = new int [amountBio];
int [] lifetimeBio = new int [amountBio];
double chanceDegrade=0.1; //chance that a biomolecule gets degraded per frame
double chanceSynthesize=100; //chance that a biomolecule gets synthesized per frame
for(int i=0;i<amountBio;i++)
{
bioExist[i]=false; //setting existing state to false
}
//properties Neutrophil
int xPosNeutrophil=random.nextInt(xSize);
int yPosNeutrophil=random.nextInt(ySize);
int L=1000;
double [] xValueNeutrophil= new double[L];
double [] yValueNeutrophil= new double[L];
double neutrophilRadius=40;
double xVector, yVector, xNormVector,yNormVector,magnitude,xSumVector,ySumVector;
double aggressiveness=1;
while(bacteriumAlive==true) //while program is running
{
frame++;
//1. Simulating a moving Bacterium
int dXBacterium=random.nextInt(11)-5; //random motion
int dYBacterium=random.nextInt(11)-5;
xPosBacterium=xPosBacterium+dXBacterium;
yPosBacterium=yPosBacterium+dYBacterium;
if(xPosBacterium<(bacteriumRadius/2+2*myPen.getSize())) //boundaries bacterium,accounting for size bacterium
{
xPosBacterium=(int)bacteriumRadius/2+2*myPen.getSize();
}
else if(xPosBacterium>xSize - (bacteriumRadius/2+2*myPen.getSize()))
{
xPosBacterium=xSize - ((int)bacteriumRadius/2+2*myPen.getSize());
}
else if(yPosBacterium<(bacteriumRadius/2+2*myPen.getSize()))
{
yPosBacterium=((int)bacteriumRadius/2+2*myPen.getSize());
}
else if(yPosBacterium>ySize - (bacteriumRadius/2+2*myPen.getSize()))
{
yPosBacterium=ySize - ((int)bacteriumRadius/2+2*myPen.getSize());
}
//2. Simulating synthesis and secretion of biomolecules by the bacterium.
for(int i=0;i<amountBio;i++)
{
double synthesizeNumber=Math.random()*100;
if(synthesizeNumber<chanceSynthesize && i==frame)
{
bioExist[frame]=true; //make the biomolecules exist
}
if(bioExist[i]==true && frame!=1) //if biomolecule exist apply motion
{
dXBio[i]=random.nextInt(41)-20;
dYBio[i]=random.nextInt(41)-20;
xPosBio[i]=xPosBio[i]+dXBio[i];
yPosBio[i]=yPosBio[i]+dYBio[i];
}
else //if biomolecule doesn't exist, make position equal bacterium position
{
xPosBio[i]=xPosBacterium;
yPosBio[i]=yPosBacterium;
}
if(xPosBio[i]>xSize) //boundaries biomolecules
{
xPosBio[i]=xSize;
}
if(xPosBio[i]<0)
{
xPosBio[i]=0;
}
if(yPosBio[i]>ySize)
{
yPosBio[i]=ySize;
}
if(yPosBio[i]<0)
{
yPosBio[i]=0;
}
if(bioExist[i]==true)
{
lifetimeBio[i]++;
double degradationNumber=Math.random()*100;
if(degradationNumber<chanceDegrade)
{
bioExist[i]=false;
}
}
if(bioExist[i]==true && lifetimeBio[i]<=100) //if biomolecule lives shorter than 100 frames==>green
{
myPen.setColor(Color.GREEN); //drawing biomolecules
myPen.setShape(Shape.CIRCLE);
myPen.setSize(5);
}
if(bioExist[i]==true && (lifetimeBio[i]>100 && lifetimeBio[i]<=500)) //if biomolecule lives 101-500 frames==>green
{
myPen.setColor(Color.yellow); //drawing biomolecules
myPen.setShape(Shape.CIRCLE);
myPen.setSize(5);
}
if(bioExist[i]==true && (lifetimeBio[i]>500 && lifetimeBio[i]<=1000)) //if biomolecule lives 501-1000 frames==>orange
{
myPen.setColor(Color.ORANGE); //drawing biomolecules
myPen.setShape(Shape.CIRCLE);
myPen.setSize(5);
}
if(bioExist[i]==true && (lifetimeBio[i]>1000 && lifetimeBio[i]<=1500)) //if biomolecule lives 1001-1500 frames==>red
{
myPen.setColor(Color.RED); //drawing biomolecules
myPen.setShape(Shape.CIRCLE);
myPen.setSize(5);
}
if(bioExist[i]==true && lifetimeBio[i]>1500) //if biomolecule lives 2001+ frames==>magenta
{
myPen.setColor(Color.magenta); //drawing biomolecules
myPen.setShape(Shape.CIRCLE);
myPen.setSize(5);
}
if(bioExist[i]==true)
{
myPen.draw(xPosBio[i],yPosBio[i]);
}
if(Math.sqrt(Math.pow(Math.abs(xPosBio[i]-xPosNeutrophil),2)+Math.pow(Math.abs(yPosBio[i]-yPosNeutrophil), 2))<neutrophilRadius)
{
bioExist[i]=false; //degrade if inside neutrophil
}
}
if(bacteriumAlive==true)
{
for(int i = 0; i <K ; i++) //defining circle, drawing points, placed here because it needs to be on top
{
xValueBacterium[i] = bacteriumRadius*Math.cos(2*Math.PI*i/K);
yValueBacterium[i] = bacteriumRadius*Math.sin(2*Math.PI*i/K);
myPen.setColor(Color.red);
myPen.setShape(Shape.CIRCLE);
myPen.setSize(5);
myPen.draw((int)xValueBacterium[i]+xPosBacterium,(int)yValueBacterium[i]+yPosBacterium);
}
}
//5. Simulating the neutrophil eating the bacteriun
xSumVector=0;
ySumVector=0;
for(int i=0;i<amountBio;i++)
{
if(Math.abs(xPosBio[i]-xPosNeutrophil)<(30+neutrophilRadius) && Math.abs(yPosBio[i]-yPosNeutrophil)<(30+neutrophilRadius) && bioExist[i]==true)
{
xVector=xPosBio[i]-xPosNeutrophil;
yVector=yPosBio[i]-yPosNeutrophil;
magnitude=Math.sqrt(Math.pow(xVector, 2)+Math.pow(yVector, 2));
xNormVector=xVector/magnitude;
yNormVector=yVector/magnitude;
xSumVector=xSumVector+xNormVector;
ySumVector=ySumVector+yNormVector;
}
}
//3. Simulating a moving neutrophil
int dXNeutrophil=random.nextInt(11)-5+(int)aggressiveness*(int)xSumVector; //random motion
int dYNeutrophil=random.nextInt(11)-5+(int)aggressiveness*(int)ySumVector;
xPosNeutrophil=xPosNeutrophil+dXNeutrophil;
yPosNeutrophil=yPosNeutrophil+dYNeutrophil;
myPen.setSize(8);
if(xPosNeutrophil<(neutrophilRadius/2+2*myPen.getSize())) //boundaries neutrophil
{
xPosNeutrophil=(int)neutrophilRadius/2+2*myPen.getSize();
}
else if(xPosNeutrophil>xSize - (neutrophilRadius/2+2*myPen.getSize()))
{
xPosNeutrophil=xSize - ((int)neutrophilRadius/2+2*myPen.getSize());
}
else if(yPosNeutrophil<(neutrophilRadius/2+2*myPen.getSize()))
{
yPosNeutrophil=((int)neutrophilRadius/2+2*myPen.getSize());
}
else if(yPosNeutrophil>ySize - (neutrophilRadius/2+2*myPen.getSize()))
{
yPosNeutrophil=ySize - ((int)neutrophilRadius/2+2*myPen.getSize());
}
for(int i = 0; i <L ; i++) //defining circle, drawing points, placed here because it needs to be on top
{
xValueNeutrophil[i] = neutrophilRadius*Math.cos(2*Math.PI*i/L);
yValueNeutrophil[i] = neutrophilRadius*Math.sin(2*Math.PI*i/L);
myPen.setColor(Color.blue);
myPen.setShape(Shape.CIRCLE);
myPen.draw((int)xValueNeutrophil[i]+xPosNeutrophil,(int)yValueNeutrophil[i]+yPosNeutrophil);
}
if(Math.abs(xPosNeutrophil-xPosBacterium)<2*bacteriumRadiusInput && Math.abs(yPosNeutrophil-yPosBacterium)<2*bacteriumRadiusInput && bacteriumRadius >=0)
{
bacteriumRadius=bacteriumRadius-1;
if(bacteriumRadius==0)
{
bacteriumAlive=false;
}
}
if(bacteriumAlive==false)
{
bacteriumAlive=true;
xPosBacterium=random.nextInt(xSize); //random starting position of bacterium
yPosBacterium=random.nextInt(ySize);
bacteriumRadius=bacteriumRadiusInput;
}
myScreen.update(); //updating/refreshing screen
myScreen.pause(10);
myScreen.clear();
}
}
public static void main(String[] args) {
Exercise3_final e = new Exercise3_final();
}
}
Any help would be appreciated!
Sounds like you need an action listener on the "Run!" button from your dialog:
_run.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// set the variables here by getting the text from the inputs
field1Var = Integer.parseInt(field1Input.getText());
field2Var = Integer.parseInt(field2Input.getText());
...
}
});
I would suggest creating a singleton class to save all the values that are captured from the first screen (options menu screen).
You can get the instance of this class anywhere in the application later on and use it.
Advantages would be:
- You will not have to carry forward the values everywhere in the application.
- The values captured will the persisted till the application is shut down.
Note: Make sure to add validations while fetching values from the options menu so that incorrect values are not set.

JFrame skipping some repaint() calls

I'm making a snake game and I've encountered an error.
I have tried two different loops: thread.sleep and Timer.schedule.
I have gotten the same problem.
It will be working fine, but at random intervals, it will start to skip every other frame for 6-10 frames.
In case I wasn't clear, 1 frame is
#Override public void paintComponent(Graphics G){...}
being called. (I have also tried paint)
This has occurred in some other games I've created, but not all. What can I do to fix it?
Here's a full copy of the code:
https://github.com/jnmcd/Snake/blob/master/Code.java
EDIT: I've done some debugging. It appears that the it's not a problem with the paint. The JPanel doesn't always update. What can I do to fix it?
I found what I needed to do. I had to add a revaidate() after the repaint().
Also In the checkKillCollisions you have to break the loop right after you found the losing condition.
Also if the game ends it keeps on showing the error message[Dialog] for which there i no end.So I have created a flag gameOver to check is game is over or not in Snake Class
static Boolean gameOver = false;//Defined in Snake Class
public void checkKillCollisions() {
boolean lose = false;
for (int i = 1; i < Snake.segments.size(); i++) {
if (Snake.segments.get(i).x == x && Snake.segments.get(i).y == y) {
lose = true;
break;//Have to do this
}
}
if (x >= 60 || x < 0 || y >= 60 || y < 0) {
lose = true;
}
if (lose) {
Snake.window.popUp("You Lose");
}
Snake.gameOver = lose;//Will set the gameOVer flag in Snake class
}
And I've modified the Loop class to stop running right after the gameOver flag is set to true
class Loop extends TimerTask {
#Override
public void run() {
if (!Snake.gameOver) {
Snake.updates();
Snake.window.render();
} else {
System.out.println("Game Over");
cancel();
Snake.window.dispose();
}
}
}

drawString method not displaying text

I have looked through Google searches and a few online tutorials and I am still stuck. It seems unfortunately I am stuck using AWT to do this assignment, seeing as Swing would be better. My assignment is to draw a die.
Currently I am stuck just trying to draw a line from corner of the the square to the edge of the die I am trying to draw. I have read that writing on top frames is ill-advised, but I am waiting on my instructor to let me know if I can just implement Swing components instead.
Currently, I can get the square to show, but I can't get the line to show after its supposedly drawn. I have read it is drawn, but hidden under another frame/object/component/something. However, how can I get the line show?
Once I can get the line to show, I can (hopefully) start drawing the die and the put the dots on it. I am only looking to get the lines to show, and not on how to do the assignment!
Any help is appreciated!
CSC 211
Example #3
P r e t t y a s a p i c t u r e
=====================================
Purpose: To demonstrate the graphic capability of Java.
*/
public class Example03
{
//
// The main method is quite simple.
// We instantiate a (graphical) object, and we play with it.
//
public static void main(String[] args)
{
System.out.println("Hi!"); //say hola
Die myPicture = new Die(); //instantiate object Die
myPicture.action(); //call type Die object myPicture's action method
System.out.println("Bye!"); //say goodbye
}
} // end Example03 class
Here is my Die class, it displays the die:
/*
File: Die.java
Defines and implements the class for our "graphical" object.
*/
// To define a keyboard
import java.awt.*; // AWT = "Abstract Window Toolkit"
public class Die extends Frame
{
public final int WIDTH = 70; // Dimension of the rectangle
public final int HEIGHT = 70; // to be drawn on the window
private int xA = 200; // Coordinates of A (top left corner)
private int yA = xA; // trying to make the frame square
private int faceSide = 0; // the die's face side
public Die() //public constructor Die to set initial stuff
{
setTitle("Let's play some dice!"); // We set the characteristics of our
setLocation(200, 200); // drawing window: the location,
setSize(400, 400); // the size, and
setBackground(Color.lightGray); // the color of the background
setVisible(true); // And we make it appear
}
//
// The action method reads the position of the picture from the keyboard and validates the face side
//
public void action()
{
BrainsOfTheOperation brains = new BrainsOfTheOperation(); //instantiate a new object of BrainsOfTheOperation
brains.action(); //call object brain's, type of BrainsOfTheOperation, method's action
xA = brains.returnXCoordinate(); //return object brain's x coordinate
yA = brains.returnYCoordinate(); //return object brain's y coordinate
faceSide = brains.returnFaceSide(); //return object brain's dice face side position
repaint();
}
//
// The only "graphical" method of the class is the paint method.
//
public void paint(Graphics pane)
{
pane.setColor(Color.cyan); // We use black paint to label
pane.drawString("A", xA - 15, yA + 5); // the 2 opposite corners
pane.drawString("B", 175 + 5, 175 + 5); // of our rectangle
pane.setColor(Color.blue); // Gray is darker than light gray
pane.drawRect(175, 175, WIDTH , HEIGHT); // This is for the rectangle
// drawBlank(pane);
}
private void drawBlank (Graphics pane)
{
pane.setColor(Color.cyan); // We use black paint to label
pane.drawString("A", xA - 15, yA + 5); // the 2 opposite corners
// pane.drawString("B", 175 + 5, 175 + 5); // of our rectangle
pane.setColor(Color.blue); // Gray is darker than light gray
pane.drawRect(175, 175, WIDTH , HEIGHT); // This is for the rectangle
}
private void drawDot (Graphics pane)
{
}
private void drawOne (Graphics pane)
{
}
private void drawTwo (Graphics pane)
{
}
private void drawThree (Graphics pane)
{
}
private void drawFour (Graphics pane)
{
}
private void drawFive (Graphics pane)
{
}
private void drawSix (Graphics pane)
{
}
} // end class Die
And finally, my BrainsOfTheOperation class that validates an user's input and then asks for coordinates:
import java.util.Scanner;
public class BrainsOfTheOperation
{
public int xA, yA; //coordinates of where the dice will play
private int faceSide = 0; //what side the dice is showing
private boolean faceSideNotValid = true; //used in a while loop to ensure a correct side is chosen
public BrainsOfTheOperation() //public constructor
{
//left blank
}
public void action() //action method to ask for a face side, valid it, and then ask for the dice's coordinates on a frame
{
Scanner keyboard = new Scanner(System.in); // Instantiating a keyboard scanner
while ( faceSideNotValid )
{
System.out.print("Enter the number on the face of the die: ");
faceSide = keyboard.nextInt(); //take the next integer
testIfValid(); //make sure its valid: if faceSide >= to 1 and faceSide <= 6, return false, to break out of while loop
}
System.out.print("Enter the location of the die: ");
xA = keyboard.nextInt(); // Determines the upper left corner of
yA = keyboard.nextInt(); // the square AKA die
}
private void testIfValid() //declare method testIfValid to test if faceSide integer is a valid number for a die
{
if ( faceSide >= 1 && faceSide <= 6 )
{
faceSideNotValid = false; //set the faceSideNotValid to false to end the while loop
}
else //otherwise, leave the boolean faceSideNotValid true as they haven't entered a correct number
{
System.out.println("Number entered invalid please try again!");
faceSideNotValid = true;
}
}
public int returnXCoordinate() //returns the die's x Coordinate
{
return xA;
}
public int returnYCoordinate()//returns the die's y Coordinate
{
return yA;
}
public int returnFaceSide()//returns the die's face side (location)
{
return faceSide;
}
}//end class BrainsOfTheOperation

Categories