examples: Cleanup and translate more examples to English

This commit is contained in:
Antonio Niño Díaz 2023-05-19 00:32:37 +01:00
parent 2b4aab4ba8
commit fa21c62ac4
13 changed files with 780 additions and 955 deletions

View File

@ -1,202 +1,156 @@
// SPDX-License-Identifier: CC0-1.0 // SPDX-License-Identifier: CC0-1.0
// //
// SPDX-FileContributor: NightFox & Co., 2009-2011 // SPDX-FileContributor: NightFox & Co., 2009-2011
//
// Example of per-pixel collisions.
// http://www.nightfoxandco.com
/*
-------------------------------------------------
NightFox's Lib Template
Ejemplo de mapas de colisiones por pixels
en superficies inclinadas
Requiere DevkitARM
Requiere NightFox's Lib
Codigo por NightFox
http://www.nightfoxandco.com
Inicio 10 de Octubre del 2009
-------------------------------------------------
*/
/*
-------------------------------------------------
Includes
-------------------------------------------------
*/
// Includes C
#include <stdio.h> #include <stdio.h>
// Includes propietarios NDS
#include <nds.h> #include <nds.h>
#include <filesystem.h> #include <filesystem.h>
// Includes librerias propias
#include <nf_lib.h> #include <nf_lib.h>
int main(int argc, char **argv)
{
// Prepare a NitroFS initialization screen
NF_Set2D(0, 0);
NF_Set2D(1, 0);
consoleDemoInit();
printf("\n NitroFS init. Please wait.\n\n");
printf(" Iniciando NitroFS,\n por favor, espere.\n\n");
swiWaitForVBlank();
// Initialize NitroFS and set it as the root folder of the filesystem
nitroFSInit(NULL);
NF_SetRootFolder("NITROFS");
// Initialize 2D engine in the top screen and use mode 0
NF_Set2D(0, 0);
// Initialize tiled backgrounds system
NF_InitTiledBgBuffers(); // Initialize storage buffers
NF_InitTiledBgSys(0); // Top screen
/* // Initialize sprite system
------------------------------------------------- NF_InitSpriteBuffers();
Main() - Bloque general del programa NF_InitSpriteSys(0); // Top screen
-------------------------------------------------
*/
int main(int argc, char **argv) { // Initialize collision map buffers
NF_InitCmapBuffers();
// Pantalla de espera inicializando NitroFS // Load background files from NitroFS
NF_Set2D(0, 0); NF_LoadTiledBg("bg/pdemo_bg", "bg3", 256, 256);
NF_Set2D(1, 0);
consoleDemoInit();
printf("\n NitroFS init. Please wait.\n\n");
printf(" Iniciando NitroFS,\n por favor, espere.\n\n");
swiWaitForVBlank();
// Define el ROOT e inicializa el sistema de archivos // Load sprite files from NitroFS
nitroFSInit(NULL); NF_LoadSpriteGfx("sprite/whiteball", 0, 16, 16);
NF_SetRootFolder("NITROFS"); // Define la carpeta ROOT para usar NITROFS NF_LoadSpritePal("sprite/whiteball", 0);
// Inicializa el motor 2D // Load collision map files from NitroFS
NF_Set2D(0, 0); // Modo 2D_0 en la pantalla superior NF_LoadCollisionBg("maps/pdemo_colmap", 0, 256, 256);
// Inicializa los fondos tileados // Create top screen background
NF_InitTiledBgBuffers(); // Inicializa los buffers para almacenar fondos NF_CreateTiledBg(0, 3, "bg3");
NF_InitTiledBgSys(0); // Inicializa los fondos Tileados para la pantalla superior
// Inicializa los Sprites // Transfer the required sprites to VRAM
NF_InitSpriteBuffers(); // Inicializa los buffers para almacenar sprites y paletas NF_VramSpriteGfx(0, 0, 0, true);
NF_InitSpriteSys(0); // Inicializa los sprites para la pantalla superior NF_VramSpritePal(0, 0, 0);
// Inicializa los buffers de mapas de colisiones // Create sprites and set their priority layer
NF_InitCmapBuffers(); for (int b = 0; b < 3; b ++)
{
NF_CreateSprite(0, b, 0, 0, -16, -16);
NF_SpriteLayer(0, b, 3);
}
// Carga los archivos de fondo // Location of the sprites
NF_LoadTiledBg("bg/pdemo_bg", "bg3", 256, 256); // Carga el fondo para la capa 3, pantalla superior s16 x[3] = { 32, 228, 10 };
s16 y[3] = { -16, 32, 100 };
// Carga los archivos de sprites // Coordinates of the sprite that have to be used as collision points
NF_LoadSpriteGfx("sprite/whiteball", 0, 16, 16); // Pelota s16 py[16] = {
NF_LoadSpritePal("sprite/whiteball", 0); 11, 13, 14, 15, 15, 16, 16, 16, 16, 16, 16, 15, 15, 14, 13, 11
};
// Carga el fondo de colisiones while (1)
NF_LoadCollisionBg("maps/pdemo_colmap", 0, 256, 256); {
// Clear text console
consoleClear();
// Crea los fondos de la pantalla superior bool down = false;
NF_CreateTiledBg(0, 3, "bg3"); bool left = false;
bool right = false;
// Transfiere a la VRAM los sprites necesarios // Handle collisions and fall of all balls
NF_VramSpriteGfx(0, 0, 0, true); // Puntero for (int b = 0; b < 3; b ++)
NF_VramSpritePal(0, 0, 0); {
down = true; // If this remains true, there is no collision
// Variables de uso genereal // Check all pixels of the lower half of the ball to see if there is
u8 b = 0; // a collision.
u8 n = 0; for (int n = 0; n < 16; n ++)
{
// Blue pixels are index 4
if (NF_GetPoint(0, (x[b] + n), (y[b] + py[n])) == 4)
down = false;
}
// Crea el Sprite del puntero en la pantalla inferior // Check for collisions left and right of the ball
for (b = 0; b < 3; b ++) { right = true;
NF_CreateSprite(0, b, 0, 0, -16, -16); // Crea el puntero en la pantalla inferior left = true;
NF_SpriteLayer(0, b, 3); // Y la capa sobre la que se dibujara
}
// Variables para el control de movimiento // Falling to the left
s16 x[3]; if (NF_GetPoint(0, (x[b] - 1), (y[b] + 16)) == 4)
s16 y[3]; left = false;
x[0] = 32;
y[0] = -16;
x[1] = 228;
y[1] = 32;
x[2] = 10;
y[2] = 100;
// Falling to the right
if (NF_GetPoint(0, (x[b] + 16), (y[b] + 16)) == 4)
right = false;
// Variables de control de colisiones, define todos los puntos de colision del sprite // On free fall, don't move on the X axis
s16 py[16]; if (left && right)
py[0] = 11; {
py[1] = 13; right = false;
py[2] = 14; left = false;
py[3] = 15; }
py[4] = 15;
py[5] = 16;
py[6] = 16;
py[7] = 16;
py[8] = 16;
py[9] = 16;
py[10] = 16;
py[11] = 15;
py[12] = 15;
py[13] = 14;
py[14] = 13;
py[15] = 11;
// Control de movimiento // Free fall
bool down = false; if (down)
bool left = false; y[b] ++;
bool right = false;
// Bucle (repite para siempre) // Move right
while(1) { if (right)
x[b] ++;
// Borra la pantalal de texto // Move left
consoleClear(); if (left)
x[b] --;
// Bola a bola // If the ball exits the screen from the bottom move it to the top
for (b = 0; b < 3; b ++) { if (y[b] > 192)
{
x[b] = 32;
y[b] = -16;
}
// Control de colisiones, caida // Set the sprite position
down = true; // Flag de descenso arriba NF_MoveSprite(0, b, x[b], y[b]);
// Busca pixel por pixel, si hay colisiones (pixel azul, nº4)
for (n = 0; n < 16; n ++) {
if (NF_GetPoint(0, (x[b] + n), (y[b] + py[n])) == 4) down = false;
}
// Control de colisiones, decide derecha o izquierda // Print sprite coordinates
right = true; // Flag de movimiento lateral arriba printf("x:%03d y:%03d\n", x[b], y[b]);
left = true;
// Caida a izquierda
if (NF_GetPoint(0, (x[b] - 1), (y[b] + 16)) == 4) left = false;
// Caida a derecha
if (NF_GetPoint(0, (x[b] + 16), (y[b] + 16)) == 4) right = false;
// Si hay caida libre, no te muevas en horizontal
if (left && right) {
right = false;
left = false;
}
// Si es necesario, caida libre }
if (down) y[b] ++;
// Muevete a la derecha
if (right) x[b] ++;
// Muevete a la izquierda
if (left) x[b] --;
// Recoloca la pelota si sale de los limites de pantalla // Update OAM array
if (y[b] > 192) { NF_SpriteOamSet(0);
x[b] = 32;
y[b] = -16;
}
// Posicion del Sprite // Wait for the screen refresh
NF_MoveSprite(0, b, x[b], y[b]); swiWaitForVBlank();
// Imprime la posicion de la pelota // Update OAM
printf("x:%03d y:%03d\n", x[b], y[b]); oamUpdate(&oamMain);
}
}
NF_SpriteOamSet(0); // Actualiza el Array del OAM
swiWaitForVBlank(); // Espera al sincronismo vertical
oamUpdate(&oamMain); // Actualiza a VRAM el OAM Secundario
}
return 0;
return 0;
} }

