Can anyone change this code to use it as a class (preferly mostly private) couse there are some other codes into the code that uses these classes by calling them in swich case or if else

// We need these libraries installed from library manager
#include <Adafruit_NeoPixel.h>
#include "OneButton.h"

// What GPIO is the strip connected to
#define PIXELPIN 4

// How many NeoPixels in the strip
#define NUMPIXELS 60

// What GPIO is the button connected to?
#define BUTTON_TAP 6

// Initialise the button, with a default low
OneButton buttonTAP(BUTTON_TAP, true);

// Initialise the pixel strip
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIXELPIN, NEO_GRB + NEO_KHZ800);

// A bunch of variables
int playerIndex = -1;
int playerIndexTrail = -2;
int playerDirection = 1;
float nextMove = 0;
float currentPlayerSpeed = 190;
unsigned long countdown = 0;
int enemyIndex = -1;
int coinIndex = -1;
int score = 0;
int bestScore = 0;
int lastScore = 0;
bool gameOver = false;

void setup()
{
// make the button pin an input
pinMode( BUTTON_TAP, INPUT_PULLUP );

// Attatch click functions to the button
buttonTAP.attachClick(singleClick);
buttonTAP.attachLongPressStart(longClick);

// Initialise the strip and set it's brightness to 20%
pixels.begin();
pixels.setBrightness(50);

// set a 2 second countdown before the player appears and starts moving
countdown = millis() + 2000;
}

void loop()
{
// Every cycle we need to tick the button state
buttonTAP.tick();

// If the game is in game over state, exit loop early
if ( gameOver )
return;

// Set the pixel display state of the level
// This sets the enemy position and the coin position
SetLevel();

// wait for a second for the player to get ready
if ( countdown > millis() )
{
pixels.show();
return;
}

// All the player display, movement and game logic is in here
DisplayPlayer();

// This sends the updated pixel color to the hardware.
pixels.show();
}

// Clear the level, setting all pixels to black
void ClearLevel()
{
for(int i=0;i<NUMPIXELS;i++)
pixels.setPixelColor(i, pixels.Color(0,0,0)); // Moderately bright green color.
//rainbow
pixels.show();
}

//random(1, 150),random(1, 255),random(150, 255)

// Show the best score in yellow and if the last score was less than the best, show that on top in red
void BestScore()
{
// Best score in yellow
for(int i=0;i<NUMPIXELS;i++)
{
if ( i < bestScore )
pixels.setPixelColor(i, pixels.Color(255,0,0 )); // Moderately bright green color.
else
pixels.setPixelColor(i, pixels.Color(0,0,0));
}

// last score is less than best is in red
if ( lastScore < bestScore )
{
for(int i=0;i<lastScore;i++)
pixels.setPixelColor(i, pixels.Color(255,0,0)); // Moderately bright green color.
}
pixels.show();
}

// Game over animation
void GameOver()
{
// First pass we animate the strip going red from the enemy position
int a = enemyIndex;
int b = enemyIndex;

for(int i=0;i<NUMPIXELS/2;i++)
{
pixels.setPixelColor(a, pixels.Color(255,0,0)); // Moderately bright green color.
pixels.setPixelColor(b, pixels.Color(255,0,0)); // Moderately bright green color.

  a = ( a + 1) % NUMPIXELS;
  b--;
  if ( b == -1 )
    b = NUMPIXELS;

  pixels.show();
  delay(20);

}

delay(100);

// Second pass we animate the strip going back from the enemy position
a = enemyIndex;
b = enemyIndex;

for(int i=0;i<NUMPIXELS/2;i++)
{
pixels.setPixelColor(a, pixels.Color(0,0,0)); // Black
pixels.setPixelColor(b, pixels.Color(0,0,0)); // Black

  a = ( a + 1) % NUMPIXELS;
  b--;
  if ( b == -1 )
    b = NUMPIXELS;

    pixels.show();
    delay(20);

}

// Now we show the best score
delay(100);
BestScore();
}

