Does anyone know how to make a play button for a game?

I am trying to make a game and don’t know how to make the background change until a new button is pressed. Here is my code:


PImage bg;
int y;

void setup() {
  size(1000, 700);
  bg = loadImage("download.jpeg");
}

boolean down = false;

void mousePressed() {
  down = true;
}

void draw() {
  background(bg);
  
  stroke(226, 204, 0);
  
  y++;
  if (y > height) {
    y = 0; 
  }
  String play = "Play";
  String mousePos = mouseX+ ", "+ mouseY;
  fill(255, 255, 255);
  textSize(30);
  text(play, 475, 250);
  text("Settings", 445, 280);
  noFill();
  textSize(10);
  text(mousePos, 950, 690);
  if (mouseX > 475 && mouseX < 530 && mouseY > 220 && mouseY < 250) {
    fill(32, 32, 32);
    textSize(30);
    text(play, 475, 250);
    println("0:0");
  }
  if (mouseX > 475 && mouseX < 530 && mouseY > 220 && mouseY < 250 && mousePressed) {
    fill(32, 32, 32);
    textSize(30);
    text(play, 475, 250);
    println("0:1");
    background(bg);
  }

Does anyone know what to do?

1 Like

Hello and a warm welcome to the forum!

Great you’ve joined!

You have to realize that when you leave the menu and enter the game, a new phase / state of your Sketch has begun.

Therefore, we store this change in a new variable state. state can either be menu or game. (and later also splash screen, or help screen)

state dictates what happens in draw().

To make the brief mousePressed permanent, the mousePressed changes state.

switch(state) { case.... similar to if().. else if().... evaluates state.

Warmest regards,

Chrisir



color  bg=0;
int y;

final int MENU=0; 
final int GAME=1; 
int state = 0;

void setup() {
  size(1000, 700);
  //bg = loadImage("download.jpeg");
}

boolean down = false;

void mousePressed() {
  down = true;
}

void draw() {

  switch (state) {

  case MENU:

    background(bg);

    stroke(226, 204, 0);

    y++;
    if (y > height) {
      y = 0;
    }

    String play = "Play";
    String mousePos = mouseX+ ", "+ mouseY;

    fill(255, 255, 255);
    textSize(30);
    text(play, 475, 250);
    text("Settings", 445, 280);
    noFill();
    textSize(10);
    text(mousePos, 950, 690);

    if (mouseX > 475 && mouseX < 530 && mouseY > 220 && mouseY < 250) {

      fill(32, 32, 32);
      textSize(30);
      text(play, 475, 250);
      println("0:0");
    }

    if (mouseX > 475 && mouseX < 530 && mouseY > 220 && mouseY < 250 && mousePressed) {
      fill(32, 32, 32);
      textSize(30);
      text(play, 475, 250);
      println("0:1");
      // background(bg);
      state=GAME;
    }

    break; 

  case GAME:
    background(210);
    text("YOUR GAME", 475, 250);
    break;
  }
}
2 Likes