View File

@ -1,178 +1,154 @@
// SPDX-License-Identifier: CC0-1.0 // SPDX-License-Identifier: CC0-1.0
// //
// SPDX-FileContributor: NightFox & Co., 2009-2011 // SPDX-FileContributor: NightFox & Co., 2009-2011
//
// Collision background example
// http://www.nightfoxandco.com
/*
-------------------------------------------------
NightFox's Lib Template
Ejemplo de fondos de colisiones
Requiere DevkitARM
Requiere NightFox's Lib
Codigo por NightFox
http://www.nightfoxandco.com
Inicio 10 de Octubre del 2009
-------------------------------------------------
*/
/*
-------------------------------------------------
Includes
-------------------------------------------------
*/
// Includes C
#include <stdio.h> #include <stdio.h>
// Includes propietarios NDS
#include <nds.h> #include <nds.h>
#include <filesystem.h> #include <filesystem.h>
// Includes librerias propias
#include <nf_lib.h> #include <nf_lib.h>
int main(int argc, char **argv)
{
// Prepare a NitroFS initialization screen
NF_Set2D(0, 0);
NF_Set2D(1, 0);
consoleDemoInit();
printf("\n NitroFS init. Please wait.\n\n");
printf(" Iniciando NitroFS,\n por favor, espere.\n\n");
swiWaitForVBlank();
// Initialize NitroFS and set it as the root folder of the filesystem
nitroFSInit(NULL);
NF_SetRootFolder("NITROFS");
// Initialize 2D engine in the top screen and use mode 0
NF_Set2D(0, 0);
// Initialize tiled backgrounds system
NF_InitTiledBgBuffers(); // Initialize storage buffers
NF_InitTiledBgSys(0); // Top screen
/* // Initialize sprite system
------------------------------------------------- NF_InitSpriteBuffers();
Main() - Bloque general del programa NF_InitSpriteSys(0); // Top screen
-------------------------------------------------
*/
int main(int argc, char **argv) { // Initialize collision map buffers
NF_InitCmapBuffers();
// Pantalla de espera inicializando NitroFS // Load background files from NitroFS
NF_Set2D(0, 0); NF_LoadTiledBg("bg/ppc_bg", "bg3", 512, 512);
NF_Set2D(1, 0);
consoleDemoInit();
printf("\n NitroFS init. Please wait.\n\n");
printf(" Iniciando NitroFS,\n por favor, espere.\n\n");
swiWaitForVBlank();
// Define el ROOT e inicializa el sistema de archivos // Load sprite files from NitroFS
nitroFSInit(NULL); NF_LoadSpriteGfx("sprite/puntero", 0, 8, 8);
NF_SetRootFolder("NITROFS"); // Define la carpeta ROOT para usar NITROFS NF_LoadSpritePal("sprite/puntero", 0);
// Inicializa el motor 2D // Load collision map files from NitroFS
NF_Set2D(0, 0); // Modo 2D_0 en la pantalla superior NF_LoadCollisionBg("maps/ppc_cmap", 0, 512, 512);
// Inicializa los fondos tileados // Create top screen background
NF_InitTiledBgBuffers(); // Inicializa los buffers para almacenar fondos NF_CreateTiledBg(0, 3, "bg3");
NF_InitTiledBgSys(0); // Inicializa los fondos Tileados para la pantalla superior
// Inicializa los Sprites // Transfer the required sprites to VRAM
NF_InitSpriteBuffers(); // Inicializa los buffers para almacenar sprites y paletas NF_VramSpriteGfx(0, 0, 0, true);
NF_InitSpriteSys(0); // Inicializa los sprites para la pantalla superior NF_VramSpritePal(0, 0, 0);
// Inicializa los buffers de mapas de colisiones // Create pointer sprite in the bottom screen and set its priority layer
NF_InitCmapBuffers(); NF_CreateSprite(0, 0, 0, 0, 124, 92);
NF_SpriteLayer(0, 0, 3);
// Carga los archivos de fondo // Movement variables
NF_LoadTiledBg("bg/ppc_bg", "bg3", 512, 512); // Carga el fondo para la capa 3, pantalla superior s16 x = 128;
s16 y = 96;
s16 spr_x = 0;
s16 spr_y = 0;
s16 bg_x = 0;
s16 bg_y = 0;
// Carga los archivos de sprites while (1)
NF_LoadSpriteGfx("sprite/puntero", 0, 8, 8); // Puntero {
NF_LoadSpritePal("sprite/puntero", 0); scanKeys(); // Read keypad
u16 keys = keysHeld(); // Keys currently pressed
// Carga el fondo de colisiones if (keys & KEY_UP)
NF_LoadCollisionBg("maps/ppc_cmap", 0, 512, 512); y --;
if (keys & KEY_DOWN)
y ++;
if (keys & KEY_LEFT)
x --;
if (keys & KEY_RIGHT)
x ++;
// Crea los fondos de la pantalla superior // Movement limits
NF_CreateTiledBg(0, 3, "bg3"); if (x < 0)
x = 0;
if (x > 511)
x = 511;
// Transfiere a la VRAM los sprites necesarios if (y < 0)
NF_VramSpriteGfx(0, 0, 0, true); // Puntero y = 0;
NF_VramSpritePal(0, 0, 0); if (y > 511)
y = 511;
// Crea el Sprite del puntero en la pantalla inferior // Background position
NF_CreateSprite(0, 0, 0, 0, 124, 92); // Crea el puntero en la pantalla inferior bg_x = x - 128;
NF_SpriteLayer(0, 0, 3); // Y la capa sobre la que se dibujara if (bg_x < 0)
bg_x = 0;
if (bg_x > 256)
bg_x = 256;
// Variable para la lectura del keypad bg_y = y - 96;
u16 keys = 0; if (bg_y < 0)
bg_y = 0;
if (bg_y > 320)
bg_y = 320;
// Variables para el control de movimiento // Sprite position
s16 x = 128; spr_x = (x - bg_x) - 4;
s16 y = 96; spr_y = (y - bg_y) - 4;
s16 spr_x = 0; NF_MoveSprite(0, 0, spr_x, spr_y);
s16 spr_y = 0;
s16 bg_x = 0;
s16 bg_y = 0;
u8 pixel = 0;
// Bucle (repite para siempre) // Print pointer position
while(1) { consoleClear();
printf("x:%03d y:%03d \n\n", x, y);
// Lee el teclado // Print pixel color
scanKeys(); u8 pixel = NF_GetPoint(0, x, y);
keys = keysHeld(); switch (pixel)
if (keys & KEY_UP) y --; {
if (keys & KEY_DOWN) y ++; case 1:
if (keys & KEY_LEFT) x --; printf("Tile: Negro / Black");
if (keys & KEY_RIGHT) x ++; break;
case 2:
printf("Tile: Rojo / Red");
break;
case 3:
printf("Tile: Verde / Green");
break;
case 4:
printf("Tile: Azul / Blue");
break;
default:
printf("Value: %03d", pixel);
break;
}
// Limites del movimiento // Update OAM array
if (x < 0) x = 0; NF_SpriteOamSet(0);
if (x > 511) x = 511;
if (y < 0) y = 0;
if (y > 511) y = 511;
// Posicion del fondo // Wait for the screen refresh
bg_x = (x - 128); swiWaitForVBlank();
if (bg_x < 0) bg_x = 0;
if (bg_x > 256) bg_x = 256;
bg_y = (y - 96);
if (bg_y < 0) bg_y = 0;
if (bg_y > 320) bg_y = 320;
// Posicion del Sprite // Update OAM
spr_x = (x - bg_x) - 4; oamUpdate(&oamMain);
spr_y = (y - bg_y) - 4;
NF_MoveSprite(0, 0, spr_x, spr_y);
// Imprime la posicion del cursor // Update scroll
consoleClear(); NF_ScrollBg(0, 3, bg_x, bg_y);
printf("x:%03d y:%03d \n\n", x, y); }
// Imprime el color del pixel
pixel = NF_GetPoint(0, x, y);
switch (pixel) {
case 1:
printf("Tile: Negro / Black");
break;
case 2:
printf("Tile: Rojo / Red");
break;
case 3:
printf("Tile: Verde / Green");
break;
case 4:
printf("Tile: Azul / Blue");
break;
default:
printf("Value: %03d", pixel);
break;
}
NF_SpriteOamSet(0); // Actualiza el Array del OAM
swiWaitForVBlank(); // Espera al sincronismo vertical
oamUpdate(&oamMain); // Actualiza a VRAM el OAM Secundario
NF_ScrollBg(0, 3, bg_x, bg_y); // Actualiza el scroll
}
return 0;
return 0;
} }