// Setup the level including the postiion of the enemy and the coin
void SetLevel()
{
// If the enemy position is -1 (has been reset)
// Find a new position for the enemy
if ( enemyIndex < 0 )
{
// I fthe player not playing, always start the enemy at the half strip position
if ( playerIndex < 0 )
{
enemyIndex = NUMPIXELS / 2;
}
// The player is in the game, so make sure not to place the enemy on or too close to the player
else
{
enemyIndex = random(0, NUMPIXELS);

  while ( abs(enemyIndex - playerIndex ) < ( NUMPIXELS / 4 ) )
    enemyIndex = random(0, NUMPIXELS);
}

}
// If the coin position is -1 (has been reset)
// Find a new position for the coin
if ( coinIndex < 0 )
{
coinIndex = random(0, NUMPIXELS);

  // pick a coin position somewhere between the player and enemy
  while ( abs(coinIndex - playerIndex ) < 7 || ( abs(coinIndex - enemyIndex ) < 7 ) )
    coinIndex = random(0, NUMPIXELS);

}

pixels.setPixelColor(enemyIndex, pixels.Color(255,10,0));
pixels.setPixelColor(coinIndex, pixels.Color(255,255,0));
}

// This is where all the magic happens
// Player movement happens here as well as game logic for collecting coins or hitting the enemy
void DisplayPlayer()
{

if ( nextMove < millis() )
{
nextMove = millis() + currentPlayerSpeed;

// The player has a visual trail, so these next 2 if statements shows or clears the trail
if ( playerIndexTrail >= 0 )
    pixels.setPixelColor(playerIndexTrail, pixels.Color(random(1, 70), random(1, 160), random(200, 255)));

if ( playerIndex >= 0)
{
  pixels.setPixelColor(playerIndex, pixels.Color(255, 0, 255));
  
  // second dot player
  
  playerIndexTrail = playerIndex;
}

// Move the player in their current direction
playerIndex += playerDirection;

// Wrap the player at the strip edges
if ( playerIndex < 0 )
  playerIndex = NUMPIXELS - 1;
else if ( playerIndex == NUMPIXELS )
  playerIndex = 0;

pixels.setPixelColor(playerIndex, pixels.Color(0, 255, 0));

//142, 255, 10 player dot

// Did the player hit the coin?
// If so, increase the score, reset coin and enemy positions and clear the level
// Next loop the SetLevel() will reset the enemy and coin
// Player speed is also increased for every coin hit
if ( playerIndex == coinIndex )
{
  enemyIndex = -1;
  coinIndex = -1;
  score++;
  currentPlayerSpeed = constrain( currentPlayerSpeed - 5, 15, 130 );
  ClearLevel();
  pixels.setPixelColor(playerIndex, pixels.Color(0, 0, 255));
}

// 142, 255, 10

// Did the player hit the enemy?
// Set the last/best score and call game over
else if ( playerIndex == enemyIndex )
{
  lastScore = score;
  if ( score >= bestScore )
    bestScore = score;
    
  GameOver();
  
  gameOver = true;
  enemyIndex = -1;
  coinIndex = -1;
  playerIndex = -1;
}

}
}

// Single button click
void singleClick()
{
// No input until player is visible
if ( countdown > millis() )
return;

// switch the player direction
playerDirection = -playerDirection;
}

// Long button click
void longClick()
{
// Switch game over state
// If it was game over, start the game, otherwise cancel a game in progress
gameOver = !gameOver;
if ( gameOver )
{
enemyIndex = -1;
coinIndex = -1;
playerIndex = -1;
currentPlayerSpeed = 190;
ClearLevel();
}
else
{
ClearLevel();
score = 0;
currentPlayerSpeed = 190;
countdown = millis() + 2000;
}
}

DON’T DOUBLE POST PLEASE.

