Hoy vamos a tratar el último artículo de esta serie de cuatro artículo sobre Intel Edison y el Kit Xadow Wearable, el cual finalizaremos hablando sobre la creación de un juego por medio de esta placa y kit de desarrollo, eso si, recordando los artículos anteriores por si te perdiste alguno: parte 1, parte 2 y parte 3.
Crear un juego
Quería hacer algo con este kit y tuve una idea para un juego.
En este juego, la banda LED está unida a la parte exterior de la caja de juegos. Como los LEDs parpadean, el jugador inclina la caja en una dirección, dependiendo del color del LED. Si el LED del centro se pone verde, debes inclinar la caja hacia delante (lejos de ti). Si el LED del centro se pone rojo, debes inclinar la caja hacia ti. Si el LED del extremo se pone verde, inclina la caja a la derecha, pero si se pone rojo debes hacerlo a la izquierda.
Este juego está diseñado no sólo para probar los reflejos, sino para hacer que el jugador piense antes de actuar.
Para crear el juego, necesitas los siguientes componentes:
Primero conecté la placa Breakout al lateral del conector de la batería y después los botones de sensor. En el otro lado conecté la pantalla y el giroscopio. Construí la caja pegando láminas de papel grueso de colores. Luego la recorté y la abrí para la pantalla. Coloqué la placa de botones bajo la pantalla; como recordarás, la sensibilidad de los botones es muy alta. En la parte frontal dibujé los símbolos sobre los botones.
Todas las placas están unidas con cinta transparente sobre una capa de papel, para evitar daños.
El borrador comienza automáticamente en Linux.
Para comenzar el juego, mantén el botón PWR en el módulo principal durante unos 9 segundos. Para apagar el juego, pulsa el mismo botón durante 3 segundos.
Cuando el juego está cargado, aparece un menú en el que puedes comenzar un juego (presionar botón A) o mostrar la Ayuda (presionar botón B). Para cerrar la ventana de ayuda, presiona el botón de flecha.
El juego consiste en cinco rondas. En cada ronda se ilumina un LED aleatorio y tienes que inclinar la caja hacia una dirección concreta. Si lo haces correctamente, la pantalla mostrará “¡Has ganado!”. Si fallas o el tiempo se agota la pantalla mostrará “¡Has perdido!”.
Puedes ver el vídeo de ejemplo Intel Edison Game.
Todo el código del juego está en un sólo archivo. Intenté hacerlo lo más sencillo posible, para que fuera fácil de analizar.
Código de borrador de juego
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 |
#include <Wire.h> #include <Seeed_ws2812.h> #include <SeeedOLED.h> #include <Seeed_QTouch.h> #include <ADXL345.h> // game state const int stateMenu = 1; const int stateCount = 3; const int stateHelp = 4; // buttons const int keyBack = 0; const int keyA = 1; const int keyB = 2; // LED strip const int ledSigPin = 12; const int numLed = 5; // answers const int answerLeft = 1; const int answerRight = 2; const int answerUp = 3; const int answerDown = 4; const int colorGreen = 1; const int colorRed = 2; const int numLevels = 6; const int answerID = 5; const int angleScale = 100; const int angleReact = 100;//tangent of actuating angle * angleScale int numWins;// number of wins int numLosts;// number of losses int gameState;// game state const int numSets = 5;// number of rounds in a game // level coding int levels[numLevels][numLed+1] = { {colorGreen,0,0,0,0,answerLeft}, {colorRed,0,0,0,0,answerRight}, {0,0,0,0,colorGreen,answerRight}, {0,0,0,0,colorRed,answerLeft}, {0,0,colorGreen,0,0,answerUp}, {0,0,colorRed,0,0,answerRight}}; // correct answer int rightAnswer; WS2812 strip = WS2812(numLed, ledSigPin); ADXL345 adxl; // current game level int gameLevel; // initialization of accelerometer void initAccel() { adxl.powerOn(); //set activity/ inactivity thresholds (0-255)s adxl.setActivityThreshold(75); //62.5mg per increment adxl.setInactivityThreshold(75); //62.5mg per increment adxl.setTimeInactivity(10); // how many seconds of no activity is inactive? //look of activity movement on this axes - 1 == on; 0 == off adxl.setActivityX(1); adxl.setActivityY(1); adxl.setActivityZ(1); //look of inactivity movement on this axes - 1 == on; 0 == off adxl.setInactivityX(1); adxl.setInactivityY(1); adxl.setInactivityZ(1); //look of tap movement on this axes - 1 == on; 0 == off adxl.setTapDetectionOnX(0); adxl.setTapDetectionOnY(0); adxl.setTapDetectionOnZ(1); //set values for what is a tap, and what is a double tap (0-255) adxl.setTapThreshold(50); //62.5mg per increment adxl.setTapDuration(15); //625us per increment adxl.setDoubleTapLatency(80); //1.25ms per increment adxl.setDoubleTapWindow(200); //1.25ms per increment //set values for what is considered freefall (0-255) adxl.setFreeFallThreshold(7); //(5 - 9) recommended - 62.5mg per increment adxl.setFreeFallDuration(45); //(20 - 70) recommended - 5ms per increment //setting all interrupts to take place on int pin 1 //I had issues with int pin 2, was unable to reset it adxl.setInterruptMapping( ADXL345_INT_SINGLE_TAP_BIT, ADXL345_INT1_PIN ); adxl.setInterruptMapping( ADXL345_INT_DOUBLE_TAP_BIT, ADXL345_INT1_PIN ); adxl.setInterruptMapping( ADXL345_INT_FREE_FALL_BIT, ADXL345_INT1_PIN ); adxl.setInterruptMapping( ADXL345_INT_ACTIVITY_BIT, ADXL345_INT1_PIN ); adxl.setInterruptMapping( ADXL345_INT_INACTIVITY_BIT, ADXL345_INT1_PIN ); //register interrupt actions - 1 == on; 0 == off adxl.setInterrupt( ADXL345_INT_SINGLE_TAP_BIT, 1); adxl.setInterrupt( ADXL345_INT_DOUBLE_TAP_BIT, 1); adxl.setInterrupt( ADXL345_INT_FREE_FALL_BIT, 1); adxl.setInterrupt( ADXL345_INT_ACTIVITY_BIT, 1); adxl.setInterrupt( ADXL345_INT_INACTIVITY_BIT, 1); } void initGame() { SeeedOled.clearDisplay(); SeeedOled.setNormalDisplay(); SeeedOled.setPageMode(); switchToMenu(); } void setup() { strip.begin(); SeeedOled.init(); initAccel(); initGame(); } void cleanLED() { for( int led = 0; led < numLed; led++ ) strip.WS2812SetRGB(led,0,0,0); } void updateLED() { strip.WS2812Send(); } void drawMenu() { SeeedOled.clearDisplay(); SeeedOled.setTextXY(0,2); SeeedOled.putString("Edison Game"); SeeedOled.setTextXY(2,1); SeeedOled.putString("A - Start"); SeeedOled.setTextXY(4,1); SeeedOled.putString("B - Help"); } void drawHelp() { SeeedOled.clearDisplay(); char *messages[] = { "Center green -", "tilt forward." , "Center red -" , "tilt backward.", "Green edge -" , "tilt same side." , "Red edge - tilt", "other side." }; for( int k = 0; k < 8; k++ ) { SeeedOled.setTextXY(k,0); SeeedOled.putString(messages[k]); } } void makeNewLevel() { gameLevel = rand() % numLevels; rightAnswer = levels[gameLevel][answerID]; } void showGameStart() { SeeedOled.clearDisplay(); SeeedOled.setTextXY(0,0); SeeedOled.putString("Press Start"); } int getKeys() { int tn = QTouch.touchNum(); return tn; } int haveTime = 20; void showGameLevel() { for( int k = 0; k < numLed; k++ ) { int color = levels[gameLevel][k]; switch(color) { case colorRed : strip.WS2812SetRGB(k,255,0,0); break; case colorGreen: strip.WS2812SetRGB(k,0,255,0); break; default : strip.WS2812SetRGB(k,0,0,0); } } updateLED(); } void switchToSets() { numWins = 0; numLosts = 0; switchToPlay(); } //------------------------------------ void switchToPlay() { cleanLED(); updateLED(); SeeedOled.clearDisplay(); SeeedOled.setTextXY(3,3); SeeedOled.putString("Get ready!"); int waitTime = 2000 + (rand()%4)*500; delay(waitTime); makeNewLevel(); SeeedOled.setTextXY(3,3); SeeedOled.putString(" "); haveTime = 100; gameState = stateCount; } void doPlay() { if( haveTime >= 0 ) { SeeedOled.setTextXY(3,1); char str[100]; sprintf(str,"-- TILT NOW --"); SeeedOled.putString(str); SeeedOled.setTextXY(5,6); sprintf(str,"%d ",haveTime); SeeedOled.putString(str); showGameLevel(); int answerID = getAnswerID(); haveTime--; if( answerID !=0 || haveTime < 0) { char *message; if( answerID != rightAnswer || haveTime < 0) { numLosts++; message = "You lose!"; } else { numWins++; message = "You win!"; } cleanLED(); updateLED(); SeeedOled.clearDisplay(); SeeedOled.setTextXY(3,4); SeeedOled.putString(message); delay(1000); if( numWins + numLosts == numSets ) { switchToMenu(); } else { switchToPlay(); } } } } //----------------------- void switchToHelp() { drawHelp(); gameState = stateHelp; cleanLED(); updateLED(); } void doHelp() { cleanLED(); updateLED(); int key = getKeys(); if( key == keyBack ) switchToMenu(); } //----------------------- void switchToMenu() { drawMenu(); gameState = stateMenu; cleanLED(); updateLED(); } void doMenu() { int key = getKeys(); if( key == keyA ) switchToSets(); if( key == keyB ) switchToHelp(); } //----------------------- void correct(int &a) { if( a > 32767 ) a = -(65536 - a); } int getAnswerID() { int x,y,z; adxl.readXYZ(&x, &y, &z); correct(x); correct(y); correct(z); int v1 = angleReact; if( z != 0 ) v1 = y*angleScale/z; if( v1 > angleReact ) return answerRight; if( v1 < -angleReact ) return answerLeft; int v2 = angleReact; if( z != 0 ) v2 = x*angleScale/z; if( v2 > angleReact ) return answerUp; if( v2 < -angleReact ) return answerDown; return 0; } void gameStep() { switch(gameState) { case stateCount: doPlay();break; case stateMenu: doMenu();break; case stateHelp: doHelp();break; } } void loop() { gameStep(); delay(10); } |
Sobre el autor
Valery Mosyagin es un investigador oficial de Intel Software. Vive en Rusia, Nizhny Novgorod. Tiene un Máster en Ciencias matemáticas y de computadoras. Trabajó en Intel durante 6 años en el equipo OpenCV y más tarde se mudó a Japón, donde trabajó para el Instituto de Investigación del Cerebro, desarrollando software para experimentos biológicos, más tarde software para análisis de tráfico de redes y software de cobertura y propagación de radio. Desde hace tiempo da cursos de programación a niños. Tiene una amplia área de intereses: realidad virtual, desarrollo de juegos, microcontroladores, IoT.
Para más información sobre IoT Gateways y para ser notificado cuando el Kit Comercial de Desarrollador Intel IoT este disponible visitaremos el Centro de Diseño incorporado.
Para aprender más acerca de nuestro programa para desarrolladores IoT ver la Zona de desarrollador Intel IoT.
Fuente:
Intel Centro de Diseño incorporado, Zona de desarrollador Intel IoT, Xadow y Arduino.