Completed Snake Program

Dependencies:   N5110 PinDetect PowerControl mbed

Fork of DocTest by Craig Evans

Files at this revision

API Documentation at this revision

Comitter:
MBirney
Date:
Thu Apr 30 15:39:20 2015 +0000
Parent:
6:1de103a19681
Child:
8:b857684a3983
Commit message:
Snake working with no boundaries 2x2 snake ; (next step boundary or classic menu)

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
main.h Show annotated file Show diff for this revision Revisions of this file
--- a/main.cpp	Mon Apr 27 20:27:23 2015 +0000
+++ b/main.cpp	Thu Apr 30 15:39:20 2015 +0000
@@ -17,7 +17,7 @@
     HARD,
 };
 
-Difficulty currentDifficulty=EASY;
+Difficulty currentDifficulty=EASY;// initialise to easy mode
 
 
 // struct for Joystick
@@ -33,7 +33,7 @@
 // create struct variable
 Joystick joystick;
 
-DirectionName previousDirection =RIGHT;
+DirectionName previousDirection =RIGHT;//initial direction =Right
 
 // read default positions of the joystick to calibrate later readings
 void calibrateJoystick()
@@ -74,8 +74,8 @@
 
 void displaySplash()
 {
-    // these are default settings so not strictly needed
-    lcd.inverseMode();      // normal colour mode
+ 
+    lcd.inverseMode();      // change colour mode
     lcd.setBrightness(0.5); // put LED backlight on 50%
 
     //Draw S
@@ -89,7 +89,7 @@
 
     lcd.printString("NAKE ",34,3);
     lcd.printString("By M.Birney",10,5);
-    lcd.drawRect(10,5,65,30,0);
+    lcd.drawRect(10,5,65,30,0); // outline for splash
 
     // need to refresh display after setting pixels
 
@@ -112,9 +112,9 @@
     lcd.drawCircle(10,35,2,0);
     lcd.drawCircle(10,43,2,0);
 
-    gameSpeed= 0.5;
+    gameSpeed= 1.0/5; // set easy game speed(for game time)
 }
-void mediumSelected() // display when medium is selected
+void mediumSelected() // display when medium is selected 
 {
     currentDifficulty=MEDIUM;
     lcd.clear();
@@ -127,7 +127,7 @@
     lcd.drawCircle(10,27,2,0);
     lcd.drawCircle(10,35,2,1);
     lcd.drawCircle(10,43,2,0);
-    gameSpeed=0.5;
+    gameSpeed=1.0/7; // set medium game speed 
 }
 
 void hardSelected() // display when hard is selected
@@ -143,9 +143,10 @@
     lcd.drawCircle(10,27,2,0);
     lcd.drawCircle(10,35,2,0);
     lcd.drawCircle(10,43,2,1);
-    gameSpeed=1.0/32;
+    gameSpeed=1.0/12; // set hard game speed
 }
 