Hello, do yourself a favour and please read How to get the best out of this forum and modify your post accordingly (including code tags and necessary documentation of your ask).

Other post/duplicate DELETED
Please do NOT cross post / duplicate as it wastes peoples time and efforts to have more than one post for a single topic.

Continued cross posting could result in a time out from the forum.

Could you take a few moments to Learn How To Use The Forum

It will help you get the best out of the forum in the future.

  • Your OS and version can be valuable information, please include it along with extra security you are using.
  • Always list the version of the IDE you are using and the board version if applicable.
  • Use quote or add error messages as an attachment NOT a picture.
  • How to insert an image into your post. ( Thanks @sterretje )
  • Add your sketch where applicable but please use CODE TAGS ( </> )
  • Add a SCHEMATIC were needed even if it is hand drawn
  • Add working links to any specific hardware as needed (NOT links to similar items)
  • Remember that the people trying to help cannot see your problem so give as much information as you can

COMMON ISSUES

  • Ensure you have FULLY inserted the USB cables.
  • Check you have a COMMON GROUND where required. ( Thanks @Perry)
  • Where possible use USB 2.0 ports or a USB 2.0 POWERED HUB to rule out USB 3.0 issues.
  • Try other computers where possible.
  • Try other USB leads where possible.
  • You may not have the correct driver installed. CH340/341 or CP2102 or FT232 VCP Drivers - FTDI
  • There may be a problem with the board check or remove your wiring first.
  • Remove any items connected to pins 0 and 1.

COMPUTER RELATED

  • Close any other serial programs before opening the IDE.
  • Ensure you turn off any additional security / antivirus just to test.
  • There may be a problem with the PC try RESTARTING it.
  • You may be selecting the wrong COM port.
  • Avoid cloud/network based installations where possible OR ensure your Network/Cloud software is RUNNING.
  • Clear your browsers CACHE.
  • Close the IDE before using any other serial programs.
  • Preferably install IDE’s as ADMINISTRATOR or your OS equivalent

ARDUINO SPECIFIC BOARDS

  • CH340/341 based clones do not report useful information to the “get board info” button.
  • NANO (Old Types) some require you to use the OLD BOOTLOADER option.
  • NANO (ALL Types) See the specific sections lower in the forum.
  • NANO (NEW Types) Install your board CORE’s.
  • Unless using EXTERNAL PROGRAMMERS please leave the IDE selection at default “AVRISP mkII”.
  • Boards using a MICRO usb connector need a cable that is both DATA and CHARGE. Many are CHARGE ONLY.

CREATE editor install locations.

  • On macOs ~/Applications/ArduinoCreateAgent-1.1/ArduinoCreateAgent.app/Contents/MacOS/config.ini
  • On Linux ~/ArduinoCreateAgent-1.1/config.ini
  • On Windows C:\Users[your user]\AppData\Roaming\ArduinoCreateAgent-1.1

Performing the above actions may help resolve your problem without further help.
Language problem ?
Try a language closer to your native language:

Thanks to all those who helped and added to this list.

And another deleted.
@armanisme
I've given you a break from the forum, please use the time to consider the advice you've been given.

Thank you.

Here you go.

// We need these libraries installed from library manager
#include <Adafruit_NeoPixel.h>
#include "OneButton.h"

// What GPIO is the strip connected to
#define PIXELPIN 4

// How many NeoPixels in the strip
#define NUMPIXELS 60

// What GPIO is the button connected to?
#define BUTTON_TAP 6

// Initialise the button, with a default low
OneButton buttonTAP(BUTTON_TAP, true);

// Initialise the pixel strip
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIXELPIN, NEO_GRB + NEO_KHZ800);



class Game *myGame;

class Game
{
    unsigned long countdown = 0;
    int playerDirection = 1;
    bool gameOver = false;
    int enemyIndex = -1;
    int coinIndex = -1;
    int playerIndex = -1;
    float currentPlayerSpeed = 190;
    int score = 0;


