I'm trying to have a square change colors from black to white and from white to black whenever the square is clicked on. I use the mouseClicked function to do so, but the problem is that the mouseClicked is not clicking correctly. When I click on the bottom of one square, the square underneath of it is pressed.
Here's my mouseClicked code:
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
System.out.println(mouseX + ", " + mouseY + ", " + (screenW / squares));
colorFlip();
}
});
My colorFlip code:
private void colorFlip() {
for (int i = 0; i < cells.size(); i++) {
Cell cell = cells.get(i);
int x = cell.getX();
int y = cell.getY();
int side = cell.getSide();
if (mouseX >= x && mouseX < x + side && mouseY >= y && mouseY < y + side) {
if (cell.getR() == 0) {
cell.setRGB(255, 255, 255);
} else if (cell.getR() == 255) {
cell.setRGB(0, 0, 0);
}
}
}
mouseX = -1;
mouseY = -1;
}
And my cell initialization code:
Cell(double xVal, double yVal, double sideVal) {
x = xVal;
y = yVal;
side = sideVal;
}
Thanks,
Pranav
Related
my goal is, that if my mouse is inside a square, that exact suqare lights up. But that isnt happening. If i move my mouse in the lower right corner all squares light up.
I've already looked up a similar post to this, but it didnt quite help me.
this is the code of my mouse class
public void mouseMoved(MouseEvent e) {
int mouseX = e.getX();
int mouseY = e.getY();
for (int y = 100; y < 500; y += 106) {
for (int x = 10; x < 700; x += 86) {
Rectangle rec = new Rectangle(x + 2, y + 2, x + 80, y + 100);
if (mouseX > rec.getMinX() && mouseX < rec.getMaxX()
&& mouseY > rec.getMinY() && mouseY < rec.getMaxY())
{
GUI.MousePos = true;
} else {
GUI.MousePos = false;
}
}
}
}
}
this is the code of my GUI class, where I create the rectangles and the colors
for (int y = 100; y < 500; y += 106) {
for (int x = 10; x < 700; x += 86) {
if (counter != Tag.MaxDay()) {
if (Tag.getArray(counter) == dayOfMonth - 1 && MousePos == true){
g.setColor(myGreenSpecial);
}
else if (Tag.getArray(counter) == dayOfMonth - 1 && MousePos == false)
g.setColor(myGreen_Date);
else if (MousePos == true)
g.setColor(myGreen_Date);
else {
g.setColor(myGreen);
}
g.fillRoundRect(x + 2, y + 2, 80, 100, 10, 10); // tage rechteck
g.setColor(Color.WHITE);
g.drawRoundRect(x + 2, y + 2, 80, 100, 10, 10);
counter++;
g.drawString("" + counter, x + 10, y + 70);
}
}
}
The problem is in your first block of code. You seem to be correctly identifying whether or not the mouse is inside the rectangles, but you aren't storing that information correctly. There's only one boolean, GUI.MousePos, that's trying to track the state of every rectangle. In effect, every rectangle is set to be highlighted the same way, and only the last value (the bottom right corner) is actually displayed.
You either need to change that to an array of booleans, one for each rectangle, or keep track of the index of the highlighted rectangle, instead of just using a boolean.
I am basically making a battleship guessing game where you have to the position of a ship by the click of your mouse. When a position of the ship is guessed correctly it deletes that ship cell from the array and when every cell is guessed correctly, the game is over.
What I am now struggling on is to
keep the ship cells within the canvas
convert the mouse position in pixels into the row and column on the grid
if the guess is correct, add the guess to the hit array and if missed adding it to the miss array.
when a guess is made, in addition to colouring the cell, print either “Hit!” or “Miss!” on the cell
sinking the ship when all cells have been hit
In your code you've mixed rows and columns. The x coordinate goes from the left to the right, this are the columns. The y axis goes from the top to the bottom and corresponds to the rows.
Don't store column, row, hit and miss in arrays. But use 2-dimensional arrays to store the position of the ship and the positions of mouse clicks:
boolean [][] ship;
boolean [][] click;
keep the ship cells within the canvas
If the direction is horizontal, then the x start position of the ship has to be less than NUM_COLS - shipLength:
randomX = (int)random(NUM_COLS - shipLength);
randomY = (int)random(NUM_ROWS);
If the direction is horizontal, then the y start position of the ship has to be less than NUM_ROWS - shipLength:
randomX = (int)random(NUM_COLS);
randomY = (int)random(NUM_ROWS - shipLength);
Call randomShip in setup rather than draw:
void setup() {
size(600, 500);
randomShip();
println(store);
}
void draw() {
// randomShip(); <---- delete
drawCells (row, column, shipLength, (255) );
}
Generate the random position and size of the ship in randomShip;
void randomShip () {
ship = new boolean[NUM_COLS][NUM_ROWS];
click = new boolean[NUM_COLS][NUM_ROWS];
shipLength = (int)random (3, 8);
int store = (int)random(vert, horz);
if (store >= 0) {
int randomX = (int)random(NUM_COLS - shipLength);
int randomY = (int)random(NUM_ROWS);
for (int i = 0; i < shipLength; i++ ) {
ship[randomX + i][randomY] = true;
}
} else {
int randomX = (int)random(NUM_COLS);
int randomY = (int)random(NUM_ROWS - shipLength);
for (int i = 0; i < shipLength; i++ ) {
ship[randomX][randomY+1] = true;
}
}
println(shipLength);
}
convert the mouse position in pixels into the row and column on the grid
if the guess is correct, add the guess to the hit array and if missed adding it to the miss array.
The cell which was clicked can be get by the dividing the mouse coordinates mouseX and mouseY by CELLSIZE
int cell_x = mouseX / CELLSIZE;
int cell_y = mouseY / CELLSIZE;
Store mark the clicked cells and count the hits and miss in mouseClicked:
void mouseClicked () {
int cell_x = mouseX / CELLSIZE;
int cell_y = mouseY / CELLSIZE;
if (!click[cell_x][cell_y]) {
click[cell_x][cell_y] = true;
if ( ship[cell_x][cell_y] ) {
hitCount ++;
} else {
missCount ++;
}
}
}
when a guess is made, in addition to colouring the cell, print either “Hit!” or “Miss!” on the cell
Evaluate the ship position (ship[][]) and clicked positions (click[][]) in drawCells. Draw the cells and the text dependent on the states in 2 nested loops:
void drawCells(int colour) {
for (int i = 0; i < NUM_COLS; i++) {
for (int j = 0; j < NUM_ROWS; j++) {
float x = i * CELLSIZE;
float y = j * CELLSIZE;
if (ship[i][j]) {
fill (colour);
rect(x, y, CELLSIZE, CELLSIZE);
}
if (click[i][j]) {
fill(255, 0, 0);
textSize(15);
text(ship[i][j] ? "hit" : "miss", x+10, y+30);
}
}
}
}
sinking the ship when all cells have been hit
Handle the end of the game in draw:
e.g.
void draw() {
drawCells(255);
if (hitCount == shipLength ) {
// [...]
}
}
Full code listing:
final int CELLSIZE = 50;
final int NUM_ROWS = 10;
final int NUM_COLS = 12;
int horz = (int)random(50);
int vert = (int)random(-50);
int store;
int shipLength;
boolean [][] ship;
boolean [][] click;
int hitCount = 0;
int missCount = 0;
void setup() {
size(600, 500);
randomShip();
println(store);
}
void draw() {
drawCells(255);
if (hitCount == shipLength ) {
// [...]
}
}
void drawCells(int colour) {
for (int i = 0; i < NUM_COLS; i++) {
for (int j = 0; j < NUM_ROWS; j++) {
float x = i * CELLSIZE;
float y = j * CELLSIZE;
if (ship[i][j]) {
fill (colour);
rect(x, y, CELLSIZE, CELLSIZE);
}
if (click[i][j]) {
fill(255, 0, 0);
textSize(15);
text(ship[i][j] ? "hit" : "miss", x+10, y+30);
}
}
}
}
void randomShip () {
ship = new boolean[NUM_COLS][NUM_ROWS];
click = new boolean[NUM_COLS][NUM_ROWS];
hitCount = 0;
missCount = 0;
shipLength = (int)random (3, 8);
int store = (int)random(vert, horz);
if (store >= 0) {
int randomX = (int)random(NUM_COLS - shipLength);
int randomY = (int)random(NUM_ROWS);
for (int i = 0; i < shipLength; i++ ) {
ship[randomX + i][randomY] = true;
}
} else {
int randomX = (int)random(NUM_COLS);
int randomY = (int)random(NUM_ROWS - shipLength);
for (int i = 0; i < shipLength; i++ ) {
ship[randomX][randomY+1] = true;
}
}
println(shipLength);
}
void mouseClicked () {
int cell_x = mouseX / CELLSIZE;
int cell_y = mouseY / CELLSIZE;
if (!click[cell_x][cell_y]) {
click[cell_x][cell_y] = true;
if ( ship[cell_x][cell_y] ) {
hitCount ++;
} else {
missCount ++;
}
}
}
I am creating a game sort of based on the Game of Life and Death. The goal of the project is when the cells turn white they will reproduce with other nearby cells, and when they are black they will die randomly. This part of the game I want to implement and have it run based on the state of the cells (life or death).
Currently, when the cells are white and the mouse is pressed the cell will turn white and stay white until the mouse is unclicked and clicked again. When they are black they will be erased if the mouse is over them. Unfortunately, that also removes the array value from the matrix I use to keep track of the current cells. How can I use matrixes without getting an Array Index out of bounds error? I've tried adding a second if statement to search for nearby cells, but it searches even if the cells aren't drawn. I including the entire code here as I do not want to exclude any parts. For reference, I am using Processing 3 for Java.
int value = 0;
int cols, rows;
int scl = 20;
boolean[][] matrix = new boolean[scl+1][scl+1];
boolean life;
boolean death;
void setup() {
frameRate(25);
size(400, 400);
int w = 400;
int h = 400;
cols = w / scl;
rows = h / scl;
}
void draw() {
background(255);
for (int x = 0; x < cols; x++) {
for (int y = 0; y < rows; y++) {
int xpos = x*scl;
int ypos = y*scl;
//cell border color
stroke(55);
if ((mouseX >= xpos && mouseX <= xpos+scl) &&
(mouseY >= ypos && mouseY <= ypos+scl)) {
if (mousePressed == true) {
//println("Clicked at: " + xpos + " and " + ypos);
if (!matrix[xpos/scl][ypos/scl]) {
matrix[xpos/scl][ypos/scl] = true;
if (life){
matrix[xpos/scl][ypos/scl] = true;
println("Living at " + xpos + " and " + ypos);
}
if (death){
matrix[xpos/scl][ypos/scl] = false;
println("Dying at " + xpos + " and " + ypos);
}
} else {
matrix[xpos/scl][ypos/scl] = false;
}
//fill(100);
fill(value);
}
//println("Mouse at: " + xpos + " and " + ypos);
} else {
fill(50);
}
if (matrix[x][y]) {
fill(value);
}
rect(xpos, ypos, scl, scl);
}
}
}
void mousePressed() {
if (value == 0) {
life = true;
death = false;
value = 245;
} else {
life = false;
death = true;
value = 0;
}
}
When I run my game it works fine on the bottom portion of the object collision but, it will not distguish that one and the other if. It is not reading the second one. I took a picture and you can see the (x, y) coords and it meets the condition but, I can still move.
IMG: http://i.stack.imgur.com/PjcHB.png
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
public class Player{
int x = 1; // Location of player
int y = 314; // location of player
int xa = 0; // Representation of where the player goes
int ya = 0; // Representation of where the player goes
int playerWeight = 115;
private int speed = 2;
int[] playerPos = {x, y};
private static final int WIDTH = 30;
private static final int HEIGHT = 30;
private Game game;
public Player(Game game){
this.game=game;
}
public void move(){
System.out.println(x + ", " + y);
x = x + xa;
y = y + ya;
if(x + xa < 0) // Left Bounds
xa = 0;
if (x + xa > game.getWidth() - WIDTH) // Right Bounds
xa = 0;
if (y + ya < 0) // Top Bounds
ya = 0;
if(y + ya > game.getHeight() - WIDTH)
ya = 0;
if (collision()) // Tile bounds
y = y - 4;
if (collision2()){
if(x > 370 && x < 531 && y < 286){ // Check for 3 values
y = y + 4;
System.out.println("-x");
/*
* Use the gravity() method to determine player fall rate
*/
}
else if(x > 370 && x < 531 && y > 223){ // Check for 3 values
ya = 0;
System.out.println("+x");
/*
* Use the gravity() method to determine player fall rate
*/
}
}
}
// Method to find where player is located
public int[] Playerposition(){
x = 1;
y = 300;
return playerPos;
}
public void Gravity(){
}
public void paint(Graphics2D g2d){
//Draws player to screen
g2d.drawImage(getPlayerImg(), x, y, null);
}
public Image getPlayerImg(){
ImageIcon ic = new ImageIcon("C:/Users/AncientPandas/Desktop/KingsQuest/Misc/Images/Sprites/player.png");
return ic.getImage();
}
public void keyReleased(KeyEvent e){
xa = 0;
ya = 0;
}
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_S)
xa = -speed;
if (e.getKeyCode() == KeyEvent.VK_F)
xa = speed;
if (e.getKeyCode() == KeyEvent.VK_E)
ya = -speed;
if (e.getKeyCode() == KeyEvent.VK_D)
ya = speed;
}
public Rectangle getBoundsPlayer(){
return new Rectangle(x, y, WIDTH, HEIGHT);
}
private boolean collision(){
return game.maplayout.getBoundsBlock().intersects(getBoundsPlayer());
}
private boolean collision2(){
return game.maplayout.getBoundsBlock2().intersects(getBoundsPlayer());
}
}
Change:
else if(x > 370 && x < 531 && y > 223){ // Check for 3 values
ya = 0;
System.out.println("+x");
/*
* Use the gravity() method to determine player fall rate
*/
}
to:
if(x > 370 && x < 531 && y < 286){ // Check for 3 values
y = y + 4;
System.out.println("-x");
/*
* Use the gravity() method to determine player fall rate
*/
}
if(x > 370 && x < 531 && y > 223){ // Check for 3 values
ya = 0;
System.out.println("+x");
/*
* Use the gravity() method to determine player fall rate
*/
}
Reason being is that the keyword "else" will only execute code within it's block if the above "if" statement's condition fails/requirements are not met. For example:
boolean anInteger = 9;
if (anInteger == 1999) {
// ...
} else {
// If 'anInteger' is not equal to 9, then execute the following code (within this block)
// ...
}
I am creating a battle ship game, where each round the player can select 4 ship routes by selecting the 4 closest tiles to him, with a mouse.
Now in the following gif, you can see if I will hover on the very edge of a tile, it will select two tiles at once, or even 4 at once if you're holding your mouse in middle of 4 tiles:
(source: gyazo.com)
This should not really be happening in the game, how can I prevent that?
This is the updating code:
/**
*
* #param x mouse X
* #param y mouse Y
*/
public void checkHover(int x, int y) {
for (int i = 0; i < tiles[0].length; i++) {
for (int j = 0; j < tiles[1].length; j++) {
// get coordinates from tile
int x1 = i * (sprite.getWidth() - 1);
int y1 = j * (sprite.getHeight() - 1);
// If we have screen translate, we can cancel it for
// this situation
int realX = x - this.translate.getX();
int realY = y - this.translate.getY();
// checking if mouse inside tile
if (realX >= x1 && realX <= x1 + sprite.getWidth() &&
realY >= y1 && realY <= y1 + sprite.getHeight()) {
// set tile to hovered sprite
this.tiles[i][j].setHover(true);
}
else {
// cancel hovered sprite
this.tiles[i][j].setHover(false);
}
}
}
}
How can I prevent that?
Instead of the two loops I would calculate the index of the 2d array based off the x and y position of the mouse, by dividing the x and y position by how much space there is from one tile to the next (which looks to be the tile width plus 1, the empty border). This will cause border hovers to favor a certain side, but it looks like you don't want to select two tiles anyways.
Once you have the index of the tile, switch the highlight on, and keep a reference to it with an instance variable like lastHighlightedTile, but before you do that, also call lastHighlightedTile.setHover(false);.
If the index of the tile is invalid, as if the mouse is out of the tile area, don't access the array and still call lastHighlightedTile.setHover(false);.
This should fix highlighting multiple tiles, and will also allow you to turn off the previous highlight (the solution of breaking out of the current loop might not turn off the previous highlight).
Assuming width of sprite is equal to 50, I see that first title has x1 to x2 coordinate (0 - 50), second title has (49 - 100), third has (99 - 150)... Same for y dimension.
So when pointer is at (x) = (50), it hovers (x1 - x2) (0-50) and (49-100) titles.
Why are you subtracting 1 from sprite width / height?
try with this:
// get coordinates from tile
int x1 = i * (sprite.getWidth());
int y1 = j * (sprite.getHeight());
Edit: I wrote sample app, which shoved me solution:
public class App {
Tile[][] tiles;
Sprite sprite;
public static void main(String[] args) {
App app = new App();
app.init();
app.checkHover(50, 50);
app.printHovers();
}
private void init() {
sprite = new Sprite();
tiles = new Tile[10][10];
for (int i = 0; i < tiles[0].length; i++) {
for (int j = 0; j < tiles[1].length; j++) {
tiles[i][j] = new Tile();
}
}
}
public void checkHover(int x, int y) {
for (int i = 0; i < tiles[0].length; i++) {
for (int j = 0; j < tiles[i].length; j++) {
// get coordinates from tile
int x1 = i * (sprite.getWidth());
int y1 = j * (sprite.getHeight());
// If we have screen translate, we can cancel it for
// this situation
// int realX = x - this.translate.getX();
// int realY = y - this.translate.getY();
int realX = x;
int realY = y;
// checking if mouse inside tile
if (realX >= x1 && realX < x1 + sprite.getWidth()
&& realY >= y1 && realY < y1 + sprite.getHeight()) {
// set tile to hovered sprite
this.tiles[i][j].setHover(true);
} else {
// cancel hovered sprite
this.tiles[i][j].setHover(false);
}
}
}
}
public void printHovers() {
for (int i = 0; i < tiles[0].length; i++) {
for (int j = 0; j < tiles[i].length; j++) {
System.out.print((tiles[i][j].isHover() ? "Y" : "O") + " ");
}
System.out.println();
}
}
public class Sprite {
public int getWidth() {
return 50;
}
public int getHeight() {
return 50;
}
}
public class Tile {
private boolean hover;
public boolean isHover() {
return hover;
}
public void setHover(boolean hover) {
this.hover = hover;
}
}
}
It works fine for (49, 49), (49, 50), (50, 49) and (50, 50) coords.
So, first you have to remove -1 subtractions, and change <= test to <.
EDIT: Different solution:
Simply declare a boolean at the beginning of the method, and set only if that boolean is still false. Once you set the tile on, also set the boolean to true, which will prevent others from being set on.
public void checkHover(int x, int y) {
boolean hasTurnedOneOn = false;
for (int i = 0; i < tiles[0].length; i++) {
for (int j = 0; j < tiles[1].length; j++) {
// get coordinates from tile
int x1 = i * (sprite.getWidth() - 1);
int y1 = j * (sprite.getHeight() - 1);
// If we have screen translate, we can cancel it for
// this situation
int realX = x - this.translate.getX();
int realY = y - this.translate.getY();
// checking if mouse inside tile
if (realX >= x1 && realX <= x1 + sprite.getWidth() &&
realY >= y1 && realY <= y1 + sprite.getHeight() && !hasTurnedOneOn) {
// set tile to hovered sprite
this.tiles[i][j].setHover(true);
hasTurnedOneOn = true;
}
else {
// cancel hovered sprite
this.tiles[i][j].setHover(false);
}
}
}
}