+
 void checkSelectedDifficulty()
 {
 
@@ -209,64 +210,72 @@
 
 void startingSnake()
 {
+   snakeX.resize(5);
+   snakeY.resize(5);
     snakeX[0]=20;
-            snakeX[1]=22;
-            snakeX[2]=24;
-           snakeX[3]=26;
-            snakeX[4]=28;
+    snakeX[1]=22;
+    snakeX[2]=24;
+    snakeX[3]=26;
+    snakeX[4]=28;
+    snakeY[0]=27;
+    snakeY[1]=27;
+    snakeY[2]=27;
+    snakeY[3]=27;
+    snakeY[4]=27;
+    
 
-   for (int i=0; i<5; i++) {
-       // lcd.setPixel(snakeX[i],snakeY[i]);
-         lcd.drawRect(snakeX[i],snakeY[i],1,1,1);
+    for (int i=0; i<5; i++) {
+        // lcd.setPixel(snakeX[i],snakeY[i]);
+        lcd.drawRect(snakeX[i],snakeY[i],1,1,1);
     }
-    
-     
-     wait(5);
+
 }
 
 
 void randomiseFood()
 {
+//   http://stackoverflow.com/questions/3383286/create-a-random-even-number-between-range
+
 
     srand(time(NULL));
 
-    int randomX = rand() % (83-1)+1; // generate random number between 1 and 82  // spaces within boundar
+    int randomX = 2 * (1 + rand() % (40 - 1 + 1)) ; //generate random even number between 2 and 80
 
-    int randomY = rand() %(46-9)+9;// generate random number betwwen 9 and 46
+    int randomY = (2 * (4 + rand() % (22 - 4 + 1))) +1; // generate random even number between 8 and 44 then plus 1 for odd number in range of 9-45
 
-    // int r = rand() % (21 - 10) + 10 // 10 -21 inclusive
 
-    while(lcd.getPixel(randomX,randomY)==1) { // if that pixel is already filled
+    while(lcd.getPixel(randomX,randomY)==1) { // if that pixel is already filled keep generating till a empty space is found
 
-        int randomX = rand() % (83-1)+1; // generate random number between 1 and 82  // spaces within boundar
-
-        int randomY = rand() %(46-9)+9;
+        int randomX = 2 * (1 + rand() % (40 - 1 + 1)) ;
+        int randomY = (2 * (4 + rand() % (22 - 4 + 1))) +1; // generate random even number between 8 and 44 then plus 1 for odd number in range of 9-45
 
 
     }
-   // lcd.setPixel(randomX,randomY) ;// set the food
-   lcd.drawRect(randomX,randomY,1,1,1);
-    food[0]=randomX; // update food position
-    food[1]=randomY;// update food position
+    // lcd.setPixel(randomX,randomY) ;// set the food
+    lcd.drawRect(randomX,randomY,1,1,1);
+    //lcd.setPixel(randomX,randomY);
+
+    foodX[0]=randomX; // update food position
+    foodY[0]=randomY;// update food position
     lcd.refresh();
-
+//serial.printf("%d",randomX);
 }
 
 void Boundary()
 {
 
 
-    for(int x = 0; x< 84; x++) {
+    for(int x = 1; x< 83; x++) { // draw 1 to 82 at y=8
         lcd.setPixel(x,8);
     }
-    for(int x = 0; x< 84; x++) {
+    for(int x = 1; x< 83; x++) { // draw 1 to 82 at y=47
         lcd.setPixel(x,47);
     }
-    for(int y = 8; y< 48; y++) {
-        lcd.setPixel(0,y);
+    for(int y = 8; y< 48; y++) {// draw 8 tp 47 at x=1
+        lcd.setPixel(1,y);
     }
-    for(int y = 8; y< 48; y++) {
-        lcd.setPixel(83,y);
+    for(int y = 8; y< 48; y++) {// draw 8 to 47 at x =82
+        lcd.setPixel(82,y);
     }
 
     lcd.refresh();
@@ -301,8 +310,8 @@
     }
 
 
-   // lcd.clearPixel(snakeX[0],snakeY[0]);//delete tail
-      lcd.drawRect(snakeX[0],snakeY[0],1,1,2);
+    // lcd.clearPixel(snakeX[0],snakeY[0]);//delete tail
+    lcd.drawRect(snakeX[0],snakeY[0],1,1,2);
 
     for (int i =0; i<snakeX.size(); i++) {  // shift elements
         snakeX[i]=snakeX[i + 1]; // apart from head
@@ -314,21 +323,33 @@
         case UP:
             snakeX[snakeX.size()-1]=snakeX[snakeX.size()-2];
             snakeY[snakeY.size()-1]=snakeY[snakeY.size()-2]-2;
+            
+ if(snakeY[snakeY.size()-1] <9) snakeY[snakeY.size()-1]=45;
             break;
 
         case DOWN:
-            snakeX[snakeX.size()-1]=snakeX[snakeX.size()-2];
+          snakeX[snakeX.size()-1]=snakeX[snakeX.size()-2];
             snakeY[snakeY.size()-1]=snakeY[snakeY.size()-2]+2;
+            
+            if(snakeY[snakeY.size()-1] >45) snakeY[snakeY.size()-1]=9;
             break;
 
         case LEFT:
             snakeX[snakeX.size()-1]=snakeX[snakeX.size()-2]-2;
+            
+            if(snakeX[snakeX.size()-1] <2) snakeX[snakeX.size()-1]=80;
+    
             snakeY[snakeY.size()-1]=snakeY[snakeY.size()-2];
             break;
 
         case RIGHT:
-            snakeX[snakeX.size()-1]=snakeX[snakeX.size()-2]+2;
+            snakeX[snakeX.size()-1]= snakeX[snakeX.size()-2]+2;
+          
+          if(snakeX[snakeX.size()-1] >80) snakeX[snakeX.size()-1]=2;
+         
+            
             snakeY[snakeY.size()-1]=snakeY[snakeY.size()-2];
+          
             break;
 
         case CENTRE:
@@ -342,51 +363,74 @@
 
     }
 }
-
+void playTune()
+{
+    
+    //float frequency[]={440,659};
+   // float beat[]={1,1,};
+    // Buzzer=0.3; 
+      //  Buzzer.period(1/(440));// time =1/f 
+        //wait(1);
+        //Buzzer.period(1/(659));
+     
+        //Buzzer=0;
+        
+           // set PWM period
+             
+// set duty cycle 
+     //wait(0.5*beat[i]);     
+}
 void gameOver()
 {
+    leds=1;
     startGame.detach();
-    lcd.clearPixel(snakeX.back(),snakeY.back());
+    lcd.drawRect(snakeX.back(),snakeY.back(),1,1,2);
     wait(0.2);
     lcd.refresh();
-    lcd.setPixel(snakeX.back(),snakeY.back());
+    lcd.drawRect(snakeX.back(),snakeY.back(),1,1,1);
     wait(0.3);
     lcd.refresh();
-    lcd.clearPixel(snakeX.back(),snakeY.back());
+    lcd.drawRect(snakeX.back(),snakeY.back(),1,1,2);
     wait(0.2);
     lcd.refresh();
-    lcd.setPixel(snakeX.back(),snakeY.back());
+    lcd.drawRect(snakeX.back(),snakeY.back(),1,1,1);
     wait(0.2);
     lcd.refresh();
     lcd.clear();
     lcd.inverseMode();
 
-    
+
     lcd.printString("Your Score" ,12,0);
-     lcd.printString("=" ,34,1);
-     
-     int updatedScore=score;
-     int length = sprintf(buffer,"%2d",updatedScore);
+    lcd.printString("=" ,34,1);
+
+    int updatedScore=score;
+    int length = sprintf(buffer,"%2d",updatedScore);
+
+    if (length <= 14)  // if string will fit on display
+        lcd.printString(buffer,40,1);
 
-        if (length <= 14)  // if string will fit on display
-            lcd.printString(buffer,40,1);
-            
-             lcd.printString("Press Reset" ,2,3);
-             lcd.printString("Button To" ,10,4);
-             lcd.printString("Play Again" ,20,5);
-           // 
-            lcd.refresh();
-    gamePlaying=0;
+    lcd.printString("Press Reset" ,2,3);
+    lcd.printString("Button To" ,10,4);
+    lcd.printString("Play Again" ,20,5);
     
+    //
+    lcd.refresh();
+   playTune();
     
+    //gamePlaying=0;
+
+
 
 }
 
+
+
 void checkForCollision()
 {
 
-    if (snakeX.back()<=0 || snakeX.back()>=82 || snakeY.back()<=8 ||snakeY.back()>=47) {
-        
+    if (snakeX.back()==0|| snakeX.back()==82 || snakeY.back()==7 ||snakeY.back()>=47) {
+        myleds=15;
+
         gameOver();
     }
 }
@@ -396,32 +440,43 @@
 void checkForFood()
 {
 
-    if (snakeX.back()+1==food[0] && snakeY.back()==food[1]) {   // if  x and y of head match food
+    if (snakeX.back()==foodX[0] && snakeY.back()==foodY[0]) {   // if  x and y of head match food
 
 
         switch(joystick.direction) {
 
             case RIGHT:
-                snakeX.push_back(food[0]+2);
-                snakeY.push_back(food[1]);
+                snakeX.insert (snakeX.begin() +0,foodX[0]-2 );
+                snakeY.insert (snakeY.begin() ,foodY[0]);
+                //snakeX.push_back(foodX[0]+2);
+                // snakeY.push_back(foodY[0]);
                 break;
             case LEFT:
 
-                snakeX.push_back(food[0]-2);
-                snakeY.push_back(food[1]);
+                snakeX.insert (snakeX.begin() +0,foodX[0]+2 );
+                snakeY.insert (snakeY.begin() ,foodY[0]);
+
+                //  snakeX.push_back(foodX[0]-2);
+                // snakeY.push_back(foodY[0]);
                 break;
 
 
             case UP:
-                snakeX.push_back(food[0]);
-                snakeY.push_back(food[1]-2);
+
+                snakeX.insert (snakeX.begin() +0,foodX[0] );
+                snakeY.insert (snakeY.begin() ,foodY[0]+2);
+                //  snakeX.push_back(foodX[0]);
+                // snakeY.push_back(foodY[0]-2);
                 break;
 
             case DOWN:
-                snakeX.push_back(food[0]);
-                snakeY.push_back(food[1]+2);
+                snakeX.insert (snakeX.begin() +0,foodX[0] );
+                snakeY.insert (snakeY.begin() ,foodY[0]-2);
+                // snakeX.push_back(foodX[0]);
+                // snakeY.push_back(foodY[0]+2);
                 break;
         }
+        lcd.drawRect(snakeX[0],snakeY[0],1,1,1);
 
         int updatedScore;
         // snakeX.insert (snakeX.begin() + 0, );
@@ -445,12 +500,18 @@
 void startButtonPressed()
 {
     gamePlaying=1;
-   // myleds=15;
+    // myleds=15;
 }
 
 
 
+void updateBrightness()
+{
+    float ain ;
+    ain=pot.read();
+    lcd.setBrightness(1-ain);
 
+}
 void updateGameISR()
 {
     updateGameFlag=1;
@@ -459,8 +520,8 @@
 void printVectorContent()
 {
 
-    for( int i=0; i<snakeX.size(); i++)
-        serial.printf( "%d \n \r"  ,snakeX[i]);
+    //for( int i=0; i<snakeX.size(); i++)
+    // serial.printf( "%d \n \r"  ,snakeX[i]);
 
 }
 
@@ -474,6 +535,8 @@
         startGame.detach();
 
         gamePaused=1;
+        leds=2;
+
     }
 
     else {
@@ -490,78 +553,71 @@
 
 void checkForCollisionWithSelf(int i)
 {
-
-        if(snakeX.back()==snakeX[i] && snakeY.back()==snakeY[i]) {
-
-
-            gameOver();
-
-        
+    if(snakeX.back()==snakeX[i] && snakeY.back()==snakeY[i]) {
+        gameOver();
     }
 
 
 }
 void startUpMenu()
 {
-
-    // first need to initialise display
-    
-    displaySplash();
-    wait(4);
+lcd.inverseMode();
     easySelected();
     joystick.direction=UNKNOWN;
     calibrateJoystick();  // get centred values of joystick
-    pollJoystick.attach(&updateJoystick,1.0/5.0);
-    startGame.attach(&updateGameISR,gameSpeed); // read joystick 10 times per second
-    
-
-
+     
 }
 
 void resetButtonPressed()
 {
-  // myleds=0;
-   easySelected();
-   pollJoystick.attach(&updateJoystick,1.0/5.0);
+    gamePlaying=0;
 }
 
 
 int main()
 {
+    leds=1;
     lcd.init();
-    startUpMenu();
     resetButton.mode(PullDown);
     startButton.mode(PullDown);
     button.mode(PullDown);
     startButton.rise(&startButtonPressed);
     resetButton.rise(&resetButtonPressed);
     button.rise(&pauseButtonPressed);
-serial.printf("starting");
+      displaySplash();
+    wait(4);
+//serial.printf("starting");
     while(1) {
-        if (gamePlaying==0) {
+        startUpMenu();
+        while (gamePlaying==0) {
+            updateJoystick();
             checkSelectedDifficulty();
-            serial.printf("check difficulty loop");
+            updateBrightness();
+            //serial.printf("check difficulty loop");
         }
 
-        else if (gamePlaying==1) {
+         if (gamePlaying==1) {
+
             lcd.clear();
             lcd.normalMode();      // normal colour mode
             Boundary();
-            
-            pollJoystick.detach();
-            startGame.attach(&updateGameISR,gameSpeed);
+            previousDirection=RIGHT;
+            joystick.direction=RIGHT; // make sure when game reset that joystick is reset to right 
             startingSnake();
             randomiseFood();
+            int score=5;
+    int length = sprintf(buffer,"%2d",score);
             if (length <= 14)  // if string will fit on display
                 lcd.printString(buffer,0,0);
             // lcd.drawRect(0,0,83,7,0);
-            lcd.refresh();
-            serial.printf("gameplaying=1 game init");
+            lcd.refresh();    
+             startGame.attach(&updateGameISR,gameSpeed);
+           
+            while (gamePlaying==1) {
 
-            //init game start time back food
-            while (1) {
-                serial.printf("enter game loop");
+                //  serial.printf("enter game loop");
                 if(updateGameFlag==1) {
+                    leds=4;
                     //updateJoystick();
                     updateGameFlag=0;
                     updateJoystick();
@@ -570,31 +626,31 @@
                     updateSnakeArray();
                     for (int i=0; i<snakeX.size(); i++) {
                         lcd.drawRect(snakeX[i],snakeY[i],1,1,1);
-                       // lcd.setPixel(snakeX[i],snakeY[i]);
-                        
+                  // lcd.setPixel(snakeX[i],snakeY[i]);
+
 
                     }
                     lcd.refresh();
                     previousDirection=joystick.direction;
-                    
+
+                    //checkForCollision();
                     checkForFood();
-                    checkForCollision();
-                    
+
+
                     for (int i=0; i<snakeX.size()-1; i++) {
                         checkForCollisionWithSelf(i);
-                    }
-
+                         updateBrightness();
+                        //serial.printf("%d",snakeX.size());
+                        // printVectorContent();
 
-                    //serial.printf("%d",snakeX.size());
-                    // printVectorContent();
+                    }
 
                 }
 
             }
-
         }
-    }
 
 
 
+    }
 }
\ No newline at end of file
--- a/main.h	Mon Apr 27 20:27:23 2015 +0000
+++ b/main.h	Thu Apr 30 15:39:20 2015 +0000
@@ -13,15 +13,17 @@
 //#include "PinDetect.h"
 
 // change this to alter tolerance of joystick direction
-#define DIRECTION_TOLERANCE 0.05
+#define DIRECTION_TOLERANCE 0.1
 
-
+AnalogIn pot(p20);
+PwmOut Buzzer(p21);
 
 //        VCC,SCE,RST,D/C,MOSI,SCLK,LED
 N5110 lcd(p7,p8,p9,p10,p11,p13,p26);
-//BusOut myleds(LED1,LED2,LED3,LED4);
-InterruptIn startButton(p6);
-InterruptIn resetButton(p5);
+BusOut myleds(LED1,LED2,LED3,LED4);
+BusOut leds(p22,p23,p24);
+InterruptIn startButton(p5);
+InterruptIn resetButton(p6);
 int score=5;
 Ticker pollJoystick;
 Ticker startGame;
@@ -40,7 +42,11 @@
 bool gamePaused=0;
 vector<int> snakeX (5);
 vector<int> snakeY (5,27);
-int food[2];//element 0 = x position element 1= y position
+vector<int> shape(5);
+int foodX[2];
+int foodY[2];
+int gameState=0;
+int gameMode=0;
 
 
 float gameSpeed;//change depending on difficulty selected