    // A bunch of variables
    int playerIndexTrail = -2;
    float nextMove = 0;
    int bestScore = 0;
    int lastScore = 0;


  public:

    void setup()
    {
      // make the button pin an input
      pinMode( BUTTON_TAP, INPUT_PULLUP );

      // Attatch click functions to the button
      buttonTAP.attachClick(Game::singleClick);
      buttonTAP.attachLongPressStart(Game::longClick);

      // Initialise the strip and set it's brightness to 20%
      pixels.begin();
      pixels.setBrightness(50);

      // set a 2 second countdown before the player appears and starts moving
      countdown = millis() + 2000;
    }

    void loop()
    {
      // Every cycle we need to tick the button state
      buttonTAP.tick();

      // If the game is in game over state, exit loop early
      if ( gameOver )
        return;

      // Set the pixel display state of the level
      // This sets the enemy position and the coin position
      SetLevel();

      // wait for a second for the player to get ready
      if ( countdown > millis() )
      {
        pixels.show();
        return;
      }

      // All the player display, movement and game logic is in here
      DisplayPlayer();

      // This sends the updated pixel color to the hardware.
      pixels.show();
    }

    // Clear the level, setting all pixels to black
    static void ClearLevel()
    {
      for (int i = 0; i < NUMPIXELS; i++)
        pixels.setPixelColor(i, pixels.Color(0, 0, 0)); // Moderately bright green color.
      //rainbow
      pixels.show();
    }

    //random(1, 150),random(1, 255),random(150, 255)

    // Show the best score in yellow and if the last score was less than the best, show that on top in red
    void BestScore()
    {
      // Best score in yellow
      for (int i = 0; i < NUMPIXELS; i++)
      {
        if ( i < bestScore )
          pixels.setPixelColor(i, pixels.Color(255, 0, 0 )); // Moderately bright green color.
        else
          pixels.setPixelColor(i, pixels.Color(0, 0, 0));
      }

      // last score is less than best is in red
      if ( lastScore < bestScore )
      {
        for (int i = 0; i < lastScore; i++)
          pixels.setPixelColor(i, pixels.Color(255, 0, 0)); // Moderately bright green color.
      }
      pixels.show();
    }

    // Game over animation
    void GameOver()
    {
      // First pass we animate the strip going red from the enemy position
      int a = enemyIndex;
      int b = enemyIndex;

      for (int i = 0; i < NUMPIXELS / 2; i++)
      {
        pixels.setPixelColor(a, pixels.Color(255, 0, 0)); // Moderately bright green color.
        pixels.setPixelColor(b, pixels.Color(255, 0, 0)); // Moderately bright green color.

        a = ( a + 1) % NUMPIXELS;
        b--;
        if ( b == -1 )
          b = NUMPIXELS;

        pixels.show();
        delay(20);
      }

      delay(100);

      // Second pass we animate the strip going back from the enemy position
      a = enemyIndex;
      b = enemyIndex;

      for (int i = 0; i < NUMPIXELS / 2; i++)
      {
        pixels.setPixelColor(a, pixels.Color(0, 0, 0)); // Black
        pixels.setPixelColor(b, pixels.Color(0, 0, 0)); // Black

        a = ( a + 1) % NUMPIXELS;
        b--;
        if ( b == -1 )
          b = NUMPIXELS;

        pixels.show();
        delay(20);
      }

      // Now we show the best score
      delay(100);
      BestScore();
    }

