Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- * main.cpp
- *
- * Created on: 13/10/2015
- * Author: Eduardo Gutiérrez
- * Llorenç Toldrà Porta
- */
- #include <vector>
- #include <unistd.h>
- #include <time.h>
- #include <algorithm>
- #include "Particle.h"
- #include "Pacman.h"
- #include "Ghost.h"
- #include "HighScoreEntry.h"
- /*** For arduino**/
- #include <stdlib.h>
- #include <stdio.h>
- //#include <string.h>
- #include <stdint.h>
- #include <fcntl.h>
- #include <termios.h>
- #include <errno.h>
- #include <sys/ioctl.h>
- #include <iostream>
- #include <fstream>
- //#include <GL/glew.h>
- #define ROWS 19//19
- #define COLUMNS 40//40
- #define LEVEL 1
- #define WIDTH 800
- #define HEIGHT 600
- #define WINDOW_X 50
- #define WINDOW_Y 50
- #define NORTH 1
- #define SOUTH 2
- #define WEST 3
- #define EAST 4
- #define MAXHIGHSCORES 10
- void display();
- void keyboard(unsigned char c,int x,int y);
- void specialkeyboard(int key,int x,int y);
- void PositionObserver(float alpha,float beta,int radi);
- void idle();
- void updatePacmanMovement();
- void ReadJPEG(char *filename,unsigned char **image,int *width, int *height);
- void LoadTexture(char *filename,int dim);
- void nextLevel();
- void pacmanDead(int i);
- void output(int x, int y, float r, float g, float b, char *string);
- void outputPixeles(int x, int y, float r, float g, float b, char *string);
- void WriteHighScoresToFile();
- void ReadHighScoresFromFile();
- void ShowInformation();
- void ShowHighScoresTable();
- void initArduinousb();
- void readArduino();
- void joystick();
- void temperature();
- void heartRate();
- void skinResistance();
- void bluetooth();
- bool calibrateHeartRate();
- bool calibrateGSR();
- using namespace std;
- using namespace RandomMaze;
- //Definición de variables.
- vector<Ghost> playingGhosts;
- vector< HighScoreEntry > highscores;
- Maze m;
- Pacman *myPacman;
- Screen s ( WIDTH,HEIGHT);
- int ghosts = 1;
- long last_t=0;
- int direccion;
- int anglealpha = 0;
- int anglebeta = 0;
- bool gameover;
- int fileDesc, arduinoRcv, arduinoBufIter;
- char buf[64] = "temp text";
- char myword[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
- GLint position[4];
- GLfloat color[4];
- int pacmanVelocityFactor = 1;
- int ghostVelocityFactor = 1;
- int gsrAverage = 0;
- int gsrSum = 0;
- int heartRateAverage = 0;
- int heartRateSum = 0;
- int main (int argc, char *argv[])
- {
- /******************************************* ARDUINO *****************************************************************/
- //initArduinousb();
- srand(time(NULL));
- anglealpha=90;
- anglebeta=90;
- m.setupMaze(ROWS, COLUMNS, LEVEL);
- m.printMaze();
- myPacman = new Pacman( &m, &s);
- gameover=false;
- highscores.clear();
- //highscores.push_back(HighScoreEntry("test",100));
- highscores.push_back(HighScoreEntry("pepito", 400));
- //highscores.push_back(HighScoreEntry("Juan", 15));
- //highscores.push_back(HighScoreEntry("Manolo",250));
- //highscores.clear();
- cout << "Tengo en higscores " << highscores.size();
- ReadHighScoresFromFile();
- cout << "He leido del fichero" << highscores.size();
- //highscores.push_back(HighScoreEntry("Manolo2",500));
- //ReadTableFromFile();
- // std::sort(highscores.begin(), highscores.end(), less_than_key());
- //cout << highscores[3];
- std::sort( highscores.begin(), highscores.end() );
- WriteHighScoresToFile();
- cout << "Tengo en despues de ordenar y escribir higscores " << highscores.size();
- //cout << "Ultimo es" << highscores[3].getScore() << "nombre" << highscores[3].getName();
- /*Esta función es la que inicializa la GLUT y negocia con el sistema de ventanas para abrir una. Los parámetros deben ser los mismos argc y argv,
- * sin modificar, de la función main(). Además, Glut entiende una serie de parámetros que pueden ser pasados por línea de comandos.*/
- glutInit(&argc, argv);
- /*En esta ocasión, utilizamos GLUT_DOUBLE en vez de GLUT_SIMPLE. Esto hace posible la utilización de la técnica de “double buffer”, con la utilizamos
- * dos buffers para pintar en uno mientras se visualiza el otro. Con esto conseguimos una mayor fluidez en escenas.
- */
- glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
- //glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
- //Posición x e y de la esquina superior izquierda de la nueva ventana, con respecto al escritorio en el que se trabaje.
- glutInitWindowPosition(WINDOW_X, WINDOW_Y);
- //Comprobamos que el ancho y alto de nuestra ventana es menor que los pixeles de la pantalla.
- //En ese caso no cabria nuestra ventana en la pantalla
- if ( glutGet(GLUT_SCREEN_WIDTH) == 0 || glutGet(GLUT_SCREEN_WIDTH) < WIDTH)
- throw out_of_range("Error: El ancho no puede ser cero. Error ancho pantalla");
- if (glutGet(GLUT_SCREEN_HEIGHT) == 0 || glutGet(GLUT_SCREEN_HEIGHT) < HEIGHT)
- throw std::out_of_range("Error: El alto no puede ser cero. Error alto pantalla");
- //El ancho y alto de la nueva ventana.
- glutInitWindowSize(WIDTH,HEIGHT);
- // Esta función es la que propiamente crea la ventana y el parámetro es el nombre de la misma.
- glutCreateWindow("Random Maze");
- glEnable(GL_DEPTH_TEST);
- glEnable(GL_LIGHTING);
- //Texture 0 is for Wall ceiling
- glBindTexture(GL_TEXTURE_2D,0);
- LoadTexture("Groundplant64x64.jpg",64);
- //MyLoadTexture("Groundplant64x64.jpg");
- //Texture 1 for food
- glBindTexture(GL_TEXTURE_2D,1);
- LoadTexture("paperwhite.jpg",64);
- //Texture 2 is for passage
- glBindTexture(GL_TEXTURE_2D,2);
- LoadTexture("FloorsMedieval64x64.jpg",64);
- //Texture 3 is for Blinky type ( red ghost)
- glBindTexture(GL_TEXTURE_2D,3);
- LoadTexture("redGlass.jpg",64);
- //Texture 4 is for Pinky type ( pink ghost)
- glBindTexture(GL_TEXTURE_2D,4);
- LoadTexture("ghostPink.jpg",64);
- //Texture 5 is for Inky type ( cyan ghost)
- glBindTexture(GL_TEXTURE_2D,5);
- LoadTexture("ghostCyan.jpg",64);
- //Texture 6 is for Pokey type ( orange ghost)
- glBindTexture(GL_TEXTURE_2D,6);
- LoadTexture("ghostOrange.jpg",64);
- //Texture 7 is for Pacman
- glBindTexture(GL_TEXTURE_2D,7);
- LoadTexture("fire.jpg",64);
- Ghost g1(ghosts,&m,&s);
- playingGhosts.push_back(g1);
- ghosts++;
- Ghost g2(ghosts,&m,&s);
- playingGhosts.push_back(g2);
- ghosts++;
- Ghost g3(ghosts,&m,&s);
- playingGhosts.push_back(g3);
- ghosts++;
- Ghost g4(ghosts,&m,&s);
- playingGhosts.push_back(g4);
- glutDisplayFunc(display);
- glutKeyboardFunc(keyboard);
- glutSpecialFunc(specialkeyboard);
- glutIdleFunc(idle);
- /*Especifica la matriz actual para realizar la composición. En ogl las operaciones de rotación, translación, escalado, etc. se
- * realizan a través de matrices de transformación. Dependiendo de lo que estemos tratando, hay tres tipos de matriz (que son
- * los tres posibles flags que puede llevar de parámetro la función): matriz de proyección (GL_PROJECTION),
- * matriz de modelo (GL_MODELVIEW) y matriz de textura (GL_TEXTURE). Con esta función indicamos a cual de estas tres deben
- * afectar las operaciones. Concretamente, GL_PROJECTION afecta a las vistas o perspectivas o proyecciones.
- */
- glMatrixMode(GL_PROJECTION);
- //Esta función cede el control del flujo del programa a GLUT que, a partir de estos "eventos", irá llamando a las funciones que han sido pasadas como callbacks.
- glutMainLoop();
- return 0;
- }
- //la función display() al ser pasada a glutDisplayFunc(), será llamada cada vez que haya que redibujar la ventana
- void display()
- {
- /******************************************* ARDUINO *****************************************************************/
- //readArduino();
- if(m.getFood() <= 0){
- usleep(3500000);
- nextLevel();
- }
- myPacman->setPoints(m.getPoints());
- //m.getFood()
- //GLint position[4];
- //GLfloat color[4];
- GLfloat colorDiff[4];
- /*Con esto se define el color con el que se borrara el buffer al hacer un glClear().
- * Los 3 primeros parámetros son las componentes R, G y B, siguiendo un rango de [0..1]. La última es el valor alpha.
- */
- glClearColor(0.0,0.0,0.0,0.0);
- /* Borra un buffer o una combinación de varios. En este caso, borra el buffer de color (en realidad, cada componente
- R G y B tienen un buffer distinto, pero aquí los trata como el mismo), el que se pinta después en pantalla.
- Para borrarlos utiliza el color que ha sido previamente definido en init() mediante glClearColor(), en este caso,
- el (0,0,0,0) es decir, pinta el buffer de negro.*/
- //glClear(GL_COLOR_BUFFER_BIT);
- glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
- glMatrixMode(GL_MODELVIEW);
- glLoadIdentity();
- PositionObserver(anglealpha,anglebeta,450);
- glMatrixMode(GL_PROJECTION);
- glLoadIdentity();
- glOrtho(-WIDTH*0.6,WIDTH*0.6,-HEIGHT*0.6,HEIGHT*0.6,10,2000);
- glMatrixMode(GL_MODELVIEW);
- glPolygonMode(GL_FRONT,GL_FILL);
- glPolygonMode(GL_BACK,GL_LINE);
- //-- Ambient light
- position[0]=0; position[1]=0; position[2]=0; position[3]=1;
- glLightiv(GL_LIGHT0,GL_POSITION,position);
- color[0]=0.2; color[1]=0.2; color[2]=0.2; color[3]=1;
- /******************************************* ARDUINO *****************************************************************/
- //temperature(); //Comentar liniea de color superior
- glLightfv(GL_LIGHT0,GL_AMBIENT,color);
- colorDiff[0]=0.0; colorDiff[1]=0.0; colorDiff[2]=0.0; colorDiff[3]=1;
- glLightfv(GL_LIGHT0,GL_DIFFUSE,colorDiff);
- glEnable(GL_LIGHT0);
- myPacman->lightOn(&m,&s,direccion);
- for(int i = 0; i < playingGhosts.size(); i++)
- {
- playingGhosts[i].lightOn(&m,&s);
- }
- m.draw3D(s.getWidth(),s.getHeigth());
- myPacman->draw3D(&m,&s);
- for(int i = 0; i < playingGhosts.size(); i++)
- {
- playingGhosts[i].draw3D(&m,&s);
- }
- updatePacmanMovement();
- for(int i = 0; i < playingGhosts.size(); i++)
- {
- pacmanDead(i);
- switch(rand()%4+1)
- {
- case 1:
- playingGhosts[i].moveNorth( &m, &s,ghostVelocityFactor);
- break;
- case 2:
- playingGhosts[i].moveSouth( &m, &s,ghostVelocityFactor);
- break;
- case 3:
- playingGhosts[i].moveWest( &m, &s,ghostVelocityFactor);
- break;
- case 4:
- playingGhosts[i].moveEast( &m, &s,ghostVelocityFactor);
- break;
- default: playingGhosts[i].moveNorth( &m, &s,ghostVelocityFactor);
- }
- }
- ShowInformation();
- glutSwapBuffers();
- }
- void PositionObserver(float alpha,float beta,int radi)
- {
- float x,y,z;
- float upx,upy,upz;
- float modul;
- x = (float)radi*cos(alpha*2*PI/360.0)*cos(beta*2*PI/360.0);
- y = (float)radi*sin(beta*2*PI/360.0);
- z = (float)radi*sin(alpha*2*PI/360.0)*cos(beta*2*PI/360.0);
- if (beta>0)
- {
- upx=-x;
- upz=-z;
- upy=(x*x+z*z)/y;
- }
- else if(beta==0)
- {
- upx=0;
- upy=1;
- upz=0;
- }
- else
- {
- upx=x;
- upz=z;
- upy=-(x*x+z*z)/y;
- }
- modul=sqrt(upx*upx+upy*upy+upz*upz);
- upx=upx/modul;
- upy=upy/modul;
- upz=upz/modul;
- gluLookAt(x,y,z, 0.0, 0.0, 0.0, upx,upy,upz);
- }
- //-----------------------------------------------
- void keyboard(unsigned char c,int x,int y)
- {
- switch(c)
- {
- case 27: // ESC
- exit (0);
- break;
- case 43: // key '+' to add a ghost //could be 65 (a) o 97(A)
- // Siempre insertamos en el mismo sitio, podemos mirar de cambiar el sitio. Nota posicion x e y en mapa.
- {
- if (ghosts < 6){
- ghosts++;
- Ghost gnew(ghosts,&m,&s);
- playingGhosts.push_back(gnew);
- }
- else cout << "No podemos añadir fantasma. Numero máximo de fantasmas es 6 " << playingGhosts.size() << endl;
- break;
- }
- case 45:{ // key '-' to remove a ghost //could be 81 (q) o 113 (Q)
- //Nos aseguramos de que siempre haya al menos un fantasma jugando
- if (ghosts > 1)
- if (playingGhosts.size() > 1) {
- glDisable(GL_LIGHT2);glDisable(GL_LIGHT3);glDisable(GL_LIGHT4);glDisable(GL_LIGHT5);glDisable(GL_LIGHT6);glDisable(GL_LIGHT7);
- cout << "fantasma nuero:" << ghosts;
- ghosts--;
- playingGhosts.pop_back();
- cout << "EplayingGhosts.size(liminamos fantasma. Numero de fantasmas en vector: " << playingGhosts.size() << endl;
- }
- else cout << "No podemos eliminar fantasma. Al menos tiene que haber un fantasma en juego.Numero de fantasmas en vector: " << playingGhosts.size() << endl;
- break;
- }
- case 105 : // Code 105 is 'i'
- if ( anglebeta <= (90-4) ) anglebeta=(anglebeta+3);
- break;
- case 107: //Code 107 is k
- if ( anglebeta >= (-90+4)) anglebeta=anglebeta-3;
- break;
- case 106: //Code 106 is j
- anglealpha=(anglealpha+3)%360;
- break;
- case 108: //Code 108 is l
- anglealpha=(anglealpha-3+360)%360;
- break;
- case 115: //Code 115 is s
- ShowHighScoresTable();
- break;
- }
- glutPostRedisplay();
- }
- void specialkeyboard(int key,int x,int y)
- {
- switch(key)
- {
- case GLUT_KEY_UP:
- direccion=NORTH;
- break;
- case GLUT_KEY_DOWN:
- direccion=SOUTH;
- break;
- case GLUT_KEY_LEFT:
- direccion=WEST;
- break;
- case GLUT_KEY_RIGHT:
- direccion=EAST;
- break;
- }
- glutPostRedisplay();
- }
- //-----------------------------------------------
- void idle()
- {
- /******************************************* ARDUINO *****************************************************************/
- //readArduino();
- long t;
- t=glutGet(GLUT_ELAPSED_TIME);
- if(last_t==0)
- last_t=t;
- else
- {
- //moviment continuo pacman
- myPacman->integrate(t-last_t);
- //movimiento fantasmas
- for(int i = 0; i < playingGhosts.size(); i++)
- {
- playingGhosts[i].integrate(t-last_t);
- }
- last_t=t;
- }
- glutPostRedisplay();
- }
- void updatePacmanMovement()
- {
- switch(direccion)
- {
- case NORTH:
- myPacman->moveNorth( &m, &s,pacmanVelocityFactor);
- break;
- case SOUTH:
- myPacman->moveSouth( &m, &s,pacmanVelocityFactor);
- break;
- case WEST:
- myPacman->moveWest( &m, &s,pacmanVelocityFactor);
- break;
- case EAST:
- myPacman->moveEast( &m, &s,pacmanVelocityFactor);
- break;
- }
- }
- /*--------------------------------------------------------*/
- /*--------------------------------------------------------*/
- void ReadJPEG(char *filename,unsigned char **image,int *width, int *height)
- {
- struct jpeg_decompress_struct cinfo;
- struct jpeg_error_mgr jerr;
- FILE * infile;
- unsigned char **buffer;
- int i,j;
- cinfo.err = jpeg_std_error(&jerr);
- jpeg_create_decompress(&cinfo);
- if ((infile = fopen(filename, "rb")) == NULL) {
- printf("Unable to open file %s\n",filename);
- exit(1);
- }
- jpeg_stdio_src(&cinfo, infile);
- jpeg_read_header(&cinfo, TRUE);
- jpeg_calc_output_dimensions(&cinfo);
- jpeg_start_decompress(&cinfo);
- *width = cinfo.output_width;
- *height = cinfo.output_height;
- *image=(unsigned char*)malloc(cinfo.output_width*cinfo.output_height*cinfo.output_components);
- buffer=(unsigned char **)malloc(1*sizeof(unsigned char **));
- buffer[0]=(unsigned char *)malloc(cinfo.output_width*cinfo.output_components);
- i=0;
- while (cinfo.output_scanline < cinfo.output_height) {
- jpeg_read_scanlines(&cinfo, buffer, 1);
- for(j=0;j<cinfo.output_width*cinfo.output_components;j++)
- {
- (*image)[i]=buffer[0][j];
- i++;
- }
- }
- free(buffer);
- jpeg_finish_decompress(&cinfo);
- // fclose(filename);
- fclose(infile);
- }
- /*--------------------------------------------------------*/
- /*--------------------------------------------------------*/
- void LoadTexture(char *filename,int dim)
- {
- unsigned char *buffer;
- unsigned char *buffer2;
- int width,height;
- long i,j;
- long k,h;
- ReadJPEG(filename,&buffer,&width,&height);
- buffer2=(unsigned char*)malloc(dim*dim*3);
- //-- The texture pattern is subsampled so that its dimensions become dim x dim --
- for(i=0;i<dim;i++)
- for(j=0;j<dim;j++)
- {
- k=i*height/dim;
- h=j*width/dim;
- buffer2[3*(i*dim+j)]=buffer[3*(k*width +h)];
- buffer2[3*(i*dim+j)+1]=buffer[3*(k*width +h)+1];
- buffer2[3*(i*dim+j)+2]=buffer[3*(k*width +h)+2];
- }
- glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
- glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
- glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,dim,dim,0,GL_RGB,GL_UNSIGNED_BYTE,buffer2);
- free(buffer);
- free(buffer2);
- }
- void nextLevel(){
- //if(m.getLevel()>9) //you win //usleep //Level = 1
- m.setupMaze(ROWS, COLUMNS, m.getLevel()+4);
- m.printMaze();
- //colocar pacman
- direccion = 3;
- myPacman->startLevel(&m, &s);
- m.setPoints(myPacman->getPoints());
- //colocar fantasmas
- playingGhosts.clear();
- ghosts = 1;
- Ghost g1(ghosts,&m,&s);
- playingGhosts.push_back(g1);
- ghosts++;
- Ghost g2(ghosts,&m,&s);
- playingGhosts.push_back(g2);
- ghosts++;
- Ghost g3(ghosts,&m,&s);
- playingGhosts.push_back(g3);
- ghosts++;
- Ghost g4(ghosts,&m,&s);
- playingGhosts.push_back(g4);
- }
- void pacmanDead(int i)
- {
- /*if(playingGhosts[i].getColumn() == myPacman->getColumn())
- if(playingGhosts[i].getRow() == myPacman->getRow()){
- usleep(3500000);
- cout << "Has muerto" << endl;
- //INICIALIZAR osicion pacman
- }
- */
- //10 es el margen de captura de error....
- if(playingGhosts[i].getpixelScreenX()- 10 < myPacman->getpixelScreenX() && myPacman->getpixelScreenX() <= playingGhosts[i].getpixelScreenX()+ 10 )
- if(playingGhosts[i].getpixelScreenY()- 10 < myPacman->getpixelScreenY() && myPacman->getpixelScreenY() <= playingGhosts[i].getpixelScreenY()+ 10 ){
- usleep(3500000);
- cout << "Has muerto" << endl;
- myPacman->setLives(myPacman->getLives()-1);
- if ( myPacman->getLives() == 0)
- {
- //highscores.push_back(HighScoreEntry("pepito", 400)
- char cadenaover[30] = "Game Over";
- //strcat(cadenaover," ");
- output(200,200,255.0,255.0,255.0,cadenaover);
- gameover=true;
- usleep(6500000);
- //condiciones para entrar en el hall of fame
- if ( ( myPacman->getPoints() > highscores[0].getScore() ) || ( highscores.size() < MAXHIGHSCORES ) || ( highscores.size() == 0) )
- {
- char Nombre[30]; // Usaremos una cadena para almacenar
- cout << "Enhorabuena has entrado en el Hall of Fame" << endl << "Introduce tu nombre :" << endl;
- // Lectura de las variables
- cin >> Nombre;
- // Visualización de los datos leídos
- cout << "Nombre:" << Nombre << endl;
- if ( highscores.size() < MAXHIGHSCORES )
- highscores.push_back( HighScoreEntry(Nombre,myPacman->getPoints()));
- else
- { //Esta la tabla llena, hemos de vaciar el menor el primero de la lista
- //myvector.erase (myvector.begin()+5);
- highscores.erase(highscores.begin());
- highscores.push_back(HighScoreEntry(Nombre,myPacman->getPoints() ));
- //Reordeno lista por si acaso
- // std::sort( highscores.begin(), highscores.end() );
- }
- //Reordeno lista por si acaso
- std::sort( highscores.begin(), highscores.end() );
- WriteHighScoresToFile();
- cout << "Partida finalizada adios";
- }
- // salimos juego
- exit(0);
- }
- else myPacman->startLevel(&m,&s);
- //INICIALIZAR osicion pacman
- }
- }
- void output(int x, int y, float r, float g, float b, char *string)
- {
- glColor3f( r, g, b );
- glMatrixMode(GL_PROJECTION);
- glLoadIdentity();
- //glPushMatrix();
- //glOrtho(-WIDTH*0.6,WIDTH*0.6,-HEIGHT*0.6,HEIGHT*0.6, 10, 2000);
- glOrtho(-WIDTH,WIDTH,-HEIGHT,HEIGHT, 10, 2000);
- glMatrixMode(GL_MODELVIEW);
- glRasterPos2f(x, y);
- int len, i;
- len = (int)strlen(string);
- for (i = 0; i < len; i++) {
- glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, string[i]);
- }
- }
- void outputPixeles(int x, int y, float r, float g, float b, char *string)
- {
- glMatrixMode(GL_PROJECTION);
- glLoadIdentity();
- //glPushMatrix();
- glOrtho(0.0,WIDTH, 0.0,HEIGHT, -1.0, 1.0);
- glMatrixMode(GL_MODELVIEW);
- glColor3f( r, g, b );
- // glWindow2f(x, y);
- glWindowPos2f(x,y);
- int len, i;
- len = (int)strlen(string);
- for (i = 0; i < len; i++) {
- glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, string[i]);
- }
- //glPopMatrix();
- }
- void WriteHighScoresToFile()
- {
- //std::ofstream myfile;
- //myfile.open ("example.txt");
- std::ofstream myfile("example.txt", std::ios::out | std::ios::trunc);
- int i=0;
- while (i < highscores.size())
- {
- myfile << highscores[i];
- i++;
- }
- //myfi
- /*
- for(int i = 0; i < highscores.size(); i++)
- {
- myfile << highscores[i];
- }
- //myfile.close();*/
- }
- void ReadHighScoresFromFile()
- {
- std::ifstream ifile("example.txt");
- HighScoreEntry tentry;
- while(ifile >> tentry) {
- highscores.push_back(tentry);
- }
- /*while(ifile) {
- ifile >> tentry;
- highscores.push_back(tentry);
- }*/
- }
- void ShowInformation()
- {
- // glOrtho(-1000,1000,-1000,1000,100,20000);
- //glMatrixMode(GL_MODELVIEW);
- if ( gameover==false)
- {
- char Result[6]; // string which will contain the number
- sprintf ( Result, "%d", myPacman->getPoints()); // %d makes the result be a decimal integer
- char cadena1[30] = "Score : ";
- strcat(cadena1,Result);
- output(200,200,255.0,255.0,255.0,cadena1);
- sprintf ( Result, "%d", myPacman->getLives()); // %d makes the result be a decimal integer
- char cadena2[30] = "Lives : ";
- strcat(cadena2,Result);
- output(50,50,255.0,255.0,255.0,cadena2);
- }
- else output(50,50,255.0,255.0,255.0,"Game over pringao");
- }
- void ShowHighScoresTable()
- {
- // glOrtho(-1000,1000,-1000,1000,100,20000);
- //glMatrixMode(GL_MODELVIEW);
- //for(int i = highscores.size(); i < 0 ; i--)
- for(int i = 0; i < highscores.size(); i++)
- {
- char Result[6]; // string which will contain the number
- sprintf ( Result, "%d", i); // %d makes the result be a decimal integer
- char cadena1[30] = "Rank : ";
- strcat(cadena1,Result);
- char cadena2[30] = "Name: ";
- strcat(cadena1,cadena2);
- //strcat(cadena1,cadena2);
- //strcat(cadena1, highscores[i].getName());
- //string tmp = "cat";
- char cadena3[50];
- strcpy(cadena3, (highscores[i].getName()).c_str());
- //For safety, you might prefer:
- /*
- string tmp = "cat";
- char tab2[1024];
- strncpy(tab2, tmp.c_str(), sizeof(tab2));
- tab2[sizeof(tab2) - 1] = 0;
- */
- strcat(cadena1,cadena3);
- char cadena4[30] = "Points: ";
- strcat(cadena1,cadena4);
- //strcat(cadena1,cadena3);
- char Result2[6]; // string which will contain the number
- sprintf ( Result2, "%d", highscores[i].getScore()); // %d makes the result be a decimal integer
- strcat(cadena1,Result2);
- //x,y en funcion de i para poner mas arriba o abajo...
- output(50,50,255.0,255.0,255.0,cadena1);
- // gameover=true;
- cout << "Posicion Tabla " << i << cadena1;
- }
- }
- void initArduinousb(){
- cout <<"Init Arduino"<<endl;
- struct termios toptions;
- // open serial port
- fileDesc = open("/dev/cu.usbmodem1421", O_RDWR | O_NOCTTY);
- printf("fd opened as %i\n", fileDesc);
- // wait for the Arduino to reboot
- usleep(3500000);
- // get current serial port settings
- tcgetattr(fileDesc, &toptions);
- // set 9600 baud both ways
- cfsetispeed(&toptions, B9600);
- cfsetospeed(&toptions, B9600);
- // 8 bits, no parity, no stop bits
- toptions.c_cflag &= ~PARENB;
- toptions.c_cflag &= ~CSTOPB;
- toptions.c_cflag &= ~CSIZE;
- toptions.c_cflag |= CS8;
- //Canonical mode
- toptions.c_lflag |= ICANON;
- // commit the serial port settings
- tcsetattr(fileDesc, TCSANOW, &toptions);
- cout << "Calibrating GSR "<<endl;
- int calIndex = 0;
- while(1){
- cout << "calibrating GSR...: "<<calIndex<<endl;
- bool readedValue = calibrateGSR();
- if(readedValue){
- calIndex++;
- }
- if(calIndex==30){
- break;
- }
- //sleep(1);
- }
- cout << "Calibrating HeartRate "<<endl;
- calIndex = 0;
- while(1){
- cout << "calibrating HeartRate...: "<<calIndex<<endl;
- bool readedValue = calibrateHeartRate();
- if(readedValue){
- calIndex++;
- }
- if(calIndex==30){
- break;
- }
- //sleep(1);
- }
- gsrAverage = gsrSum/30;
- heartRateAverage = heartRateSum/30;
- cout << "GSR Average: "<<gsrAverage<<endl;
- cout << "Pulse Average: "<<heartRateAverage<<endl;
- }
- void readArduino(){
- // Send byte to trigger Arduino to send string back
- write(fileDesc, "0", 1);
- // Receive string from Arduino
- arduinoRcv = read(fileDesc, buf, 64);
- // insert terminating zero in the string
- buf[arduinoRcv] = 0;
- //printf("%i bytes read, buffer contains: %s\n", arduinoRcv, buf);
- //printf("\n");
- joystick();
- temperature();
- heartRate();
- skinResistance();
- bluetooth();
- }
- void heartRate(){
- if(buf[0]=='H'){
- string str(buf);
- string heartrate = str.substr(2);
- cout << "HeartRate: "<< heartrate<<endl;
- try {
- double heartDouble = stod(heartrate);
- if(heartDouble>heartRateAverage+30){
- pacmanVelocityFactor = 4;
- }else if(heartDouble>heartRateAverage+15){
- pacmanVelocityFactor = 3;
- }else if(heartDouble>heartRateAverage){
- pacmanVelocityFactor = 2;
- }else{
- pacmanVelocityFactor = 1;
- }
- }
- catch (const std::invalid_argument& ia) {
- pacmanVelocityFactor = 1;
- std::cerr << "Invalid argument: " << ia.what() << '\n';
- }
- }
- }
- void skinResistance(){
- if(buf[0]=='G'){
- string str(buf);
- string gsr = str.substr(2);
- cout << "GSR: "<< gsr<<endl;
- try {
- double gsrDouble = stod(gsr);
- cout << "GSR: "<< gsrDouble<<endl;
- if(gsrDouble<gsrAverage){
- ghostVelocityFactor = 2;
- }else{
- ghostVelocityFactor = 1;
- }
- }
- catch (const std::invalid_argument& ia) {
- ghostVelocityFactor = 1;
- std::cerr << "Invalid argument: " << ia.what() << '\n';
- }
- }
- }
- void temperature(){
- if(buf[0]=='T'){
- string str(buf);
- string temperature = str.substr(2);
- cout << "Temperature: "<< temperature<<endl;
- try {
- double temperatureDouble = stod(temperature);
- if(temperatureDouble>29.0){
- //Red
- color[0]=0.8; color[1]=0.2; color[2]=0.2; color[3]=1;
- }else if(temperatureDouble<20.0){
- //Blue
- color[0]=0.2; color[1]=0.2; color[2]=0.8; color[3]=1;
- }
- else{
- color[0]=0.2; color[1]=0.2; color[2]=0.2; color[3]=1;
- }
- }
- catch (const std::invalid_argument& ia) {
- ghostVelocityFactor = 1;
- std::cerr << "Invalid argument: " << ia.what() << '\n';
- }
- }
- }
- void joystick(){
- if(buf[0]=='X'){
- cout << "X JOYSTICK: "<< buf[2]<<endl;
- if(buf[2]=='-'){
- direccion=WEST;
- }else if(buf[2]=='0'){
- //Do nothing
- }else{
- direccion=EAST;
- }
- }
- if(buf[0]=='Y'){
- cout << "Y JOYSTICK: "<< buf[2]<<endl;
- if(buf[2]=='-'){
- direccion=SOUTH;
- }else if(buf[2]=='0'){
- //Do nothing
- }else{
- direccion=NORTH;
- }
- }
- if(buf[0]=='S'){
- if(buf[2]=='0'){
- exit (0);
- }
- }
- glutPostRedisplay();
- }
- void bluetooth(){
- if(buf[0]=='i'){
- if ( anglebeta <= (90-4) ) anglebeta=(anglebeta+3);
- }else if(buf[0]=='k'){
- if ( anglebeta >= (-90+4)) anglebeta=anglebeta-3;
- }else if(buf[0]=='j'){
- anglealpha=(anglealpha+3)%360;
- }else if(buf[0]=='l'){
- anglealpha=(anglealpha-3+360)%360;
- }
- glutPostRedisplay();
- }
- bool calibrateHeartRate(){
- // Send byte to trigger Arduino to send string back
- write(fileDesc, "0", 1);
- // Receive string from Arduino
- arduinoRcv = read(fileDesc, buf, 64);
- // insert terminating zero in the string
- buf[arduinoRcv] = 0;
- if(buf[0]=='H'){
- string str(buf);
- string heartrate = str.substr(2);
- try {
- double heartDouble = stod(heartrate);
- heartRateSum+=heartDouble;
- return true;
- }
- catch (const std::invalid_argument& ia) {
- return false;
- }
- }else{
- return false;
- }
- }
- bool calibrateGSR(){
- // Send byte to trigger Arduino to send string back
- write(fileDesc, "0", 1);
- // Receive string from Arduino
- arduinoRcv = read(fileDesc, buf, 64);
- // insert terminating zero in the string
- buf[arduinoRcv] = 0;
- if(buf[0]=='G'){
- string str(buf);
- string gsr = str.substr(2);
- double gsrDouble = stod(gsr);
- gsrSum+=gsrDouble;
- return true;
- }else{
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement