Class file hereIn my Java code, the Finch robot is named myF.
I need to make myF do the following:
Tap once to move toward an object placed in front of it, with it's beak colour (myF.setLED..) red if the object is stationary and green if that object is moving.
The Finch robot should follow the object around with it's beak lighting red if the object stops and green if that object moves.
Whilst in motion, the Finch should be buzzing, but not too loud. ( myF.buzz(Buzz, BuzzDuration)
However my code isn't working as should, I know there are some mistakes but I do not know how to carry on having tried many times. Please see my code below. Any help will be greatly appreciated.
import edu.cmu.ri.createlab.terk.robot.finch.Finch;
public class Main {
//Variable declaration.
static int Buzz = 300;
static int BuzzDuration = 1200;
static int R = 250;
static int G = 250;
static int velocityLeft = 150;
static int velocityRight = 150;
static int turnLeft = -50;
static int turnRight = -50;
static int time = 0;
static int tappedCount = 0;
//Initialization of Finch
static Finch myF = new Finch();
//Main method
public static void main(String[] args)
//TAP FINCH ONCE FOR IT TO DO EITHER OF THE FOLLOWING:
//Turn red and follow stationary object
//Turn green and follow an object in motion
//Do nothing if no object is in front of Finch
{
//while (myF.isFinchUpsideDown() == false)
{
if
(myF.isTapped() == true && myF.isObstacle() == true)
{
{
//Set Beak LED to Green if object in front is moving.
// *******need to add a conditional statement for whether obstacle in front of finch is moving.
myF.setLED(R,0,0);
//myF.setWheelVelocities(velocityLeft,velocityRight);
myF.buzz(Buzz, BuzzDuration);
if (myF.isObstacleRightSide() == false)
{
myF.setWheelVelocities(0, 255);
}
else if (myF.isObstacleLeftSide() == false)
{
myF.setWheelVelocities(255, 0);
}
else if (myF.isObstacle() == true)
{
myF.stopWheels();
}
}
}
//Beak supposed to be RED if object in front is stationary, Finch should move towards object.
else {
// if
//***beak should stay off unless object is placed ahead of it and/or is moving, respectively
// (myF.isTapped() == false)
{
myF.setLED(0,0,0);
myF.setWheelVelocities(0,0);
//myF.quit();
//myF.stopWheels();
tappedCount = 0;
}
}
}
myF.quit();
// FollowObjectAround();
//RUN AGAIN i.e. "the Move method" whilst running the first algorithms above.
// boolean RunAgain = true;
//
// while(RunAgain) {
//
// Move();
//
// }
} //main(String[] args) ends here.
//FIRST PART SUCCESSFUL
//Next part: follow object incorporating corresponding beak colour
//public Main() {
public static void FollowObjectAround() {
while (true){
//This begins the movement of the finch
//if (myF.isObstacleLeftSide() == false && myF.isObstacleRightSide() == false || myF.isObstacle() == false)
//LED colours are red, green and blue
//myF.setLED(R,0,0);
//myF.setWheelVelocities(velocityLeft, velocityRight);
//^^
//here, the robot runs straight into the object and keeps going.
//might be best to have the finch stop when it reaches the object, proceeding movement if that object moves also.
//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 of the Move method for the Finch movements.
Move();
while
(myF.isTapped()==true && myF.isTapped()==true)
//if (myF.isTapped()==true && myF.isTapped()==true)
{
myF.setLED(0,0,0);
myF.stopWheels();
//break;
}
} // I just added this brace, wasn't there before.
}
//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 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();
}
}
//=====================================================================================================
//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);
}
}
//while (myF.isFinchUpsideDown() == false)
{
the "{ " here is wrong and here
{
//Set Beak LED to Green if object in front is moving.
// *******need to add a conditional statement for whether obstacle in front of finch is moving.
Related
I am making a Tic-Tac-Toe game in Java. I have four classes:
TicTacTester just calls (creates an object) the TicTacToe class.
The TicTacToe class provides the GUI of the game (it's a subclass of JFrame). It also creates the 9 buttons for the JPanel to display and users to click.
The XOButton class defines what the buttons can do and actionPerformed method.
Lastly, the GameEnd class defines what happens when the game ends (a new JFrame is created to display score and give the user 2 buttons: exit and restart).
The problem is when I try to code the contents of what happens when the user clicks "restart". It is suppose to call the resetBoard() method, which is defined in TicTacToe class. The problem is, I do not know the name of the object created from the TicTacToe class (in the tester class' static void main method I just typed "new TicTacToe", didn't need to define a name). I cannot call resetBoard from a static standpoint (i.e. I can't do TicTacToe.resetBoard(); ) because resetBoard needs to be non-static.
What I've tried:
I've tried including in the constructor of the GameEnd class a TicTacToe object. If I do this, the GameEnd object creator has to go into TicTacToe class, so I can use 'this' keyword. This does not work because the GameEnd object needs to be created when the WinCondition is met, which is checked when a button is clicked in the XOButton class.
But if I put the GameEnd object creator in the XOButton class (where is is right now and, supposedly, where it should be), in the constructor for GameEnd(String s, TicTacToe a), I cannot use 'this' keyword for the TicTacToe object.
This is my button class. Most code is not relevant so it has been hidden.
public class XOButton extends JButton implements ActionListener {
//Hidden code
private void winCheck() {
for(int j = 0; j < 3; j++) {
if(board[j][0] == 1 && board[j][1] == 1 && board[j][2] == 1 || board[0][j] == 1 && board[1][j] == 1 && board[2][j] == 1) {
player1Score++;
GameEnd end = new GameEnd("X wins this round!");
finished = true;
break;
}
else if(board[j][0] == 2 && board[j][1] == 2 && board[j][2] == 2 || board[0][j] == 2 && board[1][j] == 2 && board[2][j] == 2) {
player2Score++;
GameEnd end = new GameEnd("O wins this round!");
finished = true;
break;
}
}
if(board[0][0] == 1 && board[1][1] == 1 && board[2][2] == 1 || board[0][2] == 1 && board[1][1] == 1 && board[2][0] == 1) {
player1Score++;
GameEnd end = new GameEnd("X wins this round!");
finished = true;
}
else if(board[0][0] == 2 && board[1][1] == 2 && board[2][2] == 2 || board[0][2] == 2 && board[1][1] == 2 && board[2][0] == 2) {
player2Score++;
GameEnd end = new GameEnd("O wins this round!");
finished = true;
}
if(turn == 9 && !finished) {
GameEnd end = new GameEnd("This round is a Draw");
finished = true;
}
}
public void resetButton() {
this.setIcon(null);
markSpot(0);
this.clicked = false;
}
public static void resetStatics() {
turn = 0;
finished = false;
}
}
This is the TicTacToe class. Most code is not relevant so it has been hidden.
public class TicTacToe extends JFrame {
//Hidden code
public void resetBoard() {
for(int j = 0; j < 3; j++) {
for(int i = 0; i < 3; i++) {
buttons[j][i].resetButton();
}
}
XOButton.resetStatics();
}
}
This is the GameEnd class. An object of this is created when the WinCondition is met. Most code is not relevant so it has been hidden.
public class GameEnd extends JFrame implements ActionListener {
//Hidden code
public void actionPerformed(ActionEvent e) {
if(e.getSource() == exit) {
System.exit(0);
}
else if(e.getSource() == retry) {
TicTacToe.resetBoard();
}
}
}
//This is the Tester class
public class TicTacTester {
public static void main(String[] args) {
new TicTacToe();
}
}
What I expect to happen is the game board to restart.
It seems like you are breaking the project down too far. If you have a class for a game, keep all of its methods inside that class. The only time I can think of to use separate classes are if you are trying to create this using the Model-View-Controller (MVC) architecture, or the like. This is a common approach for an application using GUI, data access, and controllers.
There might be other times, but this is all I can think of on the top of my head.
From what you are showing, I don't think it applies.
I think this would be a better approach:
TicTacToe.java
public class TicTacToe extends JFrame {
private int scorePlayer1;
private int scorePlayer2;
private boolean initialized; // default = false
// Reset the board
// Reset the markers, etc.
public void resetGame() {}
// Check to see if there is a winner
// If so, announce the winner and return true
// Otherwise, return false.
public boolean winCheck() {}
// Set up frame, buttons, score, etc.
public void newGame(){
// Create however many JPanels you need
// Add it to a single JFrame
// When you're ready...
// and this game has not been initialized for the first time.
// In this example jframe is an instance of JFrame
if (!this.initialized)
jframe.setVisible(true);
}
// Play the game
public void play(){
// For each round,
// a player chooses where to put their "X" or "O"
// add scores, etc.
// Then at the end of each round
if (this.winCheck())
this.resetGame();
}
}
TicTacToeTester.java:
public class TicTacToeTester {
public static void main(String[] args){
TicTacToe game = new TicTacToe();
game.play();
}
}
I hope this helps!
Let me know if you have any questions. :)
i am trying to make the game Pong in Java. Now i have a problem with the collision on the paddle. It is not moving the other direction. It does work when it hits the sides of the panel.
For now i just needs to go the other way when it hits the X value of the paddle.
I made a function to check the collision.
What am i doing wrong here. Can someone please explain me this?
Thanks in advance
public void checkCollision()
{
if (ball.getY() == 0)
{
moveDown = true;
moveUp = false;
}
if ((ball.getY() + ball.getHeight()) == height)
{
moveDown = false;
moveUp = true;
}
if (ball.getX() == computer.getX())
{
moveRight = false;
moveLeft = true;
}
}
class TimerHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (counter == 0)
{
Random rand = new Random();
int random = rand.nextInt(2) + 1 ;
if (random == 1)
{
moveUp = true;
moveRight = true;
counter++;
}
else if (random == 2)
{
moveDown = true;
moveLeft = true;
counter++;
}
}
controlMovement();
checkCollision();
repaint();
}
}
I believe that your checkCollision function is incomplete... somehow, the function must have access to both paddle current positions to check if the ball hits one of the paddles...
Another suggestion is to use only one flag to indicante the movement in one axis, for example, boolean monvingUp = true indicantes that the ball is moving up at the Y-axis, when false, such flag indicates that is moving down at the Y-axis...
I changed the = to > and it fixed the problem
I am trying to make a donkey kong game.
Currently, I have a boolean called jump which tells that game if the player is jumping or not, when the space bar is pressed.
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE){
StartJump();
}
}
StartJump: Makes the sprite start jumping by changing velocity. It also changes the jump boolean to true.
public void StartJump() {
if (onground) {
velocityY = -4;
onground = false;
jump = true;
}
}
KeyReleased:
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE){
EndJump();
}
}
EndJump: Sets jump to false
public void EndJump() {
if(velocityY < -6.0)
velocityY = -6;
jump = false;
}
The problem occurs when you hold down the spacebar, jump is set to true.
Which then causes the forloop which sets the Y position of Mario to not work and he falls through the floor.
Loop: bricks just contains rectangles for Mario to stand on
for(int i = 0; i < bricks.size(); i++) {
if(marHitBox.intersects(bricks.get(i)) && !mario.getClimb() && !mario.getJump() && marHitBox.intersects(jump.get(i))) {
mario.setMarY((int)bricks.get(i).getY()-40);
mario.setVeloY(0f);
mario.setOnGround(true);
}
}
It is the !mario.getJump() that is causing the problem. Is there any way to see if the spacebar is held for more than x milliseconds to make jump = false?
Try measuring the passing time between the spacebar is pressed and released, it will fit your need.
I think just a check would make it go away
public void StartJump(){
if (!jump && onground){
velocityY = -4;
onground = false;
jump = true;
}
}
I'm writing a chess game in Java have set it up with a Board class that has a 2d array of Square objects. Each square has a height and width (between 0 and 7 inclusive).
I'm writing a method in my Board class that determines whether the passed in player is in check (given the current state of the board).
public boolean isInCheck(Player candidatePlayer) {
String candidateColor = candidatePlayer.getColor();
//get opposite color of candidatePlayer
String oppositeColor = candidateColor.equals("w") ? "b" : "w";
//loop through squares
for (int i = 0; i < myBoard.length; i++) {
for (int j = 0; j < myBoard[i].length; j++) {
//if current square not empty
if (! myBoard[i][j].isEmpty()) {
//if piece at current square is opposite color of candidate player
if (myBoard[i][j].getPiece().getColor().equals(oppositeColor)) {
ArrayList<Square> squares = myBoard[i][j].getPiece().getLegalDestinationSquares(myBoard[i][j]);
//if piece's current legal squares moves contains square of candidatePlayer's king
if (candidateColor.equals("w")) {
if (squares.contains(whiteKingSquare)) {
return true;
}
} else {
if (squares.contains(blackKingSquare)) {
return true;
}
}
}
}
}
}
return false;
}
I've set up the following board position:
bR bKn bB bP bK bP bP bR
bP bP bP bP -- bP bP bP
-- -- -- -- -- -- -- --
-- -- -- -- -- -- -- --
-- -- -- -- -- -- -- --
-- -- -- -- -- -- -- --
wP wP wP wP wQ wP wP wP
wR wKn wB wQ wK wB wKn wR
The black king is currently in check. However, when I run my isInCheckmate(player) method, it returns false. It claims that the black king can move one square down.
Here's my code:
public boolean isCheckmated(Player candidatePlayer, Player other) {
//if candidate player currently in check
if (isInCheck(candidatePlayer)) {
//loop through all squares
for (int i = 0; i <= 7; i++) {
for (int j = 0; j <= 7; j++) {
Square current = myBoard[i][j];
//if current square has one of candidatePlayer's pieces
if (current != null) {
if (current.getPiece().getColor().equals(candidatePlayer.getColor())) {
ArrayList<Square> squares = current.getPiece().getLegalDestinationSquares(current);
//loop through all of that piece's moves
for (Square square : squares) {
//if player can make that move and not in check
if (canMovePiece(current, square, candidatePlayer, other)) {
System.out.println("escape square is at " + square.getHeight() + " " + square.getWidth());
return false;
}
}
}
}
}
}
}
return true;
}
UPDATE: Including code for canMovePiece here:
public boolean canMovePiece(Square start, Square end, Player player1, Player player2) {
//squares are non-null
if (start != null && end != null) {
//get color of moving player
String movingPlayerColor = start.getPiece().getColor();
Player movingPlayer = player1.getColor().equals(movingPlayerColor) ? player1 : player2;
//squares are valid
if (isValidSquare(start.getHeight(), start.getWidth()) && isValidSquare(end.getHeight(), end.getWidth())) {
//if there is a piece at start square and ending square isn't of same color
if (start.getPiece() != null) {
//if end square has a piece on it, must be of different color (or end square is empty)
if (end.getPiece() != null && ! end.getPiece().getColor().equals(movingPlayerColor) || end.getPiece() == null)
//if piece at start can move to square at end
if (start.getPiece().getLegalDestinationSquares(start).contains(end)) {
//store captured piece so we can undo move later
Piece captured = end.getPiece();
//make move
movePiece(start, end);
boolean playerInCheck = isInCheck(movingPlayer);
//if player who made move not in check
if (! playerInCheck) {
//undo move
movePiece(end, start);
if (captured != null) {
end.setPiece(captured);
}
//return true
return true;
}
//else (player who made move is in check)
else {
//undo move
movePiece(end, start);
if (captured != null) {
end.setPiece(captured);
}
return false;
}
}
}
}
}
return false;
}
I still can't figure out why my code thinks the king is out of check if it moves a square down (where it's still in check by the white queen).
Any help much appreciated!
-Mariogs
Here is my method code I use in onTouchEvent:
public void touch(MotionEvent event) {
// starta = "klicka för att börja";
if (event.getAction() == MotionEvent.ACTION_DOWN) {
starta = "Click to start";
fN.aktivitetNer.start();
if (event.getAction() == MotionEvent.ACTION_CANCEL) {
if (y == -300) {
touch(event);
}
else if (y > -300) {
fN.aktivitetNer.interrupt();
fU.aktivitetUpp.start();
p++;
}
}
else if (y2 <= y + xMax) {
fN.aktivitetNer.interrupt();
fU.aktivitetUpp.start();
p = 0;
}
}
}
What should happening is a knife coming down very fast with help of a Thread(fN.aktivitetNer) and if the knife slice the finger(y2) you loose, if you're fast enough you score one point(p), when you loose or win the knife will go up again with another Thread(fU.aktivitetUpp)
I know it's not perfect but it's now working at all!
ps. if you click two times on the screen the programm will crash.
Well it certainly won't work in it's current form, because the code will never enter your second if statement.
Your first if statement asserts that event.getAction() == MotionEvent.ACTION_DOWN. If this is true, then atevent.getAction() cannot possibly be equal to MotionEvent.ACTION_CANCEL and you will never enter that block of code.
Since I don't know what your thread does I can't be certain, but you probably want something more like this:
public void touch(MotionEvent event)
{
// starta = "klicka för att börja";
int actionCode = event.getAction();
if (actionCode == MotionEvent.ACTION_DOWN)
{
//Start to drop knife
}
else if (actionCode == MotionEvent.ACTION_CANCEL || actionCode == MotionEvent.ACTION_UP)
{
if (Knife is falling, and touch point is below knife)
{
//Add one to score
}
else if (Knife is falling, and touch point is above knife)
{
//Reset score to 0
}
}
else if (Knife has already fallen and still touching screen)
{
//Reset score to 0
}
}