    // Setup the level including the postiion of the enemy and the coin
    void SetLevel()
    {
      // If the enemy position is -1 (has been reset)
      // Find a new position for the enemy
      if ( enemyIndex < 0 )
      {
        // I fthe player not playing, always start the enemy at the half strip position
        if ( playerIndex < 0 )
        {
          enemyIndex = NUMPIXELS / 2;
        }
        // The player is in the game, so make sure not to place the enemy on or too close to the player
        else
        {
          enemyIndex = random(0, NUMPIXELS);

          while ( abs(enemyIndex - playerIndex ) < ( NUMPIXELS / 4 ) )
            enemyIndex = random(0, NUMPIXELS);
        }
      }
      // If the coin position is -1 (has been reset)
      // Find a new position for the coin
      if ( coinIndex < 0 )
      {
        coinIndex = random(0, NUMPIXELS);

        // pick a coin position somewhere between the player and enemy
        while ( abs(coinIndex - playerIndex ) < 7 || ( abs(coinIndex - enemyIndex ) < 7 ) )
          coinIndex = random(0, NUMPIXELS);
      }

      pixels.setPixelColor(enemyIndex, pixels.Color(255, 10, 0));
      pixels.setPixelColor(coinIndex, pixels.Color(255, 255, 0));
    }

    // This is where all the magic happens
    // Player movement happens here as well as game logic for collecting coins or hitting the enemy
    void DisplayPlayer()
    {

      if ( nextMove < millis() )
      {
        nextMove = millis() + currentPlayerSpeed;

        // The player has a visual trail, so these next 2 if statements shows or clears the trail
        if ( playerIndexTrail >= 0 )
          pixels.setPixelColor(playerIndexTrail, pixels.Color(random(1, 70), random(1, 160), random(200, 255)));

        if ( playerIndex >= 0)
        {
          pixels.setPixelColor(playerIndex, pixels.Color(255, 0, 255));

          // second dot player

          playerIndexTrail = playerIndex;
        }

        // Move the player in their current direction
        playerIndex += playerDirection;

        // Wrap the player at the strip edges
        if ( playerIndex < 0 )
          playerIndex = NUMPIXELS - 1;
        else if ( playerIndex == NUMPIXELS )
          playerIndex = 0;

        pixels.setPixelColor(playerIndex, pixels.Color(0, 255, 0));
        //142, 255, 10 player dot

        // Did the player hit the coin?
        // If so, increase the score, reset coin and enemy positions and clear the level
        // Next loop the SetLevel() will reset the enemy and coin
        // Player speed is also increased for every coin hit
        if ( playerIndex == coinIndex )
        {
          enemyIndex = -1;
          coinIndex = -1;
          score++;
          currentPlayerSpeed = constrain( currentPlayerSpeed - 5, 15, 130 );
          ClearLevel();
          pixels.setPixelColor(playerIndex, pixels.Color(0, 0, 255));
        }
        // 142, 255, 10

        // Did the player hit the enemy?
        // Set the last/best score and call game over
        else if ( playerIndex == enemyIndex )
        {
          lastScore = score;
          if ( score >= bestScore )
            bestScore = score;

          GameOver();

          gameOver = true;
          enemyIndex = -1;
          coinIndex = -1;
          playerIndex = -1;
        }
      }
    }

    // Single button click
    static void singleClick()
    {
      // No input until player is visible
      if ( myGame->countdown > millis() )
        return;

      // switch the player direction
      myGame->playerDirection = -myGame->playerDirection;
    }

    // Long button click
    static void longClick()
    {
      // Switch game over state
      // If it was game over, start the game, otherwise cancel a game in progress
      myGame->gameOver = !myGame->gameOver;
      if ( myGame->gameOver )
      {
        myGame->enemyIndex = -1;
        myGame->coinIndex = -1;
        myGame->playerIndex = -1;
        myGame->currentPlayerSpeed = 190;
        myGame->ClearLevel();
      }
      else
      {
        myGame->ClearLevel();
        myGame->score = 0;
        myGame->currentPlayerSpeed = 190;
        myGame->countdown = millis() + 2000;
      }
    }
};

void setup()
{
  myGame = new Game();
  myGame->setup();
}

void loop()
{
  myGame->loop();
}
1 Like

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.