View File

@ -1,196 +1,174 @@
// SPDX-License-Identifier: CC0-1.0 // SPDX-License-Identifier: CC0-1.0
// //
// SPDX-FileContributor: NightFox & Co., 2009-2011 // SPDX-FileContributor: NightFox & Co., 2009-2011
//
// Collision map example.
// http://www.nightfoxandco.com
/*
-------------------------------------------------
NightFox's Lib Template
Ejemplo de mapas de colisiones
Requiere DevkitARM
Requiere NightFox's Lib
Codigo por NightFox
http://www.nightfoxandco.com
Inicio 10 de Octubre del 2009
-------------------------------------------------
*/
/*
-------------------------------------------------
Includes
-------------------------------------------------
*/
// Includes C
#include <stdio.h> #include <stdio.h>
// Includes propietarios NDS
#include <nds.h> #include <nds.h>
#include <filesystem.h> #include <filesystem.h>
// Includes librerias propias
#include <nf_lib.h> #include <nf_lib.h>
int main(int argc, char **argv)
{
// Prepare a NitroFS initialization screen
NF_Set2D(0, 0);
NF_Set2D(1, 0);
consoleDemoInit();
printf("\n NitroFS init. Please wait.\n\n");
printf(" Iniciando NitroFS,\n por favor, espere.\n\n");
swiWaitForVBlank();
// Initialize NitroFS and set it as the root folder of the filesystem
nitroFSInit(NULL);
NF_SetRootFolder("NITROFS");
// Initialize 2D engine in both screens and use mode 0
NF_Set2D(0, 0);
NF_Set2D(1, 0);
// Initialize tiled backgrounds system
NF_InitTiledBgBuffers(); // Initialize storage buffers
NF_InitTiledBgSys(0); // Top screen
NF_InitTiledBgSys(1); // Bottom screen
/* // Initialize sprite system
------------------------------------------------- NF_InitSpriteBuffers();
Main() - Bloque general del programa NF_InitSpriteSys(0); // Top screen
------------------------------------------------- NF_InitSpriteSys(1); // Bottom screen
*/
int main(int argc, char **argv) { // Initialize text system
NF_InitTextSys(0); // Top screen
// Pantalla de espera inicializando NitroFS // Initialize collision map buffers
NF_Set2D(0, 0); NF_InitCmapBuffers();
NF_Set2D(1, 0);
consoleDemoInit();
printf("\n NitroFS init. Please wait.\n\n");
printf(" Iniciando NitroFS,\n por favor, espere.\n\n");
swiWaitForVBlank();
// Define el ROOT e inicializa el sistema de archivos // Load background files from NitroFS
nitroFSInit(NULL); NF_LoadTiledBg("bg/layer3", "moon", 256, 256);
NF_SetRootFolder("NITROFS"); // Define la carpeta ROOT para usar NITROFS NF_LoadTiledBg("bg/colmap", "boxes", 768, 512);
// Inicializa el motor 2D // Load sprite files from NitroFS
NF_Set2D(0, 0); // Modo 2D_0 en ambas pantallas NF_LoadSpriteGfx("sprite/puntero", 0, 8, 8);
NF_Set2D(1, 0); NF_LoadSpritePal("sprite/puntero", 0);
// Inicializa los fondos tileados // Load text font files from NitroFS
NF_InitTiledBgBuffers(); // Inicializa los buffers para almacenar fondos NF_LoadTextFont("fnt/default", "normal", 256, 256, 0);
NF_InitTiledBgSys(0); // Inicializa los fondos Tileados para la pantalla superior
NF_InitTiledBgSys(1); // Iniciliaza los fondos Tileados para la pantalla inferior
// Inicializa los Sprites // Load collision map files from NitroFS
NF_InitSpriteBuffers(); // Inicializa los buffers para almacenar sprites y paletas NF_LoadCollisionMap("maps/cmap", 0, 768, 512);
NF_InitSpriteSys(0); // Inicializa los sprites para la pantalla superior
NF_InitSpriteSys(1); // Inicializa los sprites para la pantalla inferior
// Inicializa el motor de texto // Create top screen background
NF_InitTextSys(0); // Inicializa el texto para la pantalla superior NF_CreateTiledBg(0, 3, "moon");
// Inicializa los buffers de mapas de colisiones // Create bottom screen backgrounds
NF_InitCmapBuffers(); NF_CreateTiledBg(1, 3, "moon");
NF_CreateTiledBg(1, 2, "boxes");
// Carga los archivos de fondo desde la FAT / NitroFS a la RAM // Create a text layer
NF_LoadTiledBg("bg/layer3", "moon", 256, 256); // Carga el fondo para la capa 3, pantalla inferior NF_CreateTextLayer(0, 2, 0, "normal");
NF_LoadTiledBg("bg/colmap", "boxes", 768, 512); // Carga el fondo para la capa 2, pantalla inferior
// Carga los archivos de sprites desde la FAT / NitroFS a la RAM // Transfer the required sprites to VRAM
NF_LoadSpriteGfx("sprite/puntero", 0, 8, 8); // Puntero NF_VramSpriteGfx(1, 0, 0, true);
NF_LoadSpritePal("sprite/puntero", 0); NF_VramSpritePal(1, 0, 0);
// Carga la fuente por defecto para el texto // Create pointer sprite in the bottom screen and set its priority layer
NF_LoadTextFont("fnt/default", "normal", 256, 256, 0); NF_CreateSprite(1, 0, 0, 0, 124, 92);
NF_SpriteLayer(1, 0, 2);
// Carga el mapa de colisiones // Movement variables
NF_LoadCollisionMap("maps/cmap", 0, 768, 512); s16 x = 128;
s16 y = 96;
s16 spr_x = 0;
s16 spr_y = 0;
s16 bg_x = 0;
s16 bg_y = 0;
// Crea los fondos de la pantalla superior // Buffer de texto
NF_CreateTiledBg(0, 3, "moon"); char mytext[32];
// Crea los fondos de la pantalla inferior
NF_CreateTiledBg(1, 3, "moon");
NF_CreateTiledBg(1, 2, "boxes");
// Crea una capa de texto while (1)
NF_CreateTextLayer(0, 2, 0, "normal"); {
scanKeys(); // Read keypad
u16 keys = keysHeld(); // Keys currently pressed
// Transfiere a la VRAM los sprites necesarios if (keys & KEY_UP)
NF_VramSpriteGfx(1, 0, 0, true); // Puntero y --;
NF_VramSpritePal(1, 0, 0); if (keys & KEY_DOWN)
y ++;
if (keys & KEY_LEFT)
x --;
if (keys & KEY_RIGHT)
x ++;
// Crea el Sprite del puntero en la pantalla inferior // Limites del movimiento
NF_CreateSprite(1, 0, 0, 0, 124, 92); // Crea el puntero en la pantalla inferior if (x < 0)
NF_SpriteLayer(1, 0, 2); // Y la capa sobre la que se dibujara x = 0;
if (x > 767)
x = 767;
// Variable para la lectura del keypad if (y < 0)
u16 keys = 0; y = 0;
if (y > 511)
y = 511;
// Variables para el control de movimiento // Background position
s16 x = 128; bg_x = x - 128;
s16 y = 96; if (bg_x < 0)
s16 spr_x = 0; bg_x = 0;
s16 spr_y = 0; if (bg_x > 512)
s16 bg_x = 0; bg_x = 512;
s16 bg_y = 0;
// Buffer de texto bg_y = y - 96;
char mytext[32]; if (bg_y < 0)
bg_y = 0;
if (bg_y > 320)
bg_y = 320;
// Sprite position
spr_x = (x - bg_x) - 4;
spr_y = (y - bg_y) - 4;
NF_MoveSprite(1, 0, spr_x, spr_y);
// Print pointer position
sprintf(mytext,"x:%d y:%d ", x, y);
NF_WriteText(0, 2, 1, 1, mytext);
// Bucle (repite para siempre) // Print tile number
while(1) { switch (NF_GetTile(0, x, y))
{
case 0:
sprintf(mytext,"Tile: Vacio / Void ");
break;
case 1:
sprintf(mytext,"Tile: Rojo / Red ");
break;
case 2:
sprintf(mytext,"Tile: Verde / Green ");
break;
case 3:
sprintf(mytext,"Tile: Azul / Blue ");
break;
}
NF_WriteText(0, 2, 1, 3, mytext);
// Lee el teclado // Update text layers
scanKeys(); NF_UpdateTextLayers();
keys = keysHeld();
if (keys & KEY_UP) y --;
if (keys & KEY_DOWN) y ++;
if (keys & KEY_LEFT) x --;
if (keys & KEY_RIGHT) x ++;
// Limites del movimiento // Update OAM array
if (x < 0) x = 0; NF_SpriteOamSet(1);
if (x > 767) x = 767;
if (y < 0) y = 0;
if (y > 511) y = 511;
// Posicion del fondo // Wait for the screen refresh
bg_x = (x - 128); swiWaitForVBlank();
if (bg_x < 0) bg_x = 0;
if (bg_x > 512) bg_x = 512;
bg_y = (y - 96);
if (bg_y < 0) bg_y = 0;
if (bg_y > 320) bg_y = 320;
// Posicion del Sprite // Update OAM
spr_x = (x - bg_x) - 4; oamUpdate(&oamSub);
spr_y = (y - bg_y) - 4;
NF_MoveSprite(1, 0, spr_x, spr_y);
// Imprime la posicion del cursor // Update background scroll
sprintf(mytext,"x:%d y:%d ", x, y); NF_ScrollBg(1, 2, bg_x, bg_y);
NF_WriteText(0, 2, 1, 1, mytext); }
// Imprime el nº de tile
switch (NF_GetTile(0, x, y)) {
case 0:
sprintf(mytext,"Tile: Vacio / Void ");
break;
case 1:
sprintf(mytext,"Tile: Rojo / Red ");
break;
case 2:
sprintf(mytext,"Tile: Verde / Green ");
break;
case 3:
sprintf(mytext,"Tile: Azul / Blue ");
break;
}
NF_WriteText(0, 2, 1, 3, mytext);
NF_UpdateTextLayers(); // Actualiza las capas de texto
NF_SpriteOamSet(1); // Actualiza el Array del OAM
swiWaitForVBlank(); // Espera al sincronismo vertical
oamUpdate(&oamSub); // Actualiza a VRAM el OAM Secundario
NF_ScrollBg(1, 2, bg_x, bg_y); // Actualiza el scroll
}
return 0;
return 0;
} }

