Advertisement
Guest User

Untitled

a guest
Jan 27th, 2016
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 27.53 KB | None | 0 0
  1. * main.cpp
  2. *
  3. * Created on: 13/10/2015
  4. * Author: Eduardo Gutiérrez
  5. * Llorenç Toldrà Porta
  6. */
  7.  
  8. #include <vector>
  9. #include <unistd.h>
  10. #include <time.h>
  11. #include <algorithm>
  12. #include "Particle.h"
  13. #include "Pacman.h"
  14. #include "Ghost.h"
  15. #include "HighScoreEntry.h"
  16.  
  17. /*** For arduino**/
  18. #include <stdlib.h>
  19. #include <stdio.h>
  20. //#include <string.h>
  21. #include <stdint.h>
  22. #include <fcntl.h>
  23. #include <termios.h>
  24. #include <errno.h>
  25. #include <sys/ioctl.h>
  26. #include <iostream>
  27. #include <fstream>
  28. //#include <GL/glew.h>
  29.  
  30. #define ROWS 19//19
  31. #define COLUMNS 40//40
  32. #define LEVEL 1
  33.  
  34. #define WIDTH 800
  35. #define HEIGHT 600
  36.  
  37. #define WINDOW_X 50
  38. #define WINDOW_Y 50
  39.  
  40. #define NORTH 1
  41. #define SOUTH 2
  42. #define WEST 3
  43. #define EAST 4
  44.  
  45. #define MAXHIGHSCORES 10
  46.  
  47. void display();
  48. void keyboard(unsigned char c,int x,int y);
  49. void specialkeyboard(int key,int x,int y);
  50. void PositionObserver(float alpha,float beta,int radi);
  51. void idle();
  52. void updatePacmanMovement();
  53. void ReadJPEG(char *filename,unsigned char **image,int *width, int *height);
  54. void LoadTexture(char *filename,int dim);
  55. void nextLevel();
  56. void pacmanDead(int i);
  57. void output(int x, int y, float r, float g, float b, char *string);
  58. void outputPixeles(int x, int y, float r, float g, float b, char *string);
  59. void WriteHighScoresToFile();
  60. void ReadHighScoresFromFile();
  61. void ShowInformation();
  62. void ShowHighScoresTable();
  63.  
  64. void initArduinousb();
  65. void readArduino();
  66. void joystick();
  67. void temperature();
  68. void heartRate();
  69. void skinResistance();
  70. void bluetooth();
  71.  
  72. bool calibrateHeartRate();
  73. bool calibrateGSR();
  74.  
  75. using namespace std;
  76. using namespace RandomMaze;
  77.  
  78.  
  79. //Definición de variables.
  80. vector<Ghost> playingGhosts;
  81. vector< HighScoreEntry > highscores;
  82. Maze m;
  83. Pacman *myPacman;
  84. Screen s ( WIDTH,HEIGHT);
  85. int ghosts = 1;
  86. long last_t=0;
  87. int direccion;
  88. int anglealpha = 0;
  89. int anglebeta = 0;
  90. bool gameover;
  91.  
  92. int fileDesc, arduinoRcv, arduinoBufIter;
  93. char buf[64] = "temp text";
  94.  
  95. char myword[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
  96.  
  97.  
  98. GLint position[4];
  99. GLfloat color[4];
  100.  
  101. int pacmanVelocityFactor = 1;
  102. int ghostVelocityFactor = 1;
  103.  
  104. int gsrAverage = 0;
  105. int gsrSum = 0;
  106. int heartRateAverage = 0;
  107. int heartRateSum = 0;
  108.  
  109. int main (int argc, char *argv[])
  110. {
  111.  
  112. /******************************************* ARDUINO *****************************************************************/
  113. //initArduinousb();
  114. srand(time(NULL));
  115.  
  116. anglealpha=90;
  117. anglebeta=90;
  118.  
  119. m.setupMaze(ROWS, COLUMNS, LEVEL);
  120. m.printMaze();
  121.  
  122. myPacman = new Pacman( &m, &s);
  123.  
  124. gameover=false;
  125.  
  126. highscores.clear();
  127. //highscores.push_back(HighScoreEntry("test",100));
  128. highscores.push_back(HighScoreEntry("pepito", 400));
  129. //highscores.push_back(HighScoreEntry("Juan", 15));
  130. //highscores.push_back(HighScoreEntry("Manolo",250));
  131. //highscores.clear();
  132.  
  133. cout << "Tengo en higscores " << highscores.size();
  134.  
  135. ReadHighScoresFromFile();
  136.  
  137. cout << "He leido del fichero" << highscores.size();
  138. //highscores.push_back(HighScoreEntry("Manolo2",500));
  139. //ReadTableFromFile();
  140. // std::sort(highscores.begin(), highscores.end(), less_than_key());
  141. //cout << highscores[3];
  142. std::sort( highscores.begin(), highscores.end() );
  143.  
  144. WriteHighScoresToFile();
  145. cout << "Tengo en despues de ordenar y escribir higscores " << highscores.size();
  146. //cout << "Ultimo es" << highscores[3].getScore() << "nombre" << highscores[3].getName();
  147.  
  148. /*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,
  149. * 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.*/
  150. glutInit(&argc, argv);
  151.  
  152. /*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
  153. * dos buffers para pintar en uno mientras se visualiza el otro. Con esto conseguimos una mayor fluidez en escenas.
  154. */
  155. glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
  156. //glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
  157.  
  158. //Posición x e y de la esquina superior izquierda de la nueva ventana, con respecto al escritorio en el que se trabaje.
  159. glutInitWindowPosition(WINDOW_X, WINDOW_Y);
  160.  
  161. //Comprobamos que el ancho y alto de nuestra ventana es menor que los pixeles de la pantalla.
  162. //En ese caso no cabria nuestra ventana en la pantalla
  163. if ( glutGet(GLUT_SCREEN_WIDTH) == 0 || glutGet(GLUT_SCREEN_WIDTH) < WIDTH)
  164. throw out_of_range("Error: El ancho no puede ser cero. Error ancho pantalla");
  165.  
  166. if (glutGet(GLUT_SCREEN_HEIGHT) == 0 || glutGet(GLUT_SCREEN_HEIGHT) < HEIGHT)
  167. throw std::out_of_range("Error: El alto no puede ser cero. Error alto pantalla");
  168.  
  169. //El ancho y alto de la nueva ventana.
  170. glutInitWindowSize(WIDTH,HEIGHT);
  171.  
  172. // Esta función es la que propiamente crea la ventana y el parámetro es el nombre de la misma.
  173. glutCreateWindow("Random Maze");
  174.  
  175. glEnable(GL_DEPTH_TEST);
  176. glEnable(GL_LIGHTING);
  177.  
  178. //Texture 0 is for Wall ceiling
  179. glBindTexture(GL_TEXTURE_2D,0);
  180. LoadTexture("Groundplant64x64.jpg",64);
  181. //MyLoadTexture("Groundplant64x64.jpg");
  182. //Texture 1 for food
  183. glBindTexture(GL_TEXTURE_2D,1);
  184. LoadTexture("paperwhite.jpg",64);
  185.  
  186. //Texture 2 is for passage
  187. glBindTexture(GL_TEXTURE_2D,2);
  188. LoadTexture("FloorsMedieval64x64.jpg",64);
  189.  
  190. //Texture 3 is for Blinky type ( red ghost)
  191. glBindTexture(GL_TEXTURE_2D,3);
  192. LoadTexture("redGlass.jpg",64);
  193.  
  194. //Texture 4 is for Pinky type ( pink ghost)
  195. glBindTexture(GL_TEXTURE_2D,4);
  196. LoadTexture("ghostPink.jpg",64);
  197.  
  198. //Texture 5 is for Inky type ( cyan ghost)
  199. glBindTexture(GL_TEXTURE_2D,5);
  200. LoadTexture("ghostCyan.jpg",64);
  201.  
  202. //Texture 6 is for Pokey type ( orange ghost)
  203. glBindTexture(GL_TEXTURE_2D,6);
  204. LoadTexture("ghostOrange.jpg",64);
  205.  
  206. //Texture 7 is for Pacman
  207. glBindTexture(GL_TEXTURE_2D,7);
  208. LoadTexture("fire.jpg",64);
  209.  
  210.  
  211. Ghost g1(ghosts,&m,&s);
  212. playingGhosts.push_back(g1);
  213.  
  214. ghosts++;
  215. Ghost g2(ghosts,&m,&s);
  216. playingGhosts.push_back(g2);
  217.  
  218. ghosts++;
  219. Ghost g3(ghosts,&m,&s);
  220. playingGhosts.push_back(g3);
  221.  
  222. ghosts++;
  223. Ghost g4(ghosts,&m,&s);
  224. playingGhosts.push_back(g4);
  225.  
  226. glutDisplayFunc(display);
  227.  
  228. glutKeyboardFunc(keyboard);
  229.  
  230. glutSpecialFunc(specialkeyboard);
  231.  
  232. glutIdleFunc(idle);
  233.  
  234. /*Especifica la matriz actual para realizar la composición. En ogl las operaciones de rotación, translación, escalado, etc. se
  235. * realizan a través de matrices de transformación. Dependiendo de lo que estemos tratando, hay tres tipos de matriz (que son
  236. * los tres posibles flags que puede llevar de parámetro la función): matriz de proyección (GL_PROJECTION),
  237. * matriz de modelo (GL_MODELVIEW) y matriz de textura (GL_TEXTURE). Con esta función indicamos a cual de estas tres deben
  238. * afectar las operaciones. Concretamente, GL_PROJECTION afecta a las vistas o perspectivas o proyecciones.
  239. */
  240. glMatrixMode(GL_PROJECTION);
  241.  
  242. //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.
  243. glutMainLoop();
  244. return 0;
  245.  
  246. }
  247.  
  248. //la función display() al ser pasada a glutDisplayFunc(), será llamada cada vez que haya que redibujar la ventana
  249.  
  250. void display()
  251. {
  252. /******************************************* ARDUINO *****************************************************************/
  253. //readArduino();
  254. if(m.getFood() <= 0){
  255. usleep(3500000);
  256. nextLevel();
  257. }
  258.  
  259. myPacman->setPoints(m.getPoints());
  260.  
  261.  
  262. //m.getFood()
  263.  
  264. //GLint position[4];
  265. //GLfloat color[4];
  266. GLfloat colorDiff[4];
  267.  
  268. /*Con esto se define el color con el que se borrara el buffer al hacer un glClear().
  269. * Los 3 primeros parámetros son las componentes R, G y B, siguiendo un rango de [0..1]. La última es el valor alpha.
  270. */
  271. glClearColor(0.0,0.0,0.0,0.0);
  272.  
  273. /* Borra un buffer o una combinación de varios. En este caso, borra el buffer de color (en realidad, cada componente
  274. R G y B tienen un buffer distinto, pero aquí los trata como el mismo), el que se pinta después en pantalla.
  275. Para borrarlos utiliza el color que ha sido previamente definido en init() mediante glClearColor(), en este caso,
  276. el (0,0,0,0) es decir, pinta el buffer de negro.*/
  277. //glClear(GL_COLOR_BUFFER_BIT);
  278.  
  279. glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
  280.  
  281. glMatrixMode(GL_MODELVIEW);
  282. glLoadIdentity();
  283.  
  284.  
  285. PositionObserver(anglealpha,anglebeta,450);
  286.  
  287. glMatrixMode(GL_PROJECTION);
  288. glLoadIdentity();
  289.  
  290. glOrtho(-WIDTH*0.6,WIDTH*0.6,-HEIGHT*0.6,HEIGHT*0.6,10,2000);
  291. glMatrixMode(GL_MODELVIEW);
  292.  
  293. glPolygonMode(GL_FRONT,GL_FILL);
  294. glPolygonMode(GL_BACK,GL_LINE);
  295.  
  296. //-- Ambient light
  297.  
  298. position[0]=0; position[1]=0; position[2]=0; position[3]=1;
  299.  
  300. glLightiv(GL_LIGHT0,GL_POSITION,position);
  301.  
  302. color[0]=0.2; color[1]=0.2; color[2]=0.2; color[3]=1;
  303. /******************************************* ARDUINO *****************************************************************/
  304. //temperature(); //Comentar liniea de color superior
  305. glLightfv(GL_LIGHT0,GL_AMBIENT,color);
  306. colorDiff[0]=0.0; colorDiff[1]=0.0; colorDiff[2]=0.0; colorDiff[3]=1;
  307. glLightfv(GL_LIGHT0,GL_DIFFUSE,colorDiff);
  308. glEnable(GL_LIGHT0);
  309.  
  310. myPacman->lightOn(&m,&s,direccion);
  311.  
  312. for(int i = 0; i < playingGhosts.size(); i++)
  313. {
  314. playingGhosts[i].lightOn(&m,&s);
  315. }
  316.  
  317.  
  318. m.draw3D(s.getWidth(),s.getHeigth());
  319. myPacman->draw3D(&m,&s);
  320.  
  321. for(int i = 0; i < playingGhosts.size(); i++)
  322. {
  323. playingGhosts[i].draw3D(&m,&s);
  324. }
  325.  
  326. updatePacmanMovement();
  327.  
  328. for(int i = 0; i < playingGhosts.size(); i++)
  329. {
  330.  
  331. pacmanDead(i);
  332.  
  333.  
  334. switch(rand()%4+1)
  335. {
  336. case 1:
  337. playingGhosts[i].moveNorth( &m, &s,ghostVelocityFactor);
  338. break;
  339. case 2:
  340. playingGhosts[i].moveSouth( &m, &s,ghostVelocityFactor);
  341. break;
  342. case 3:
  343. playingGhosts[i].moveWest( &m, &s,ghostVelocityFactor);
  344. break;
  345. case 4:
  346. playingGhosts[i].moveEast( &m, &s,ghostVelocityFactor);
  347. break;
  348. default: playingGhosts[i].moveNorth( &m, &s,ghostVelocityFactor);
  349.  
  350. }
  351.  
  352. }
  353.  
  354. ShowInformation();
  355.  
  356. glutSwapBuffers();
  357. }
  358.  
  359. void PositionObserver(float alpha,float beta,int radi)
  360. {
  361. float x,y,z;
  362. float upx,upy,upz;
  363. float modul;
  364.  
  365. x = (float)radi*cos(alpha*2*PI/360.0)*cos(beta*2*PI/360.0);
  366. y = (float)radi*sin(beta*2*PI/360.0);
  367. z = (float)radi*sin(alpha*2*PI/360.0)*cos(beta*2*PI/360.0);
  368.  
  369. if (beta>0)
  370. {
  371. upx=-x;
  372. upz=-z;
  373. upy=(x*x+z*z)/y;
  374. }
  375. else if(beta==0)
  376. {
  377. upx=0;
  378. upy=1;
  379. upz=0;
  380. }
  381. else
  382. {
  383. upx=x;
  384. upz=z;
  385. upy=-(x*x+z*z)/y;
  386. }
  387.  
  388.  
  389. modul=sqrt(upx*upx+upy*upy+upz*upz);
  390.  
  391. upx=upx/modul;
  392. upy=upy/modul;
  393. upz=upz/modul;
  394.  
  395. gluLookAt(x,y,z, 0.0, 0.0, 0.0, upx,upy,upz);
  396. }
  397.  
  398.  
  399.  
  400. //-----------------------------------------------
  401. void keyboard(unsigned char c,int x,int y)
  402. {
  403.  
  404. switch(c)
  405. {
  406. case 27: // ESC
  407. exit (0);
  408. break;
  409. case 43: // key '+' to add a ghost //could be 65 (a) o 97(A)
  410. // Siempre insertamos en el mismo sitio, podemos mirar de cambiar el sitio. Nota posicion x e y en mapa.
  411. {
  412. if (ghosts < 6){
  413. ghosts++;
  414. Ghost gnew(ghosts,&m,&s);
  415. playingGhosts.push_back(gnew);
  416. }
  417. else cout << "No podemos añadir fantasma. Numero máximo de fantasmas es 6 " << playingGhosts.size() << endl;
  418. break;
  419. }
  420. case 45:{ // key '-' to remove a ghost //could be 81 (q) o 113 (Q)
  421. //Nos aseguramos de que siempre haya al menos un fantasma jugando
  422. if (ghosts > 1)
  423. if (playingGhosts.size() > 1) {
  424. glDisable(GL_LIGHT2);glDisable(GL_LIGHT3);glDisable(GL_LIGHT4);glDisable(GL_LIGHT5);glDisable(GL_LIGHT6);glDisable(GL_LIGHT7);
  425. cout << "fantasma nuero:" << ghosts;
  426. ghosts--;
  427. playingGhosts.pop_back();
  428. cout << "EplayingGhosts.size(liminamos fantasma. Numero de fantasmas en vector: " << playingGhosts.size() << endl;
  429. }
  430. else cout << "No podemos eliminar fantasma. Al menos tiene que haber un fantasma en juego.Numero de fantasmas en vector: " << playingGhosts.size() << endl;
  431.  
  432. break;
  433. }
  434. case 105 : // Code 105 is 'i'
  435. if ( anglebeta <= (90-4) ) anglebeta=(anglebeta+3);
  436. break;
  437. case 107: //Code 107 is k
  438. if ( anglebeta >= (-90+4)) anglebeta=anglebeta-3;
  439. break;
  440. case 106: //Code 106 is j
  441. anglealpha=(anglealpha+3)%360;
  442. break;
  443. case 108: //Code 108 is l
  444. anglealpha=(anglealpha-3+360)%360;
  445. break;
  446. case 115: //Code 115 is s
  447. ShowHighScoresTable();
  448. break;
  449.  
  450.  
  451.  
  452. }
  453. glutPostRedisplay();
  454. }
  455.  
  456. void specialkeyboard(int key,int x,int y)
  457. {
  458.  
  459. switch(key)
  460. {
  461. case GLUT_KEY_UP:
  462. direccion=NORTH;
  463. break;
  464. case GLUT_KEY_DOWN:
  465. direccion=SOUTH;
  466. break;
  467. case GLUT_KEY_LEFT:
  468. direccion=WEST;
  469. break;
  470. case GLUT_KEY_RIGHT:
  471. direccion=EAST;
  472. break;
  473. }
  474. glutPostRedisplay();
  475. }
  476.  
  477. //-----------------------------------------------
  478. void idle()
  479. {
  480. /******************************************* ARDUINO *****************************************************************/
  481. //readArduino();
  482. long t;
  483.  
  484. t=glutGet(GLUT_ELAPSED_TIME);
  485.  
  486. if(last_t==0)
  487. last_t=t;
  488. else
  489. {
  490. //moviment continuo pacman
  491. myPacman->integrate(t-last_t);
  492.  
  493. //movimiento fantasmas
  494. for(int i = 0; i < playingGhosts.size(); i++)
  495. {
  496. playingGhosts[i].integrate(t-last_t);
  497. }
  498.  
  499. last_t=t;
  500. }
  501. glutPostRedisplay();
  502. }
  503.  
  504.  
  505. void updatePacmanMovement()
  506. {
  507.  
  508.  
  509. switch(direccion)
  510. {
  511. case NORTH:
  512. myPacman->moveNorth( &m, &s,pacmanVelocityFactor);
  513. break;
  514. case SOUTH:
  515. myPacman->moveSouth( &m, &s,pacmanVelocityFactor);
  516. break;
  517. case WEST:
  518. myPacman->moveWest( &m, &s,pacmanVelocityFactor);
  519. break;
  520. case EAST:
  521. myPacman->moveEast( &m, &s,pacmanVelocityFactor);
  522. break;
  523.  
  524. }
  525.  
  526. }
  527.  
  528. /*--------------------------------------------------------*/
  529. /*--------------------------------------------------------*/
  530. void ReadJPEG(char *filename,unsigned char **image,int *width, int *height)
  531. {
  532. struct jpeg_decompress_struct cinfo;
  533. struct jpeg_error_mgr jerr;
  534. FILE * infile;
  535. unsigned char **buffer;
  536. int i,j;
  537.  
  538. cinfo.err = jpeg_std_error(&jerr);
  539. jpeg_create_decompress(&cinfo);
  540.  
  541.  
  542. if ((infile = fopen(filename, "rb")) == NULL) {
  543. printf("Unable to open file %s\n",filename);
  544. exit(1);
  545. }
  546.  
  547. jpeg_stdio_src(&cinfo, infile);
  548. jpeg_read_header(&cinfo, TRUE);
  549. jpeg_calc_output_dimensions(&cinfo);
  550. jpeg_start_decompress(&cinfo);
  551.  
  552. *width = cinfo.output_width;
  553. *height = cinfo.output_height;
  554.  
  555.  
  556. *image=(unsigned char*)malloc(cinfo.output_width*cinfo.output_height*cinfo.output_components);
  557.  
  558. buffer=(unsigned char **)malloc(1*sizeof(unsigned char **));
  559. buffer[0]=(unsigned char *)malloc(cinfo.output_width*cinfo.output_components);
  560.  
  561.  
  562. i=0;
  563. while (cinfo.output_scanline < cinfo.output_height) {
  564. jpeg_read_scanlines(&cinfo, buffer, 1);
  565.  
  566. for(j=0;j<cinfo.output_width*cinfo.output_components;j++)
  567. {
  568. (*image)[i]=buffer[0][j];
  569. i++;
  570. }
  571.  
  572. }
  573.  
  574. free(buffer);
  575. jpeg_finish_decompress(&cinfo);
  576. // fclose(filename);
  577. fclose(infile);
  578. }
  579.  
  580.  
  581.  
  582. /*--------------------------------------------------------*/
  583. /*--------------------------------------------------------*/
  584. void LoadTexture(char *filename,int dim)
  585. {
  586. unsigned char *buffer;
  587. unsigned char *buffer2;
  588. int width,height;
  589. long i,j;
  590. long k,h;
  591.  
  592. ReadJPEG(filename,&buffer,&width,&height);
  593.  
  594. buffer2=(unsigned char*)malloc(dim*dim*3);
  595.  
  596. //-- The texture pattern is subsampled so that its dimensions become dim x dim --
  597. for(i=0;i<dim;i++)
  598. for(j=0;j<dim;j++)
  599. {
  600. k=i*height/dim;
  601. h=j*width/dim;
  602.  
  603. buffer2[3*(i*dim+j)]=buffer[3*(k*width +h)];
  604. buffer2[3*(i*dim+j)+1]=buffer[3*(k*width +h)+1];
  605. buffer2[3*(i*dim+j)+2]=buffer[3*(k*width +h)+2];
  606.  
  607. }
  608.  
  609. glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
  610. glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
  611. glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
  612. glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,dim,dim,0,GL_RGB,GL_UNSIGNED_BYTE,buffer2);
  613.  
  614. free(buffer);
  615. free(buffer2);
  616.  
  617. }
  618.  
  619. void nextLevel(){
  620. //if(m.getLevel()>9) //you win //usleep //Level = 1
  621.  
  622. m.setupMaze(ROWS, COLUMNS, m.getLevel()+4);
  623. m.printMaze();
  624.  
  625. //colocar pacman
  626. direccion = 3;
  627. myPacman->startLevel(&m, &s);
  628. m.setPoints(myPacman->getPoints());
  629.  
  630. //colocar fantasmas
  631. playingGhosts.clear();
  632.  
  633. ghosts = 1;
  634. Ghost g1(ghosts,&m,&s);
  635. playingGhosts.push_back(g1);
  636.  
  637. ghosts++;
  638. Ghost g2(ghosts,&m,&s);
  639. playingGhosts.push_back(g2);
  640.  
  641. ghosts++;
  642. Ghost g3(ghosts,&m,&s);
  643. playingGhosts.push_back(g3);
  644.  
  645. ghosts++;
  646. Ghost g4(ghosts,&m,&s);
  647. playingGhosts.push_back(g4);
  648.  
  649. }
  650.  
  651. void pacmanDead(int i)
  652.  
  653. {
  654.  
  655. /*if(playingGhosts[i].getColumn() == myPacman->getColumn())
  656. if(playingGhosts[i].getRow() == myPacman->getRow()){
  657. usleep(3500000);
  658. cout << "Has muerto" << endl;
  659. //INICIALIZAR osicion pacman
  660. }
  661. */
  662. //10 es el margen de captura de error....
  663.  
  664. if(playingGhosts[i].getpixelScreenX()- 10 < myPacman->getpixelScreenX() && myPacman->getpixelScreenX() <= playingGhosts[i].getpixelScreenX()+ 10 )
  665. if(playingGhosts[i].getpixelScreenY()- 10 < myPacman->getpixelScreenY() && myPacman->getpixelScreenY() <= playingGhosts[i].getpixelScreenY()+ 10 ){
  666. usleep(3500000);
  667. cout << "Has muerto" << endl;
  668. myPacman->setLives(myPacman->getLives()-1);
  669.  
  670. if ( myPacman->getLives() == 0)
  671. {
  672. //highscores.push_back(HighScoreEntry("pepito", 400)
  673. char cadenaover[30] = "Game Over";
  674.  
  675. //strcat(cadenaover," ");
  676. output(200,200,255.0,255.0,255.0,cadenaover);
  677. gameover=true;
  678. usleep(6500000);
  679.  
  680. //condiciones para entrar en el hall of fame
  681. if ( ( myPacman->getPoints() > highscores[0].getScore() ) || ( highscores.size() < MAXHIGHSCORES ) || ( highscores.size() == 0) )
  682.  
  683. {
  684. char Nombre[30]; // Usaremos una cadena para almacenar
  685. cout << "Enhorabuena has entrado en el Hall of Fame" << endl << "Introduce tu nombre :" << endl;
  686. // Lectura de las variables
  687. cin >> Nombre;
  688. // Visualización de los datos leídos
  689. cout << "Nombre:" << Nombre << endl;
  690.  
  691. if ( highscores.size() < MAXHIGHSCORES )
  692. highscores.push_back( HighScoreEntry(Nombre,myPacman->getPoints()));
  693. else
  694. { //Esta la tabla llena, hemos de vaciar el menor el primero de la lista
  695. //myvector.erase (myvector.begin()+5);
  696. highscores.erase(highscores.begin());
  697.  
  698. highscores.push_back(HighScoreEntry(Nombre,myPacman->getPoints() ));
  699.  
  700. //Reordeno lista por si acaso
  701. // std::sort( highscores.begin(), highscores.end() );
  702. }
  703. //Reordeno lista por si acaso
  704. std::sort( highscores.begin(), highscores.end() );
  705. WriteHighScoresToFile();
  706. cout << "Partida finalizada adios";
  707. }
  708.  
  709. // salimos juego
  710. exit(0);
  711. }
  712. else myPacman->startLevel(&m,&s);
  713.  
  714. //INICIALIZAR osicion pacman
  715. }
  716. }
  717.  
  718. void output(int x, int y, float r, float g, float b, char *string)
  719. {
  720. glColor3f( r, g, b );
  721. glMatrixMode(GL_PROJECTION);
  722. glLoadIdentity();
  723. //glPushMatrix();
  724. //glOrtho(-WIDTH*0.6,WIDTH*0.6,-HEIGHT*0.6,HEIGHT*0.6, 10, 2000);
  725. glOrtho(-WIDTH,WIDTH,-HEIGHT,HEIGHT, 10, 2000);
  726. glMatrixMode(GL_MODELVIEW);
  727. glRasterPos2f(x, y);
  728. int len, i;
  729. len = (int)strlen(string);
  730. for (i = 0; i < len; i++) {
  731. glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, string[i]);
  732. }
  733. }
  734.  
  735. void outputPixeles(int x, int y, float r, float g, float b, char *string)
  736. {
  737. glMatrixMode(GL_PROJECTION);
  738. glLoadIdentity();
  739. //glPushMatrix();
  740. glOrtho(0.0,WIDTH, 0.0,HEIGHT, -1.0, 1.0);
  741. glMatrixMode(GL_MODELVIEW);
  742.  
  743. glColor3f( r, g, b );
  744. // glWindow2f(x, y);
  745. glWindowPos2f(x,y);
  746. int len, i;
  747. len = (int)strlen(string);
  748. for (i = 0; i < len; i++) {
  749. glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, string[i]);
  750. }
  751. //glPopMatrix();
  752. }
  753.  
  754.  
  755. void WriteHighScoresToFile()
  756. {
  757.  
  758. //std::ofstream myfile;
  759. //myfile.open ("example.txt");
  760. std::ofstream myfile("example.txt", std::ios::out | std::ios::trunc);
  761. int i=0;
  762. while (i < highscores.size())
  763. {
  764. myfile << highscores[i];
  765. i++;
  766. }
  767. //myfi
  768. /*
  769. for(int i = 0; i < highscores.size(); i++)
  770. {
  771. myfile << highscores[i];
  772. }
  773. //myfile.close();*/
  774. }
  775.  
  776. void ReadHighScoresFromFile()
  777. {
  778.  
  779. std::ifstream ifile("example.txt");
  780. HighScoreEntry tentry;
  781. while(ifile >> tentry) {
  782. highscores.push_back(tentry);
  783. }
  784. /*while(ifile) {
  785. ifile >> tentry;
  786. highscores.push_back(tentry);
  787. }*/
  788. }
  789.  
  790. void ShowInformation()
  791. {
  792. // glOrtho(-1000,1000,-1000,1000,100,20000);
  793. //glMatrixMode(GL_MODELVIEW);
  794. if ( gameover==false)
  795. {
  796. char Result[6]; // string which will contain the number
  797.  
  798. sprintf ( Result, "%d", myPacman->getPoints()); // %d makes the result be a decimal integer
  799.  
  800. char cadena1[30] = "Score : ";
  801.  
  802. strcat(cadena1,Result);
  803.  
  804. output(200,200,255.0,255.0,255.0,cadena1);
  805.  
  806. sprintf ( Result, "%d", myPacman->getLives()); // %d makes the result be a decimal integer
  807.  
  808. char cadena2[30] = "Lives : ";
  809.  
  810. strcat(cadena2,Result);
  811.  
  812. output(50,50,255.0,255.0,255.0,cadena2);
  813. }
  814. else output(50,50,255.0,255.0,255.0,"Game over pringao");
  815. }
  816.  
  817. void ShowHighScoresTable()
  818. {
  819.  
  820.  
  821.  
  822. // glOrtho(-1000,1000,-1000,1000,100,20000);
  823. //glMatrixMode(GL_MODELVIEW);
  824. //for(int i = highscores.size(); i < 0 ; i--)
  825.  
  826. for(int i = 0; i < highscores.size(); i++)
  827. {
  828.  
  829.  
  830.  
  831. char Result[6]; // string which will contain the number
  832.  
  833. sprintf ( Result, "%d", i); // %d makes the result be a decimal integer
  834.  
  835. char cadena1[30] = "Rank : ";
  836.  
  837. strcat(cadena1,Result);
  838.  
  839. char cadena2[30] = "Name: ";
  840.  
  841. strcat(cadena1,cadena2);
  842. //strcat(cadena1,cadena2);
  843.  
  844. //strcat(cadena1, highscores[i].getName());
  845.  
  846. //string tmp = "cat";
  847. char cadena3[50];
  848. strcpy(cadena3, (highscores[i].getName()).c_str());
  849. //For safety, you might prefer:
  850. /*
  851. string tmp = "cat";
  852. char tab2[1024];
  853. strncpy(tab2, tmp.c_str(), sizeof(tab2));
  854. tab2[sizeof(tab2) - 1] = 0;
  855. */
  856. strcat(cadena1,cadena3);
  857.  
  858. char cadena4[30] = "Points: ";
  859.  
  860. strcat(cadena1,cadena4);
  861.  
  862. //strcat(cadena1,cadena3);
  863.  
  864. char Result2[6]; // string which will contain the number
  865.  
  866. sprintf ( Result2, "%d", highscores[i].getScore()); // %d makes the result be a decimal integer
  867.  
  868. strcat(cadena1,Result2);
  869.  
  870. //x,y en funcion de i para poner mas arriba o abajo...
  871. output(50,50,255.0,255.0,255.0,cadena1);
  872.  
  873. // gameover=true;
  874.  
  875. cout << "Posicion Tabla " << i << cadena1;
  876.  
  877. }
  878. }
  879.  
  880. void initArduinousb(){
  881.  
  882. cout <<"Init Arduino"<<endl;
  883. struct termios toptions;
  884.  
  885. // open serial port
  886. fileDesc = open("/dev/cu.usbmodem1421", O_RDWR | O_NOCTTY);
  887.  
  888. printf("fd opened as %i\n", fileDesc);
  889.  
  890. // wait for the Arduino to reboot
  891. usleep(3500000);
  892.  
  893. // get current serial port settings
  894. tcgetattr(fileDesc, &toptions);
  895. // set 9600 baud both ways
  896. cfsetispeed(&toptions, B9600);
  897. cfsetospeed(&toptions, B9600);
  898. // 8 bits, no parity, no stop bits
  899. toptions.c_cflag &= ~PARENB;
  900. toptions.c_cflag &= ~CSTOPB;
  901. toptions.c_cflag &= ~CSIZE;
  902. toptions.c_cflag |= CS8;
  903. //Canonical mode
  904. toptions.c_lflag |= ICANON;
  905. // commit the serial port settings
  906. tcsetattr(fileDesc, TCSANOW, &toptions);
  907.  
  908.  
  909.  
  910. cout << "Calibrating GSR "<<endl;
  911. int calIndex = 0;
  912. while(1){
  913. cout << "calibrating GSR...: "<<calIndex<<endl;
  914. bool readedValue = calibrateGSR();
  915. if(readedValue){
  916. calIndex++;
  917. }
  918. if(calIndex==30){
  919. break;
  920. }
  921. //sleep(1);
  922. }
  923.  
  924. cout << "Calibrating HeartRate "<<endl;
  925. calIndex = 0;
  926. while(1){
  927. cout << "calibrating HeartRate...: "<<calIndex<<endl;
  928. bool readedValue = calibrateHeartRate();
  929. if(readedValue){
  930. calIndex++;
  931. }
  932. if(calIndex==30){
  933. break;
  934. }
  935. //sleep(1);
  936. }
  937.  
  938. gsrAverage = gsrSum/30;
  939. heartRateAverage = heartRateSum/30;
  940.  
  941. cout << "GSR Average: "<<gsrAverage<<endl;
  942. cout << "Pulse Average: "<<heartRateAverage<<endl;
  943. }
  944.  
  945. void readArduino(){
  946.  
  947. // Send byte to trigger Arduino to send string back
  948. write(fileDesc, "0", 1);
  949.  
  950. // Receive string from Arduino
  951. arduinoRcv = read(fileDesc, buf, 64);
  952. // insert terminating zero in the string
  953. buf[arduinoRcv] = 0;
  954.  
  955. //printf("%i bytes read, buffer contains: %s\n", arduinoRcv, buf);
  956.  
  957. //printf("\n");
  958.  
  959. joystick();
  960. temperature();
  961. heartRate();
  962. skinResistance();
  963. bluetooth();
  964.  
  965. }
  966.  
  967. void heartRate(){
  968. if(buf[0]=='H'){
  969. string str(buf);
  970. string heartrate = str.substr(2);
  971. cout << "HeartRate: "<< heartrate<<endl;
  972. try {
  973. double heartDouble = stod(heartrate);
  974.  
  975. if(heartDouble>heartRateAverage+30){
  976. pacmanVelocityFactor = 4;
  977. }else if(heartDouble>heartRateAverage+15){
  978. pacmanVelocityFactor = 3;
  979. }else if(heartDouble>heartRateAverage){
  980. pacmanVelocityFactor = 2;
  981. }else{
  982. pacmanVelocityFactor = 1;
  983. }
  984.  
  985. }
  986. catch (const std::invalid_argument& ia) {
  987. pacmanVelocityFactor = 1;
  988. std::cerr << "Invalid argument: " << ia.what() << '\n';
  989. }
  990. }
  991. }
  992.  
  993. void skinResistance(){
  994.  
  995. if(buf[0]=='G'){
  996. string str(buf);
  997. string gsr = str.substr(2);
  998. cout << "GSR: "<< gsr<<endl;
  999. try {
  1000.  
  1001. double gsrDouble = stod(gsr);
  1002. cout << "GSR: "<< gsrDouble<<endl;
  1003.  
  1004. if(gsrDouble<gsrAverage){
  1005. ghostVelocityFactor = 2;
  1006. }else{
  1007. ghostVelocityFactor = 1;
  1008. }
  1009. }
  1010. catch (const std::invalid_argument& ia) {
  1011. ghostVelocityFactor = 1;
  1012. std::cerr << "Invalid argument: " << ia.what() << '\n';
  1013. }
  1014. }
  1015. }
  1016.  
  1017. void temperature(){
  1018. if(buf[0]=='T'){
  1019. string str(buf);
  1020. string temperature = str.substr(2);
  1021. cout << "Temperature: "<< temperature<<endl;
  1022. try {
  1023. double temperatureDouble = stod(temperature);
  1024. if(temperatureDouble>29.0){
  1025. //Red
  1026. color[0]=0.8; color[1]=0.2; color[2]=0.2; color[3]=1;
  1027. }else if(temperatureDouble<20.0){
  1028. //Blue
  1029. color[0]=0.2; color[1]=0.2; color[2]=0.8; color[3]=1;
  1030. }
  1031. else{
  1032. color[0]=0.2; color[1]=0.2; color[2]=0.2; color[3]=1;
  1033. }
  1034.  
  1035. }
  1036. catch (const std::invalid_argument& ia) {
  1037. ghostVelocityFactor = 1;
  1038. std::cerr << "Invalid argument: " << ia.what() << '\n';
  1039. }
  1040.  
  1041. }
  1042. }
  1043.  
  1044. void joystick(){
  1045. if(buf[0]=='X'){
  1046. cout << "X JOYSTICK: "<< buf[2]<<endl;
  1047. if(buf[2]=='-'){
  1048. direccion=WEST;
  1049. }else if(buf[2]=='0'){
  1050. //Do nothing
  1051. }else{
  1052. direccion=EAST;
  1053. }
  1054. }
  1055.  
  1056. if(buf[0]=='Y'){
  1057. cout << "Y JOYSTICK: "<< buf[2]<<endl;
  1058. if(buf[2]=='-'){
  1059. direccion=SOUTH;
  1060. }else if(buf[2]=='0'){
  1061. //Do nothing
  1062. }else{
  1063. direccion=NORTH;
  1064. }
  1065. }
  1066.  
  1067. if(buf[0]=='S'){
  1068. if(buf[2]=='0'){
  1069. exit (0);
  1070. }
  1071. }
  1072. glutPostRedisplay();
  1073. }
  1074.  
  1075.  
  1076. void bluetooth(){
  1077. if(buf[0]=='i'){
  1078. if ( anglebeta <= (90-4) ) anglebeta=(anglebeta+3);
  1079. }else if(buf[0]=='k'){
  1080. if ( anglebeta >= (-90+4)) anglebeta=anglebeta-3;
  1081. }else if(buf[0]=='j'){
  1082. anglealpha=(anglealpha+3)%360;
  1083. }else if(buf[0]=='l'){
  1084. anglealpha=(anglealpha-3+360)%360;
  1085. }
  1086. glutPostRedisplay();
  1087. }
  1088.  
  1089. bool calibrateHeartRate(){
  1090.  
  1091. // Send byte to trigger Arduino to send string back
  1092. write(fileDesc, "0", 1);
  1093.  
  1094. // Receive string from Arduino
  1095. arduinoRcv = read(fileDesc, buf, 64);
  1096. // insert terminating zero in the string
  1097. buf[arduinoRcv] = 0;
  1098.  
  1099. if(buf[0]=='H'){
  1100. string str(buf);
  1101. string heartrate = str.substr(2);
  1102. try {
  1103. double heartDouble = stod(heartrate);
  1104. heartRateSum+=heartDouble;
  1105. return true;
  1106. }
  1107. catch (const std::invalid_argument& ia) {
  1108. return false;
  1109. }
  1110. }else{
  1111. return false;
  1112. }
  1113. }
  1114.  
  1115. bool calibrateGSR(){
  1116.  
  1117. // Send byte to trigger Arduino to send string back
  1118. write(fileDesc, "0", 1);
  1119.  
  1120. // Receive string from Arduino
  1121. arduinoRcv = read(fileDesc, buf, 64);
  1122. // insert terminating zero in the string
  1123. buf[arduinoRcv] = 0;
  1124.  
  1125. if(buf[0]=='G'){
  1126. string str(buf);
  1127. string gsr = str.substr(2);
  1128. double gsrDouble = stod(gsr);
  1129. gsrSum+=gsrDouble;
  1130. return true;
  1131. }else{
  1132. return false;
  1133. }
  1134. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement