This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
memory game graphics java
I'm coding a program that is a 4x4 memory game. Within these 16 boxes will be a pair of integers from 0-7. I have all of that already randomized and coded correctly. Now I'm trying to figure out how to pair the colors with the corresponding integers each time the mouse clicks over the box.
Here most of the code. I know the logic for this game isn't started yet, but I'm more focused on the displayHit method and setColor method right now. Just posting the whole code because maybe I messed up somewhere else.
/*Sets the background of your memory board to black*/
public void init()
{
setSize(400,400);
setBackground(Color.BLACK);
buildBoard(4);
}
/*This is main in java applets
You may need to add (not change) a couple things in this method
*/
public void paint(Graphics canvas)
{
if(firstRun) //for the first run we need to build our random board
{
print2DArray(board);
buildBoard(4);
firstRun = false;
}
else // once our board is built we will display the game
{
displayGame(canvas);
if (mouseClicked) // if the mouse has been clicked
{
displayHit(canvas);//find which box the user clicked
mouseClicked = false;
}
}
}
/*
DO NOT change this method
determines if the mouse has been pressed
sets x and y Mouse to the location of the mouse arrow
redraws the image
*/
public boolean mouseDown(Event e, int x, int y )
{
mouseClicked = true;
xMouse = x;
yMouse = y;
repaint();
return true;
}
/*DO NOT change this method
redraws the scene
*/
public void update ( Graphics g )
{
paint(g);
}
/*
pre: none
post: build an array that holds the memory values for a board of size x size
the board will hold two of each int from 0 to size randomly placed in the array
*/
public void buildBoard(int s)
{
int a = 4;
for (int row = 0; row < a; row++)
for (int column = 0; column < a; column++)
{
board[row][column] = count++ % 8;
}
for(int row = 0; row < 4; row++)
for(int column = 0; column < 4; column ++)
{
int x = (int)Math.floor(Math.random()*4);
int y = (int)Math.floor(Math.random()*4);
temp = board[row][column];
board[row][column] = board[x][y];
board[x][y] = temp;
}
}
public static void print2DArray(int[][] arr)
{
for (int row = 0; row < arr.length; row++)
{
for (int col = 0; col < arr[row].length; col++)
{
System.out.print(arr[row][col] + " ");
}
System.out.println();
}
}
public void displayGame(Graphics canvas)
{
canvas.setColor(Color.WHITE);
for(int i =0; i < 400; i+= WIDTH)
for(int j = 0; j < 400; j+= WIDTH)
canvas.drawRect(i, j, WIDTH, WIDTH);
}
/*
Pre: xMouse and yMouse have been initialized
Post: A circle is displayed in the correct box on the screen
Currently the circle is displayed at the mouse location
*/
public void displayHit(Graphics g)
{
setColor(g);
centerHit(xMouse, xMouse);
g.fillOval(xMouse, yMouse, 40, 40);
}
public void setColor(Graphics g)
{
switch(temp)
{
case 0: g.setColor(Color.RED);
break;
case 1: g.setColor(Color.GREEN);
break;
case 2: g.setColor(Color.BLUE);
break;
case 3: g.setColor(Color.ORANGE);
break;
case 4: g.setColor(Color.CYAN);
break;
case 5: g.setColor(Color.MAGENTA);
break;
case 6: g.setColor(Color.PINK);
break;
case 7: g.setColor(Color.YELLOW);
break;
}
}
public void centerHit(int centerX, int centerY)
{
{
if ((xMouse > 0) && (xMouse <=100))
xMouse = 33;
else if ((xMouse > 100) && (xMouse <=200))
xMouse = 133;
else if ((xMouse > 200) && (xMouse <=300))
xMouse = 233;
else if ((xMouse > 300) && (xMouse <=400))
xMouse = 333;
}
{
if ((yMouse > 0) && (yMouse <=100))
yMouse = 33;
else if ((yMouse > 100) && (yMouse <=200))
yMouse = 133;
else if ((yMouse > 200) && (yMouse <=300))
yMouse = 233;
else if ((yMouse > 300) && (yMouse <=400))
yMouse = 333;
}
}
}
It looks like temp is never changed once buildBoard is called. Which is why you always see the same colour.
this code is fine
public void setColor(Graphics g)
{
switch(temp)
{
case 0: g.setColor(Color.RED);
break;
case 1: g.setColor(Color.GREEN);
break;
case 2: g.setColor(Color.BLUE);
break;
case 3: g.setColor(Color.ORANGE);
break;
case 4: g.setColor(Color.CYAN);
break;
case 5: g.setColor(Color.MAGENTA);
break;
case 6: g.setColor(Color.PINK);
break;
case 7: g.setColor(Color.YELLOW);
break;
}
}
but you are not setting temp anywhere in the code to choose which case/colour you want to use. you need to change temp when you click on a square either by hardcoding it or randomly generating a number between 0-7 to set the colour randomly
Related
My game is a shooting game for school. I need help on the collision between my bullet and my enemy. I have placed the bullet class with my player but for some reason it keeps on passing through it and not disappearing. The first example below shows the weapon class which is for the bullet and the one underneath that is the main.
class Weapons{
PImage bullet;
int speed;
int imageSize = 20;
float x = 20;
float y = 20;
float m;
int damage = 5;
int[] src = new int[2];
float[] dest = new float[2];
Weapons(int x, int y){
speed = 12;
dest[0] = mouseX;
dest[1] = mouseY;
src[0] = x;
src[1] = y;
m = (dest[1]-src[1]) / (dest[0]-src[0]);
this.x = x;
this.y = y;
bullet = loadImage("bullet.png");
bullet.resize(imageSize,imageSize);
}
boolean shooting(){
image(bullet, x, y); // if attack is true then renfer the image
x += speed;
y = (m * (x - dest[0])) + dest[1];
return (x > width || y > height);
}
boolean crash(Enemy enemies) {
//// return the result of checking if the plane has crashed into the bird
return abs(this.x-enemies.x) < bullet.width && abs(this.y - enemies.y) < bullet.height;
}
}
Maincharacter MC;
Goal G;
ArrayList<Enemy> enemies = new ArrayList<>();
ArrayList<Weapons> bullets = new ArrayList<>();
final int Playing = 0;
final int Finish = 1;
int gameMode = Playing;
//Enemy[] enemies = new Enemy[10];
PImage background; // creating background
int bgX = 0;
void setup(){
size(800,500);
MC = new Maincharacter(100,3);
//E1 = new Enemy();
G = new Goal(100,20);
background = loadImage("Battleground1.png");
background.resize(width*2,height); //set image to be same size as the canvas
for(int i = 0; i<2; i++){ // i represent how many enemy I want.
enemies.add(new Enemy((int)random(200,850), (int)random(0, height- 150) ) );
}
//for(int i=0 ; i < enemies.length ; i++){
//enemies[i] = new Enemy(); }
}
void draw(){
if(gameMode == Playing){
background();
MC.display();
G.display();
for(Enemy E : enemies){
E.update();
if (MC.crash(E)){
gameMode = Finish;
}
}
for(Weapons W: bullets){
W.update();
if(enemies.crash(W)){ // doesnt exist
gameMode = Finish;
}
}
// for(int i=0 ; i < enemies.length ; i++){
//enemies[i].update(); }
}}
void keyPressed(){
// creating the movemnt for my main charcter
MC.move();
if (keyCode == RIGHT || keyCode == 68 ){
MC.x += 10;
} else if (keyCode == UP || keyCode == 87) {
MC.y -=10;
} else if (keyCode == LEFT || keyCode == 65){
MC.x -= 10;
} else if(keyCode == DOWN || keyCode == 83 ){
MC.y += 10;
} else if (keyCode == 32) { // space bar
MC.attack_function(); // call attack function to create bullet object
}// make an attack
}
void mousePressed(){ // when mouse is pressed call attack function to create bullet object
MC.attack_function();
}
void background(){
//scrolling background image
image(background, bgX, height/2); //draw image to fill the canvas
//draw image again off the right of the canvas
image(background, bgX+background.width, height/2);
bgX -= 4;
if(bgX == -background.width ) //if first image completely off the canvas
{
bgX=0; //reset back to initial value background
}
}
What I want is to have bullet colliding with the enemies and then disappearing.
You are trying to call the method enemies.crash(W) but enemies is some collection of Enemy instances. Enemy does not provide the method crash as well.
You have to loop for each of your enemies all of your weapons and call the method crash on the Weapon instance giving the current enemy, something like:
for (Enemy enemy: enemies){
enemy.update();
if (mainCharacter.crash(enemy)) {
gameMode = Finish;
}
for (Weapons weapon: bullets) {
weapon.update();
if (weapon.crash(enemy)) {
gameMode = Finish;
// TODO: are you sure that killing an enemy finishes the game?
}
}
}
(Please note that I used mainCharacter instead of MC here for better readability.)
I have this match 3 game, but if I swiping outside the game board this error showed to me and crush the app:
java.lang.ArrayIndexOutOfBoundsException: length=9; index=11
I tried to fix this error but I don't know how to make it work when I touch outside the game board, is that way to make touch only inside the game board game or just a way to ignore this error when it's happing?
public void swap()
{
if(swapIndex > 0)
{
switch (direction){
case "right":
board[poseI][poseJ + 1].poseX -= cellWidth/ 8;
board[poseI][poseJ].poseX += cellWidth/ 8;
break;
case "left":
board[poseI][poseJ - 1].poseX += cellWidth/ 8;
board[poseI][poseJ].poseX -= cellWidth/ 8;
break;
case "up":
board[poseI - 1][poseJ].poseY += cellWidth/ 8;
board[poseI][poseJ].poseY -= cellWidth/ 8;
break;
case "down":
board[poseI + 1][poseJ].poseY -= cellWidth/ 8;
board[poseI][poseJ].poseY += cellWidth/ 8;
break;
}
swapIndex--;
}else {
Candies candies;
candies = board[poseI][poseJ];
board[poseI][poseJ] = board[newPoseI][newPoseJ];
board[newPoseI][newPoseJ] = candies;
board[poseI][poseJ].poseX = (int) (poseJ * cellWidth + drawX);
board[poseI][poseJ].poseY = (int) (poseI * cellWidth + drawY);
board[newPoseI][newPoseJ].poseX = (int) (newPoseJ * cellWidth + drawX);
board[newPoseI][newPoseJ].poseY = (int) (newPoseI * cellWidth + drawY);
swapIndex = 8;
if (gameState == GameState.swapping)
{
gameState = GameState.checkSwapping;
// count user moves
increaseUserMove();
}else {
gameState = GameState.nothing;
}
}
}
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
canvas.drawColor(Color.WHITE); // Background Color
// Create Game top Background
canvas.drawBitmap(spriteSheet.topBG , 0, - cellWidth * 2, null);
// Create Game bottom Background
canvas.drawBitmap(spriteSheet.bottomBG , 0, drawY + cellWidth * 9, null);
// Create Game middle Background
canvas.drawBitmap(spriteSheet.bg_middle , 0, drawY, null);
// Create Game Cells
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setColor(Color.BLACK); // cells color
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 9; j++)
{
canvas.drawLine(0, drawY + (i * cellWidth), cellWidth * 10, drawY + (i * cellWidth), p);
canvas.drawLine(j * cellWidth , drawY, j * cellWidth, drawY + cellWidth * 9, p);
}
}
for (Candies[] candie: board)
{
for (Candies candies: candie)
{
candies.drawCandies(canvas, spriteSheet);
}
}
for(int i = 0; i < board.length; i++)
{
for(int j = 0; j < board[0].length; j++)
{
candies.drawCandies(canvas, spriteSheet);
}
}
//canvas.drawBitmap(spriteSheet.candiesBMP, candies.poseX, candies.poseY, null);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
final int action = event.getAction();
switch (action)
{
case MotionEvent.ACTION_DOWN:
oldX = event.getX();
oldY = event.getY();
poseI = (int) (oldY - drawY) / cellWidth;
poseJ = (int) (oldX - drawX) / cellWidth;
move = true;
break;
case MotionEvent.ACTION_MOVE:
if(gameState == GameState.nothing)
{
float newX = event.getX();
float newY = event.getY();
float deltaX = Math.abs(newX - oldX);
float deltaY = Math.abs(newY - oldY);
if(move && deltaX > 30 || deltaY > 30)
{
// check how many pixels our fingers moved
// if we moved our finger more than 30 pixels we start checking in which direction
move = false;
if (Math.abs(oldX- newX) > Math.abs(oldY - newY))
{
// if the first X touch - the end of the X touch is bigger than the
// first Y touch - the end of the touch Y so the direction is in the X direction
// now we will check which is bigger the oldX or newX for know if its left or right
if(newX > oldX)
{
direction = "right";
newPoseJ = (poseJ + 1);
}else {
direction = "left";
newPoseJ = (poseJ - 1);
}
newPoseI = poseI;
}
if (Math.abs(oldY - newY) > Math.abs(oldX - newX))
{
if(newY > oldY)
{
direction = "down";
newPoseI = (poseI + 1);
}else {
direction = "up";
newPoseI = (poseI - 1);
}
newPoseJ = poseJ;
}
gameState = GameState.swapping;
}
}
break;
}
return true;
}
I'm trying to make a minesweeper clone using Processing's java. I have managed to create a grid and each tile has a randomized value assigned to it, but for some reason, only the top left tile can be clicked, the rest of the tiles do not return a value. If anyone knows whats wrong with my code or what I could try that would be great, thanks
Here's my Java code:
int realWidth = 500;
int realHeight = 500;
int tilemount = 0;
boolean mousePress = false;
//calls class
Tile[] tile = new Tile[100];
float tileSize = realWidth/10;
//sets size of window
void settings() {
size(realWidth, realHeight);
}
//Draws 100 tiles on the grid and assignemts each with a value from -1 - 9
void setup() {
int x = 0;
int y = 0;
for (int i = 0; i < tile.length; i++) {
tile[i] = new Tile(x, y, int(random(-1,9)), tilemount);
x += tileSize;
if (x > realWidth-tileSize) {
x = 0;
y += tileSize;
}
tilemount ++;
}
print("done");
}
//updates each tile in the list
void draw() {
background(50);
for (int i = 0; i < tile.length; i++) {
tile[i].display();
tile[i].tileClicked();
}
//checks if tiles are clicked
clickCheck();
}
//sets up tile class
class Tile {
int x;
int y;
int value;
int tilemount;
Tile(int x, int y, int value, int tilemount) {
this.x = x;
this.y = y;
this.value = value;
this.tilemount = tilemount;
}
//positions the tile based off of display values
void display() {
rect(x, y, tileSize, tileSize);
}
//the problem:
/*if tile is clicked, it should run through all 100 tiles in the list,
detect if the mouse is inside the x value assinged to each tile, and produce the
value of the tile the mouse is currently inside */
void tileClicked() {
if (mousePressed && mousePress == false) {
mousePress = true;
for (int i = 0; i < tile.length; i++) {
//println(tile[i].x, tile[i].y);
//println(tile[2].x, tile[2].y, mouseX, mouseY);
if (mouseX > tile[i].x && mouseX < tileSize && mouseY > tile[i].y && mouseY < tileSize) {
println(i, tile[i].value);
break;
}
}
}
}
}
//Checks if mouse is clicked
void clickCheck() {
if (!mousePressed) {
mousePress = false;
}
}
There is a bit of confusion over classes/objects and global variables in your code.
I say that for a few reasons:
boolean mousePress = false; is a global variable, accessible throughout the sketch, however you are accessing it and changing it from each Tile instance, resetting it's value: you probably meant to use a mousePress property for Tile. This way, each Tile has it's mousePress without interfering with one another.
in tileClicked() you're itereratting through all the tiles, from Tile which means unecessarily doing the loop for each time: each tile can check it's own coordinates and position to know if it's being clicked or not (no need for the loop)
speaking of checking bounds, checking if mouseX < tileSize and mouseY < tileSize will only check for the top left tile: you probably meant mouseX < x + tileSize and mouseY < y + tileSize
Here's a version of your sketch with the above notes applied
(and optional debug text rendering to double check the printed value against the tile):
int realWidth = 500;
int realHeight = 500;
int tilemount = 0;
//calls class
Tile[] tile = new Tile[100];
float tileSize = realWidth/10;
//sets size of window
void settings() {
size(realWidth, realHeight);
}
//Draws 100 tiles on the grid and assignemts each with a value from -1 - 9
void setup() {
int x = 0;
int y = 0;
for (int i = 0; i < tile.length; i++) {
tile[i] = new Tile(x, y, int(random(-1,9)), tilemount);
x += tileSize;
if (x > realWidth-tileSize) {
x = 0;
y += tileSize;
}
tilemount ++;
}
println("done");
}
//updates each tile in the list
void draw() {
background(50);
for (int i = 0; i < tile.length; i++) {
tile[i].display();
tile[i].tileClicked();
//checks if tiles are clicked
tile[i].clickCheck();
}
}
//sets up tile class
class Tile {
int x;
int y;
int value;
int tilemount;
boolean mousePress = false;
Tile(int x, int y, int value, int tilemount) {
this.x = x;
this.y = y;
this.value = value;
this.tilemount = tilemount;
}
//positions the tile based off of display values
void display() {
fill(255);
rect(x, y, tileSize, tileSize);
fill(0);
text(value,x + tileSize * 0.5, y + tileSize * 0.5);
}
//the problem:
/*if tile is clicked, it should run through all 100 tiles in the list,
detect if the mouse is inside the x value assinged to each tile, and produce the
value of the tile the mouse is currently inside */
void tileClicked() {
if (mousePressed && mousePress == false) {
mousePress = true;
//println(tile[2].x, tile[2].y, mouseX, mouseY);
if (mouseX > x && mouseX < x + tileSize && mouseY > y && mouseY < y + tileSize) {
println(value);
}
}
}
//Checks if mouse is clicked
void clickCheck() {
if (!mousePressed) {
mousePress = false;
}
}
}
I understand the intent of the mousePress variable, but I'd like to mousePressed() function which you can use to avoid de-bouncing/resetting this value and simplify code a bit.
Here's a version of the above sketch using mousePressed() (and renaming variables a touch to be in line with Java naming conventions):
int realWidth = 500;
int realHeight = 500;
int tileCount = 0;
//calls class
Tile[] tiles = new Tile[100];
float tileSize = realWidth/10;
//sets size of window
void settings() {
size(realWidth, realHeight);
}
//Draws 100 tiles on the grid and assignemts each with a value from -1 - 9
void setup() {
int x = 0;
int y = 0;
for (int i = 0; i < tiles.length; i++) {
tiles[i] = new Tile(x, y, int(random(-1,9)), tileCount);
x += tileSize;
if (x > realWidth-tileSize) {
x = 0;
y += tileSize;
}
tileCount ++;
}
println("done");
}
//updates each tile in the list
void draw() {
background(50);
for (int i = 0; i < tiles.length; i++) {
tiles[i].display();
}
}
void mousePressed(){
for (int i = 0; i < tiles.length; i++) {
tiles[i].click();
}
}
//sets up tile class
class Tile {
int x;
int y;
int value;
int index;
Tile(int x, int y, int value, int tileCount) {
this.x = x;
this.y = y;
this.value = value;
this.index = tileCount;
}
//positions the tile based off of display values
void display() {
fill(255);
rect(x, y, tileSize, tileSize);
// optional: display the tile value for debugging purposes
fill(0);
text(value, x + tileSize * 0.5, y + tileSize * 0.5);
}
//the problem:
/*if tile is clicked, it should detect if the mouse is inside the
value assinged to each tile, and produce the
value of the tile the mouse is currently inside */
void click() {
if (mouseX > x && mouseX < x + tileSize && mouseY > y && mouseY < y + tileSize) {
println("index", index, "value", value);
}
}
}
Good start though: keep going!
The rest of the code is good, congrats on using a 1D array for a 2D grid layout (and the logic for resetting the x position on each row). Have fun learning !
I think you did a good job naming functions and classes and what not. From this point, I would recommend breaking your code down so that you can make sure that at least 3 tiles function fully before allowing the tilelength to be something like 100 (for 100 tiles).
so from what I can see:
+ You have 3 apostrophes at the end of your code that need to be removed.
+ you use tile.length but never defined a length variable in your class, so when your for loop runs it has no number to use to determine it's number of cycles.
+ Please double check your logic in the tileClicked function with the help of a truth/logic table: https://en.wikipedia.org/wiki/Truth_table . I didn't look too deeply into this but this looks like an area where one misunderstanding could throw ;
Try adding this.length = 3; in your tile class and then re-run your code to see if more tiles pop up.
And it might be good to use some system.out.println calls to print conditional values out so that you can see the intermeediate results and compare them to what you expect to happen. Just some basic debugging.
Good luck.
I'm programming a little 2d game. Acutally I'm busy with the jumping-function. I want my player to jump, when i press the up-arrow key. I managed to make him jumping, but there is a delay of at least one second. This dealy is not existing for other actions like moving left or right. Do you know where it comes from?
The code for jumping is in the keyReaction method.
public class John<I> extends AbstractGame<I> {
//lists
List<ImageObject<I>> floor = new ArrayList<>();
//variables
double jumpHeight = 0;
//boolean
boolean jump = false;
//fix values
int blockHeight = 40;
int blockWidth = 40;
public John(double width, double height) {
//getPlayer()
super(new ImageObject<>("player.png", new Vertex(120, height - 200), new Vertex(0, 0)), width, height);
//floor objects
for(int i=0; i<getWidth(); i+=blockWidth)
floor.add(new ImageObject<>("brick.png", new Vertex(i, getHeight() - blockHeight)));
//add arrays to canvas
getGOss().add(floor);
}
#Override
public void doChecks() {
for(ImageObject<I> f:floor) {
//gravity
if(!(jump) && !(getPlayer().touches(f)))
getPlayer().getMotion().y++;
//stop y-motion on ground
if(getPlayer().touches(f)){
getPlayer().getPos().y = getHeight() - blockHeight - getPlayer().getHeight();
getPlayer().getMotion().y = 0;}
}
}
#Override
public boolean isStopped(){
return false;
}
#Override
public void keyReaction(KeyCode keycode){
switch (keycode) {
//move left
case LEFT_ARROW:
getPlayer().getMotion().x = -2;
break;
case VK_A:
getPlayer().getMotion().x = -2;
break;
//move right
case RIGHT_ARROW:
getPlayer().getMotion().x = 2;
break;
case VK_D:
getPlayer().getMotion().x = 2;
break;
//jump
case UP_ARROW:
jump = true;
if(jumpHeight < 100){
jumpHeight += 5;
getPlayer().getPos().y -=5;
} else if (jumpHeight < 200){
jumpHeight +=5;
getPlayer().getPos().y +=5;
}
break;
case VK_W:
break;
case SPACE:
break;
}
}
#Override
public void keyReactionReleased(KeyCode keycode){
switch (keycode) {
//move left
case LEFT_ARROW:
getPlayer().getMotion().x = 0;
break;
case VK_A:
getPlayer().getMotion().x = 0;
break;
//move right
case RIGHT_ARROW:
getPlayer().getMotion().x = 0;
break;
case VK_D:
getPlayer().getMotion().x = 0;
break;
//jump
case UP_ARROW:
jump = false;
jumpHeight = 0;
break;
case VK_W:
jump = false;
break;
case SPACE:
break;
}
}
//test main
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new SwingScreen(new John<>(1800, 600)));
f.pack();
f.setVisible(true);
}
}
Thank you for your help.
Code with the if:
case UP_ARROW:
if(jumpHeight < 20){
jumpHeight += 5;
getPlayer().getPos().y = -5;
} else if (jumpHeight < 40){
jumpHeight +=5;
getPlayer().getPos().y = 5;
}
break;
Code without the if:
case UP_ARROW:
getPlayer().getPos().y = -5;
break;
KeyReaction:
setOnKeyPressed((ev)->{
logic.keyReaction(KeyCode.fromCode(ev.getCode().impl_getCode()));
ev.consume();
});
setOnKeyReleased((ev)->{
logic.keyReactionReleased(KeyCode.fromCode(ev.getCode().impl_getCode()));
ev.consume();
});
In your jumpheight method you have
jump = true;
if(jumpHeight < 100){
jumpHeight += 5;
getPlayer().getPos().y -=5;
} else if (jumpHeight < 200){
jumpHeight +=5;
getPlayer().getPos().y +=5;
}
break;
On the 4th line there, you have a -=5 for the pos. There is likely another method that prevents the ypos from going under 0. What happens then is you press the up arrow, it gets sent 40 times(200/5), eventually the jumpheight is greater than 200, and only then does the player start moving up.
Using processing I am trying to recreate snakes and ladders games. The grid is done and so is a "dice".
i would like to number the grid like the actual snakes and ladders games. And also add a way that when I move the pawn there will be a link between the "dice" (number that is shown at the bottom of the screen) and the number of boxes the pawn will move.
// Class that displays a single cell of a checker board
class GameBoard {
/*-----------------------properties------------------*/
float x;
float y;
int rVal;
int gVal;
int bVal;
color squareColor; //color of cell fill
int ccSize; //size of cell
/*-----------------------methods---------------------*/
// constructor method
public GameBoard(int tempX, int tempY, color tempColor, int tempSize) {
x = tempX;
y = tempY;
squareColor = tempColor;
ccSize = tempSize;
}
// draws ccColor = tempColor; the cell. This is public because other objects will need to
// be able to tell the object to draw itself.
public void display() {
fill(squareColor);
noStroke();
rectMode(CORNER);
rect(x, y, ccSize, ccSize);
}
}
class Dice {
float xDice;
float yDice;
float diceSize;
String randomNumber = "";
public Dice (float xNewDice, float yNewDice, float newDiceSize) {
xDice = xNewDice;
yDice = yNewDice;
diceSize = newDiceSize;
randomNumber = "4";
}
public void displayDice() {
stroke(0);
fill(255);
rectMode(CENTER);
rect(xDice, yDice, diceSize, diceSize);
}
public void displayNumber() {
textSize(50);
fill(0);
textAlign(CENTER, CENTER);
text(randomNumber, xDice, yDice);
}
public void getRandomNumber() {
float referenceNumber = int(random(1, 7));
if (referenceNumber == 1) {
randomNumber = "1";
}
if (referenceNumber == 2) {
randomNumber = "2";
}
if (referenceNumber == 3) {
randomNumber = "3";
}
if (referenceNumber == 4) {
randomNumber = "4";
}
if (referenceNumber == 5) {
randomNumber = "5";
}
if (referenceNumber == 6) {
randomNumber = "6";
}
}
public void generateRandom() {
textSize(50);
fill(0);
textAlign(CENTER, CENTER);
text(randomNumber, xDice, yDice);
float referenceNumber = int(random(1, 7));
if (referenceNumber == 1) {
randomNumber = "1";
}
if (referenceNumber == 2) {
randomNumber = "2";
}
if (referenceNumber == 3) {
randomNumber = "3";
}
if (referenceNumber == 4) {
randomNumber = "4";
}
if (referenceNumber == 5) {
randomNumber = "5";
}
if (referenceNumber == 6) {
randomNumber = "6";
}
}
}
boolean rollingDice = false;
//create an array of GameBoard objects
GameBoard[] [] squareBoard;
Dice randomDice;
//number of GameBoards
int cellSize = 100;
// set things up
void setup() {
noStroke();
size(700, 800);
background(0);
//initialize the array of GameBoard objects
//base it on the size of the canvas and the size of the individual cells
squareBoard = new GameBoard[width/cellSize][height/cellSize];
randomDice = new Dice (width/2, 750, 80);
//initialize checker board
initCheckerboard();
}
// main drawing loop
void draw() {
background(44, 44, 44);
drawCheckerboard();
randomDice.displayDice();
randomDice.displayNumber();
if(rollingDice) {
randomDice.generateRandom();
}
}
void mouseClicked() {
rollingDice = !rollingDice;
}
// draws a checkerboard pattern
void initCheckerboard() {
// flag to indicate whether to fill with white or black
boolean white = true;
GameBoard cCell;
// flag to indicate whether we are starting an odd or even column
// this is used to ensure that column n + 1 always starts with a different fill
// than column n.
boolean oddColumn = true;
// walk across the x-axis
for (int x=0; x < width; x = x+cellSize) {
// walk down the y-axis
for (int y=0; y < height-100; y = y+cellSize) {
// create the GameBoard
if (white) {
cCell = new GameBoard(x, y, color(64, 64, 64), cellSize);
}
else {
cCell = new GameBoard(x, y, color(44, 44, 44), cellSize);
}
squareBoard[x/cellSize][y/cellSize] = cCell;
//invert the fill color for next cell
white = !white;
}
// make sure that each successive column starts with a different fill
white = !oddColumn;
// flip the flag that tells us whether we're starting an even or odd column
oddColumn = !oddColumn;
}
}
// draws a checkerboard pattern
void drawCheckerboard() {
noStroke();
// walk across the x-axis
for (int x=0; x < width; x = x+cellSize) {
// walk down the y-axis
for (int y=0; y < height-100; y = y+cellSize) {
// draw the GameBoard
squareBoard[x/cellSize][y/cellSize].display();
}
}
}
I tried to change your code as little as possible. As for the movement and the dice, that is a different subject and you have no code in there to do it... I would suggest trying a few things first and if you can't get it ask another question!
As for the numbers as in the snake game you need to fill the rows first, start from below, and every row switch the x of the check rectangles:
// Class that displays a single cell of a checker board
class GameBoard {
/*-----------------------properties------------------*/
float x;
float y;
int rVal;
int gVal;
int bVal;
color squareColor; //color of cell fill
int ccSize; //size of cell
int index;
/*-----------------------methods---------------------*/
// constructor method
public GameBoard(int tempX, int tempY, color tempColor, int tempSize, int i) {
x = tempX;
y = tempY;
squareColor = tempColor;
ccSize = tempSize;
index = i;
}
// draws ccColor = tempColor; the cell. This is public because other objects will need to
// be able to tell the object to draw itself.
public void display() {
fill(squareColor);
noStroke();
rectMode(CORNER);
rect(x, y, ccSize, ccSize);
fill(255);
text(String.valueOf(index), x-ccSize*0.5, y-ccSize*0.5, 200, 200);
}
}
class Dice {
float xDice;
float yDice;
float diceSize;
String randomNumber = "";
public Dice (float xNewDice, float yNewDice, float newDiceSize) {
xDice = xNewDice;
yDice = yNewDice;
diceSize = newDiceSize;
randomNumber = "4";
}
public void displayDice() {
stroke(0);
fill(255);
rectMode(CENTER);
rect(xDice, yDice, diceSize, diceSize);
}
public void displayNumber() {
textSize(50);
fill(0);
textAlign(CENTER, CENTER);
text(randomNumber, xDice, yDice);
}
public void getRandomNumber() {
float referenceNumber = int(random(1, 7));
if (referenceNumber == 1) {
randomNumber = "1";
}
if (referenceNumber == 2) {
randomNumber = "2";
}
if (referenceNumber == 3) {
randomNumber = "3";
}
if (referenceNumber == 4) {
randomNumber = "4";
}
if (referenceNumber == 5) {
randomNumber = "5";
}
if (referenceNumber == 6) {
randomNumber = "6";
}
}
public void generateRandom() {
textSize(50);
fill(0);
textAlign(CENTER, CENTER);
text(randomNumber, xDice, yDice);
float referenceNumber = int(random(1, 7));
if (referenceNumber == 1) {
randomNumber = "1";
}
if (referenceNumber == 2) {
randomNumber = "2";
}
if (referenceNumber == 3) {
randomNumber = "3";
}
if (referenceNumber == 4) {
randomNumber = "4";
}
if (referenceNumber == 5) {
randomNumber = "5";
}
if (referenceNumber == 6) {
randomNumber = "6";
}
}
}
boolean rollingDice = false;
//create an array of GameBoard objects
GameBoard[] [] squareBoard;
Dice randomDice;
//number of GameBoards
int cellSize = 100;
// set things up
void setup() {
noStroke();
size(700, 800);
background(0);
//initialize the array of GameBoard objects
//base it on the size of the canvas and the size of the individual cells
squareBoard = new GameBoard[width/cellSize][height/cellSize];
randomDice = new Dice (width/2, 750, 80);
//initialize checker board
initCheckerboard();
}
// main drawing loop
void draw() {
background(44, 44, 44);
drawCheckerboard();
randomDice.displayDice();
randomDice.displayNumber();
if (rollingDice) {
randomDice.generateRandom();
}
}
void mouseClicked() {
rollingDice = !rollingDice;
}
// draws a checkerboard pattern
void initCheckerboard() {
// flag to indicate whether to fill with white or black
boolean white = true;
GameBoard cCell;
// flag to indicate whether we are starting an odd or even column
// this is used to ensure that column n + 1 always starts with a different fill
// than column n.
boolean oddColumn = true;
int index = 0;
boolean switcher = false;
// walk down the y-axis
for (int y=height-100-cellSize; y >= 0 ; y = y-cellSize) {
// walk across the x-axis
for (int x=0; x < width; x = x+cellSize) {
// create the GameBoard
int nx = x;
if(switcher) nx = width - cellSize - x;
if (white) {
cCell = new GameBoard(nx, y, color(64, 64, 64), cellSize, index);
}
else {
cCell = new GameBoard(nx, y, color(44, 44, 44), cellSize, index);
}
println(y);
squareBoard[x/cellSize][y/cellSize] = cCell;
//invert the fill color for next cell
white = !white;
index++;
}
switcher = !switcher;
// make sure that each successive column starts with a different fill
white = !oddColumn;
// flip the flag that tells us whether we're starting an even or odd column
oddColumn = !oddColumn;
}
}
// draws a checkerboard pattern
void drawCheckerboard() {
noStroke();
// walk across the x-axis
for (int x=0; x < width; x = x+cellSize) {
// walk down the y-axis
for (int y=0; y < height-100; y = y+cellSize) {
// draw the GameBoard
squareBoard[x/cellSize][y/cellSize].display();
}
}
}