View File

@ -1,200 +1,163 @@
// SPDX-License-Identifier: CC0-1.0 // SPDX-License-Identifier: CC0-1.0
// //
// SPDX-FileContributor: NightFox & Co., 2009-2011 // SPDX-FileContributor: NightFox & Co., 2009-2011
//
// "Reveal" effect
// http://www.nightfoxandco.com
/*
-------------------------------------------------
NightFox's Lib Template
Efecto de "revelado"
Requiere DevkitARM
Requiere NightFox's Lib
Codigo por NightFox
http://www.nightfoxandco.com
Inicio 10 de Octubre del 2009
-------------------------------------------------
*/
/*
-------------------------------------------------
Includes
-------------------------------------------------
*/
// Includes C
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <unistd.h> #include <unistd.h>
#include <time.h> #include <time.h>
// Includes propietarios NDS
#include <nds.h> #include <nds.h>
#include <filesystem.h> #include <filesystem.h>
// Includes librerias propias
#include <nf_lib.h> #include <nf_lib.h>
int main(int argc, char **argv)
{
// Prepare a NitroFS initialization screen
NF_Set2D(0, 0);
NF_Set2D(1, 0);
consoleDemoInit();
printf("\n NitroFS init. Please wait.\n\n");
printf(" Iniciando NitroFS,\n por favor, espere.\n\n");
swiWaitForVBlank();
// Initialize NitroFS and set it as the root folder of the filesystem
nitroFSInit(NULL);
NF_SetRootFolder("NITROFS");
// Initialize 2D engine in both screens. Use mode 0 in the top screen, and
// mode 5 in the bottom screen.
NF_Set2D(0, 0);
NF_Set2D(1, 5);
// Initialize tiled backgrounds system in the top screen
NF_InitTiledBgBuffers(); // Initialize storage buffers
NF_InitTiledBgSys(0);
/* // Initialize bitmap backgrounds system in the bottom screen
------------------------------------------------- NF_Init8bitsBgBuffers(); // Initialize storage buffers
Main() - Bloque general del programa NF_InitBitmapBgSys(1, 0); // Initialize 8-bit bitmap backgrounds
------------------------------------------------- NF_Init8bitsBackBuffer(1); // Initialize backbuffer
*/ NF_Enable8bitsBackBuffer(1); // Enable backbuffer
int main(int argc, char **argv) { // Initialize sprite system in the bottom screen
NF_InitSpriteBuffers(); // Initialize storage buffers
NF_InitSpriteSys(1);
// Pantalla de espera inicializando NitroFS // Load tiled background files from NitroFS
NF_Set2D(0, 0); NF_LoadTiledBg("bg/nfl", "nfl", 256, 256);
NF_Set2D(1, 0);
consoleDemoInit();
printf("\n NitroFS init. Please wait.\n\n");
printf(" Iniciando NitroFS,\n por favor, espere.\n\n");
swiWaitForVBlank();
// Define el ROOT e inicializa el sistema de archivos // Load bitmap background files from NitroFS
nitroFSInit(NULL); NF_Load8bitsBg("bg/img8b_1", 0);
NF_SetRootFolder("NITROFS"); // Define la carpeta ROOT para usar NITROFS NF_Load8bitsBg("bg/img8b_2", 1);
// Inicializa el motor 2D // Load sprite files from NitroFS
NF_Set2D(0, 0); // Modo 2D_0 en la pantalla superior NF_LoadSpriteGfx("spr/bola", 0, 32, 32);
NF_Set2D(1, 5); // Modo 2D_5 en la pantalla superior NF_LoadSpritePal("spr/bola", 0);
// Inicializa los fondos tileados (Pantalla superior) // Create bottom screen background
NF_InitTiledBgBuffers(); // Inicializa los buffers para almacenar fondos NF_CreateTiledBg(0, 3, "nfl");
NF_InitTiledBgSys(0); // Inicializa los fondos Tileados para la pantalla superior
// Inicializa los fondos en modo "BITMAP" (Pantalla inferior) // Transfer image to the backbuffer of the top screen
NF_Init8bitsBgBuffers(); // Inicializa los buffers para almacenar fondos NF_Copy8bitsBuffer(1, 2, 1);
NF_InitBitmapBgSys(1, 0); // Inicializa los fondos bitmap de 8 bits // Transfer image to layer 3 of the top screen
NF_Init8bitsBackBuffer(1); // Inicializa el BackBuffer NF_Copy8bitsBuffer(1, 1, 0);
NF_Enable8bitsBackBuffer(1); // Habilita el BackBuffer en la pantalla inferior // Copy backbuffer of the top screen to layer 2
NF_Flip8bitsBackBuffer(1, 0);
// Inicializa los Sprites // Transfer the required sprites to VRAM
NF_InitSpriteBuffers(); // Inicializa los buffers para almacenar sprites y paletas NF_VramSpriteGfx(1, 0, 0, true);
NF_InitSpriteSys(1); // Inicializa los sprites para la pantalla inferior NF_VramSpritePal(1, 0, 0);
// Carga los archivos de tiles desde la FAT / NitroFS a la RAM // Set random seed based on the current time
NF_LoadTiledBg("bg/nfl", "nfl", 256, 256); srand(time(NULL));
// Carga el archivo BITMAP de imagen en formato RAW a la RAM // State of the balls
NF_Load8bitsBg("bg/img8b_1", 0); s16 bola_x[32];
NF_Load8bitsBg("bg/img8b_2", 1); s16 bola_y[32];
s8 bola_spx[32];
s8 bola_spy[32];
// Carga los archivos de sprites desde la FAT / NitroFS a la RAM for (int n = 0; n < 32; n ++)
NF_LoadSpriteGfx("spr/bola", 0, 32, 32); // Bola azul {
NF_LoadSpritePal("spr/bola", 0); bola_x[n] = rand() % 223;
bola_y[n] = rand() % 159;
bola_spx[n] = (rand() % 3) + 1;
bola_spy[n] = (rand() % 3) + 1;
NF_CreateSprite(1, n, 0, 0, bola_x[n], bola_y[n]);
NF_SpriteLayer(1, n, 3);
}
// Crea los fondos de la pantalla superior while (1)
NF_CreateTiledBg(0, 3, "nfl"); {
// Read keys and touchscreen
scanKeys();
touchPosition touchscreen;
touchRead(&touchscreen);
u16 keys_held = keysHeld();
u16 keys_down = keysDown();
// Tranfiere las imagenes a la pantalla superior, backbuffer // Check if the touch screen is pressed
NF_Copy8bitsBuffer(1, 2, 1); if (keys_held & KEY_TOUCH)
// Tranfiere las imagenes a la pantalla superior, capa 3 {
NF_Copy8bitsBuffer(1, 1, 0); int x = touchscreen.px - 8;
// Copia el BackBuffer de la pantalla superior a la capa 2 if (x < 0)
NF_Flip8bitsBackBuffer(1, 0); x = 0;
if (x > 239)
x = 239;
// Transfiere a la VRAM los sprites necesarios int y = touchscreen.py - 8;
NF_VramSpriteGfx(1, 0, 0, true); // Bola (todos los frames en VRAM) Pantalla superior if (y < 0)
NF_VramSpritePal(1, 0, 0); y = 0;
if (y > 175)
y = 175;
// Variables generales y inicializacion del random // Draw a 16x16 block around the touchscreen coordinates in the
u8 n = 0; // bottom screen.
srand(time(NULL)); for (int dy = 0; dy < 16; dy ++)
{
for (int dx = 0; dx < 16; dx ++)
{
u16 idx = ((y + dy) << 8) + (x + dx);
NF_8BITS_BACKBUFFER[1].data[idx] = 0;
}
}
}
// Crea las bolas en la pantalla superior // Press X to reload the top screen image
s16 bola_x[32]; if (keys_down & KEY_B)
s16 bola_y[32]; NF_Copy8bitsBuffer(1, 2, 1);
s8 bola_spx[32];
s8 bola_spy[32];
for (n = 0; n < 32; n ++) {
bola_x[n] = (rand() % 223);
bola_y[n] = (rand() % 159);
bola_spx[n] = (rand() % 3) + 1;
bola_spy[n] = (rand() % 3) + 1;
NF_CreateSprite(1, n, 0, 0, bola_x[n], bola_y[n]);
NF_SpriteLayer(1, n, 3);
}
// Variables del control del touchpad // Copy bottom screen backbuffer to layer 2
u16 keys = 0; NF_Flip8bitsBackBuffer(1, 0);
touchPosition touchscreen;
s16 x = 0;
s16 y = 0;
// Control del dibujado // Move the sprites
u16 idx = 0; for (int n = 0; n < 32; n ++)
u16 dx = 0; {
u16 dy = 0; bola_x[n] += bola_spx[n];
if ((bola_x[n] < 0) || (bola_x[n] > 223))
bola_spx[n] *= -1;
// Repite para siempre bola_y[n] += bola_spy[n];
while (1) { if ((bola_y[n] < 0) || (bola_y[n] > 159))
bola_spy[n] *= -1;
// Lectura de posicion del stylus NF_MoveSprite(1, n, bola_x[n], bola_y[n]);
scanKeys(); // Lee el touchpad via Libnds }
touchRead(&touchscreen);
keys = keysHeld(); // Verifica el estado del touchscreen
// Si presionas sobre el keypad... // Update OAM array
if (keys & KEY_TOUCH) { NF_SpriteOamSet(1);
// Lee el touchpad // Wait for the screen refresh
x = (touchscreen.px - 8); swiWaitForVBlank();
if (x < 0) x = 0;
if (x > 239) x = 239;
y = ((touchscreen.py - 8));
if (y < 0) y = 0;
if (y > 175) y = 175;
// Borra un bloque de 16x16 // Update OAM
for (dy = 0; dy < 16; dy ++) { oamUpdate(&oamSub);
for (dx = 0; dx < 16; dx ++) { }
idx = ((y + dy) << 8) + (x + dx);
// Pantalla inferior
NF_8BITS_BACKBUFFER[1].data[idx] = 0;
}
}
}
// Lee las teclas pulsadas
keys = keysDown();
// Presiona X restaura imagen superior
if (keys & KEY_B) NF_Copy8bitsBuffer(1, 2, 1);
// Copia el BackBuffer de la pantalla inferior a la capa 2
NF_Flip8bitsBackBuffer(1, 0);
// Mueve las bolas
for (n = 0; n < 32; n ++) {
bola_x[n] += bola_spx[n];
if ((bola_x[n] < 0) || (bola_x[n] > 223)) bola_spx[n] *= -1;
bola_y[n] += bola_spy[n];
if ((bola_y[n] < 0) || (bola_y[n] > 159)) bola_spy[n] *= -1;
NF_MoveSprite(1, n, bola_x[n], bola_y[n]);
}
// Actualiza el array de OAM
NF_SpriteOamSet(1);
swiWaitForVBlank(); // Espera al sincronismo vertical
// Actualiza el OAM
oamUpdate(&oamSub);
}
return 0;
return 0;
} }

View File

@ -137,7 +137,8 @@ int main(int argc, char **argv)
angle -= 2048; angle -= 2048;
} }
swiWaitForVBlank(); // Wait for the screen refresh // Wait for the screen refresh
swiWaitForVBlank();
// Update parameters of the affine backgrounds // Update parameters of the affine backgrounds
for (int n = 0; n < 2; n ++) for (int n = 0; n < 2; n ++)

View File

@ -60,7 +60,7 @@ int main(int argc, char **argv)
while (1) while (1)
{ {
scanKeys(); // Read keypad scanKeys(); // Read keypad
uint16_t keys = keysHeld(); // Keys currently pressed u16 keys = keysHeld(); // Keys currently pressed
// If pressing left // If pressing left
if (keys & KEY_LEFT) if (keys & KEY_LEFT)
@ -82,7 +82,8 @@ int main(int argc, char **argv)
bg_x[1] = (int)(bg_x[0] / 1.5); bg_x[1] = (int)(bg_x[0] / 1.5);
bg_x[2] = (int)(bg_x[1] / 1.5); bg_x[2] = (int)(bg_x[1] / 1.5);
swiWaitForVBlank(); // Wait for the screen refresh // Wait for the screen refresh
swiWaitForVBlank();
// Update background scroll during vertical blanking to avoid tearing // Update background scroll during vertical blanking to avoid tearing
for (int n = 0; n < 4; n ++) for (int n = 0; n < 4; n ++)

View File

@ -78,7 +78,8 @@ int main(int argc, char **argv)
NF_Copy16bitsBuffer(1, 1, 0); // Background NF_Copy16bitsBuffer(1, 1, 0); // Background
NF_Draw16bitsImage(1, 1, x, y, true); // Ball (magenta is transparent) NF_Draw16bitsImage(1, 1, x, y, true); // Ball (magenta is transparent)
swiWaitForVBlank(); // Wait for the screen refresh // Wait for the screen refresh
swiWaitForVBlank();
// Send backbuffers to the screen // Send backbuffers to the screen
NF_Flip16bitsBackBuffer(0); NF_Flip16bitsBackBuffer(0);

View File

@ -36,7 +36,7 @@ int main(int argc, char **argv)
NF_InitTiledBgSys(0); // Top screen NF_InitTiledBgSys(0); // Top screen
NF_InitTiledBgSys(1); // Bottom screen NF_InitTiledBgSys(1); // Bottom screen
// Initialize sprite backgrounds system // Initialize sprite system
NF_InitSpriteBuffers(); // Initialize storage buffers NF_InitSpriteBuffers(); // Initialize storage buffers
NF_InitSpriteSys(0); // Top screen NF_InitSpriteSys(0); // Top screen
NF_InitSpriteSys(1); // Bottom screen NF_InitSpriteSys(1); // Bottom screen
@ -134,7 +134,8 @@ int main(int argc, char **argv)
NF_SpriteOamSet(0); NF_SpriteOamSet(0);
NF_SpriteOamSet(1); NF_SpriteOamSet(1);
swiWaitForVBlank(); // Wait for the screen refresh // Wait for the screen refresh
swiWaitForVBlank();
// Update OAM // Update OAM
oamUpdate(&oamMain); oamUpdate(&oamMain);

View File

@ -93,7 +93,8 @@ int main(int argc, char **argv)
NF_Draw16bitsImage(1, img2, 0, 0, false); NF_Draw16bitsImage(1, img2, 0, 0, false);
} }
swiWaitForVBlank(); // Wait for the screen refresh // Wait for the screen refresh
swiWaitForVBlank();
// Send backbuffers to the screen // Send backbuffers to the screen
NF_Flip16bitsBackBuffer(0); NF_Flip16bitsBackBuffer(0);

View File

@ -155,7 +155,8 @@ int main(int argc, char **argv)
} }
} }
swiWaitForVBlank(); // Wait for the screen refresh // Wait for the screen refresh
swiWaitForVBlank();
// Send backbuffer to the screen // Send backbuffer to the screen
NF_Flip16bitsBackBuffer(0); NF_Flip16bitsBackBuffer(0);

View File

@ -92,7 +92,8 @@ int main(int argc, char **argv)
if (newpress & KEY_L) if (newpress & KEY_L)
NF_PlayRawSound(0, 127, 0, false, 0); NF_PlayRawSound(0, 127, 0, false, 0);
swiWaitForVBlank(); // Wait for the screen refresh // Wait for the screen refresh
swiWaitForVBlank();
} }
return 0; return 0;

View File

@ -1,404 +1,350 @@
// SPDX-License-Identifier: CC0-1.0 // SPDX-License-Identifier: CC0-1.0
// //
// SPDX-FileContributor: NightFox & Co., 2010 // SPDX-FileContributor: NightFox & Co., 2010
//
// Basic UDP communications example.
// http://www.nightfoxandco.com
/*
-------------------------------------------------
NightFox's Lib Template
Ejemplo basico comunicacion con el protocolo UDP
Requiere DevkitARM
Requiere NightFox's Lib
Codigo por NightFox
http://www.nightfoxandco.com
Inicio 10 de Octubre del 2009
-------------------------------------------------
*/
/*
-------------------------------------------------
Includes
-------------------------------------------------
*/
// Includes propietarios NDS
#include <nds.h> #include <nds.h>
// Includes C++
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <unistd.h> #include <unistd.h>
// Includes propios
#include <nf_lib.h> #include <nf_lib.h>
#include "nf_wifi.h" #include <nf_wifi.h>
/*
-------------------------------------------------
Defines
-------------------------------------------------
*/
#define myport 22334 #define myport 22334
char server_ip[18]; // Guarda la IP del servidor char server_ip[18]; // Stores the IP of the server
bool _ConnectWIFI(void); // Conectate al punto de acceso por defecto // Tries to connect to the default access point
u8 _SelectMode(void); // Servidor o cliente bool ConnectWIFI(void)
s16 _SendData(const char* mydata); // Envia datos por el canal abierto {
s16 _GetData(void); // Recibe datos por el canal abierto bool status = false;
s16 _LookForServer(void); // Busca un servidor al que conectarse
printf("Conectando via WFC...\n\n");
swiWaitForVBlank();
if (NF_WiFiConnectDefaultAp())
{
// Return connection parameters
printf("Conexion realizada.\n\n");
printf("IP : %s\n", inet_ntoa(NF_IP));
printf("Gateway: %s\n", inet_ntoa(NF_GATEWAY));
printf("Mask : %s\n", inet_ntoa(NF_MASK));
printf("DNS1 : %s\n", inet_ntoa(NF_DNS1));
printf("DNS2 : %s\n\n", inet_ntoa(NF_DNS2));
// Success
status = true;
}
else
{
// Error
printf("Conexion no establecida\n");
}
/* swiWaitForVBlank();
------------------------------------------------- return status;
Main() - Bloque general del programa
-------------------------------------------------
*/
int main(int argc, char **argv) {
u8 modo = 0; // Cliente (1) - Servidor (2)
u16 keys = 0; // Lectura del teclado
u32 contador = 0;
char temp[256];
bool loop = true;
bool senddata = true;
// Inicializa las 2D
NF_Set2D(0, 0); // Modo 2D_0 en la pantalla superior
NF_Set2D(1, 0); // Modo 2D_0 en la pantalla inferior
// Inicializa la consola de texto
consoleDemoInit();
consoleClear();
// Intenta conectarte al WFC...
if (_ConnectWIFI()) {
// Selecciona si seras servidor o cliente
modo = _SelectMode();
// Inicia como servidor o cliente
if (modo == 1) {
// Cliente
if (_LookForServer() > 0) {
//if (1) {
NF_WIFI_CreateUdpSender(server_ip, myport);
} else {
loop = false;
}
} else {
// Servidor
NF_WIFI_CreateUdpListener(myport);
}
// Envia o recive datos hasta cancelar la transmision
while (loop) {
// Lee el teclado
scanKeys();
keys = keysDown();
if (modo == 1) { // Envio de datos al servidor
// Si pulsas A, envia datos
if (keys & KEY_A) senddata = true;
// Si pulsas B, pausa el envio
if (keys & KEY_B) senddata = false;
// Si pulsas X, resetea el contador
if (keys & KEY_X) contador = 0;
// Si se pulsa R, sal
if (keys & KEY_R) loop = false;
if (senddata) {
if (loop) {
// Debes enviar datos...
sprintf(temp, "%05lu", contador);
} else {
// o la señal de salida?
sprintf(temp, "Exit");
}
// Envia y verifica si se han recibido
printf("Envio: %s\n", temp);
if (_SendData(temp) > 0) {
// Imprime los datos recibidos
printf("Verificado: %s\n\n", NF_RECV_BUFFER);
// Incrementa el valor
contador ++;
if (contador > 9999) contador = 0;
} else {
printf("Error de envio.\n");
}
}
} else { // Recepcion de datos desde el cliente
// Si se pulsa R, sal
if (keys & KEY_R) loop = false;
// Recibe los datos
if (_GetData() > 0) {
// Imprime los datos recibidos
printf("Recivido: %s\n", NF_RECV_BUFFER);
// Si has recibido la señal de salida...
if (strcmp(NF_RECV_BUFFER, "Exit") == 0) loop = false;
} else {
// Si no hay datos, esperalos
printf("Esperando datos...\n");
}
}
// Espera al sincronismo vertical
swiWaitForVBlank();
}
}
// Cierra el socket
close(NF_SOCKET);
// Deten el WIFI
NF_WiFiDisconnectAp();
// Informa
printf("\nSesion finalizada\n");
while (1) {
swiWaitForVBlank();
}
return 0;
} }
// Wait for the user to select client (1) or server (2) mode.
u8 SelectMode(void)
{
u8 modo = 0;
printf("A - Cliente\nB - Servidor\n");
swiWaitForVBlank();
while (modo == 0)
{
scanKeys();
u16 keys = keysDown();
if (keys & KEY_A)
modo = 1;
if (keys & KEY_B)
modo = 2;
/* swiWaitForVBlank();
------------------------------------------------- }
Funciones
-------------------------------------------------
*/
// Intenta conectarte al punto de acceso por defecto
bool _ConnectWIFI(void) {
bool status = false;
// Intenta conectarte al AP...
printf("Conectando via WFC...\n\n");
swiWaitForVBlank();
if (NF_WiFiConnectDefaultAp()) {
// Devuelve los parametros de la conexion TCP/IP con el AP
printf("Conexion realizada.\n\n");
printf("Ip : %s\n", inet_ntoa(NF_IP));
printf("Gateway: %s\n", inet_ntoa(NF_GATEWAY));
printf("Mask : %s\n", inet_ntoa(NF_MASK));
printf("Dns1 : %s\n", inet_ntoa(NF_DNS1));
printf("Dns2 : %s\n\n", inet_ntoa(NF_DNS2));
// Marca como conectado
status = true;
} else {
// No se ha podido conectar
printf("Conexion no establecida\n");
}
swiWaitForVBlank();
return status;
return modo;
} }
// Send data through the open channel
s16 SendData(const char *mydata)
{
bool checksum = false;
bool timeout = false;
s32 status = 0;
char buffer[NF_WIFI_BUFFER_SIZE];
// Copy data to a temporary buffer
sprintf(buffer, "%s", mydata);
// Selecciona si seras Cliente (1) o Servidor (2) while (!checksum && !timeout)
u8 _SelectMode(void) { {
// Send data using UDP
NF_WIFI_UdpSend(buffer);
u8 modo = 0; // Wait for the confirmation from the other end with a 600 ms timeout
u16 keys = 0; status = NF_WIFI_UdpListen(600000);
printf("A - Cliente\nB - Servidor\n"); // Do a data checksum
swiWaitForVBlank(); if (status > 0)
{
while (modo == 0) { if ((strcmp(NF_SEND_BUFFER, NF_RECV_BUFFER) == 0))
scanKeys(); {
keys = keysDown(); checksum = true;
if (keys & KEY_A) modo = 1; }
if (keys & KEY_B) modo = 2; else
swiWaitForVBlank(); {
} checksum = true;
status = -1; // Checksum error
return modo; }
}
else
{
timeout = true;
status = -2; // Timed out
}
}
return status;
} }
// Receive data from the open channel
s16 GetData(void)
{
// Listen to data with a 300 millisecond timeout
s32 status = NF_WIFI_UdpListen(300000);
// If any data has been received, return them to the sender to check them
if (status > 0)
NF_WIFI_UdpSend(NF_RECV_BUFFER);
// Envia datos por el canal abierto return status;
s16 _SendData(const char* mydata) {
// Variables
bool checksum = false;
bool timeout = false;
s32 status = 0;
char buffer[NF_WIFI_BUFFER_SIZE];
// Copia los datos al buffer
sprintf(buffer, "%s", mydata);
while (!checksum && !timeout) {
// Envia los datos por UDP
NF_WIFI_UdpSend(buffer);
// Espera la confirmacion de los datos
status = NF_WIFI_UdpListen(600000); // Time out 600 milisegundos
// Realiza un checksum de los datos
if (status > 0) {
if ((strcmp(NF_SEND_BUFFER, NF_RECV_BUFFER) == 0)) {
// Si el envio es correcto, continua
checksum = true;
} else {
checksum = true;
status = -1; // Error de checksum
}
} else {
timeout = true;
status = -2; // Time out
}
}
// Devuelve el estado
return status;
} }
// Scans all IPs in the specified range to look for a server to connect to.
s16 LookForServer(void)
{
// Variables locales
char myip[18];
char temp[64];
u16 p = 0;
// Recibe datos por el canal abierto bool loop = true;
s16 _GetData(void) { s8 status = 0;
// Variables // Get the local IP and extract its range (for example, "192.168.0.")
s32 status = 0; sprintf(temp, "%s", inet_ntoa(NF_IP));
for (int n = 0; n < strlen(temp); n ++)
{
myip[n] = temp[n];
char c = temp[n];
// Espera los datos if (c == '.')
status = NF_WIFI_UdpListen(300000); // Time out 300 milisegundos {
p++;
// Si se han recibido datos, devuelvelos para su verificacion // If this is the third dot, end the string
if (status > 0) NF_WIFI_UdpSend(NF_RECV_BUFFER); if (p == 3)
{
myip[n + 1] = '\0';
break;
}
}
}
// Devuelve el estado // Scan all possible IPs
return status; p = 0;
for (int n = 1; n < 255; n ++)
{
scanKeys();
u16 keys = keysDown();
// Generate IP
sprintf(temp, "%s%d", myip, n);
printf("%s ", temp);
swiWaitForVBlank();
// Create sender socket
NF_WIFI_CreateUdpSender(temp, myport);
// Send data and verify that it has been received
loop = true;
while (loop)
{
status = SendData("HANDSHAKE");
if (status > 0)
{
// Print received data
printf("Encontrado.\n");
// Save its value
sprintf(server_ip, temp);
p = n;
n = 255;
loop = false;
}
else
{
printf("Timed out.\n");
if (status == -2)
loop = false;
}
}
// Close the socket
close(NF_SOCKET);
// If the user wants to cancel, exit
if (keys & KEY_R)
break;
}
return p;
} }
int main(int argc, char **argv)
{
u8 modo = 0; // Client (1) - Server (2)
u32 contador = 0;
char temp[256];
bool loop = true;
bool senddata = true;
// Escanea el rango de IP's para encontrar el servidor // Initialize 2D engine in both screens and use mode 0
s16 _LookForServer(void) { NF_Set2D(0, 0);
NF_Set2D(1, 0);
// Variables locales // Initialize demo text console
char myip[18]; consoleDemoInit();
char temp[64];
char character[2];
u16 n = 0; // Try to connect to the WiFi access point
u16 p = 0; if (ConnectWIFI())
{
// Ask the user if this console is a server or a client
modo = SelectMode();
bool loop = true; if (modo == 1)
s8 status = 0; {
// Run as client
if (LookForServer() > 0)
NF_WIFI_CreateUdpSender(server_ip, myport);
else
loop = false;
}
else
{
// Run as server
NF_WIFI_CreateUdpListener(myport);
}
u16 keys = 0; // Send or receive data until the transmission is cancelled
while (loop)
{
scanKeys();
u16 keys = keysDown();
// Guarda la direccion IP local (su rango, por ejemplo "192.168.0." if (modo == 1)
sprintf(temp, "%s", inet_ntoa(NF_IP)); {
for (n = 0; n < (strlen(temp)); n ++) { // Send data to server
// Copia el caracter
memcpy((myip + n), (temp + n), 1);
memcpy(character, (temp + n), 1);
character[1] = '\0';
// Si es un punto...
if (strcmp(character, ".") == 0) {
p ++;
// Si es el 3er punto...
if (p == 3) {
myip[(n + 1)] = '\0'; // Pon el caracter terminador
n = strlen(temp); // Y termina
}
}
}
// Escanea todo el rango de IP's // Send data when the user presses A
p = 0; if (keys & KEY_A)
senddata = true;
for (n = 1; n < 255; n ++) { // Stop sending data when the user presses B
if (keys & KEY_B)
senddata = false;
// Lee el teclado // Reset counter when the user presses X
scanKeys(); if (keys & KEY_X)
keys = keysDown(); contador = 0;
// Calcula la IP // Exit if R is pressed
sprintf(temp, "%s%d", myip, n); if (keys & KEY_R)
printf("%s ", temp); loop = false;
swiWaitForVBlank();
// Crea el socket de envio if (senddata)
NF_WIFI_CreateUdpSender(temp, myport); {
if (loop)
{
// Send data if the loop is active
sprintf(temp, "%05lu", contador);
}
else
{
// If not, send an exit string
sprintf(temp, "Exit");
}
// Envia y verifica si se han recibido // Send it and verify that it has been received
loop = true; printf("Envio: %s\n", temp);
while (loop) { if (SendData(temp) > 0)
status = _SendData("HANDSHAKE"); {
if (status > 0) { // Print the received data
// Imprime los datos recibidos printf("Verificado: %s\n\n", NF_RECV_BUFFER);
printf("Encontrado.\n"); // Increment counter
// Guarda el valor contador++;
sprintf(server_ip, temp); if (contador > 9999)
p = n; contador = 0;
n = 255; }
loop = false; else
} else { {
printf("Time Out.\n"); printf("Error de envio.\n");
if (status == -2) loop = false; }
} }
} }
else
{
// Data reception in the client
// Cierra el socket creado // Exit loop if R is pressed
close(NF_SOCKET); if (keys & KEY_R)
loop = false;
// Si pulsas cancelar // Receive data
if (keys & KEY_R) n = 255; if (GetData() > 0)
{
// Print received data
printf("Recivido: %s\n", NF_RECV_BUFFER);
} // If the exit signal has been received
if (strcmp(NF_RECV_BUFFER, "Exit") == 0)
loop = false;
}
else
{
// If there is nothing available, wait for data
printf("Esperando datos...\n");
}
}
return p; // Wait for the screen refresh
swiWaitForVBlank();
}
}
// Close the socket
close(NF_SOCKET);
// Stop WiFi
NF_WiFiDisconnectAp();
printf("\nSesion finalizada\n");
while (1)
{
swiWaitForVBlank();
}
return 0;
} }

View File

@ -19,7 +19,8 @@ int main(int argc, char **argv)
while (1) while (1)
{ {
swiWaitForVBlank(); // Wait for the screen refresh // Wait for the screen refresh
swiWaitForVBlank();
} }
// If this is reached, the program will return to the loader if the loader // If this is reached, the program will return to the loader if the loader