int main(int argc, const char * argv[]) { //arrays de meses const char *meses[12] = { "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Nomviembre", "Diciembre" }; //instacio a File para abrir archivos como "archivo" FILE *archivo,*archivo1,*archivo2; //declaro a fila y un iterador int fila, i, pos_ini, pos_fin, cantidad_caracteres; //guardo la linea con un array de string char caracteres[TAMANO_LINEA]; //guardo la linea con un array de string char variable_destino[TAMANO_LINEA]; //declaro el separador de lineas char caracter_buscado = '*'; //Se define el nombre del archivo /*FILES EN MAC*//* char transacciones[1240]="/Applications/MAMP/htdocs/C/prueba/prueba/TRANSACCIONES.txt"; char productos[1250] = "/Applications/MAMP/htdocs/C/prueba/prueba/PRODUCTOS.txt"; char locales[1250] = "/Applications/MAMP/htdocs/C/prueba/prueba/LOCALES.txt"; */ /*FILES EN PC*/ char transacciones[1240]="TRANSACCIONES.txt"; char productos[1250] = "PRODUCTOS.txt"; char locales[1250] = "LOCALES.txt"; // Permite abrir archivo. archivo = fopen(transacciones,"r"); archivo1 = fopen(productos,"r"); archivo2 = fopen(locales,"r"); // Si el archivo no se encuentra o se esta dañado, no se puede leer. if (archivo == NULL || archivo1 == NULL || archivo2 == NULL) { printf("Archivo no puede ser leido\n\n"); system("pause"); exit(1); } /** * Estructura Transaccion * *<dia>*<mes>*<anio>*<id_local>*<id_producto>*<cantidad>* * */ // Definimos vector de largo NUMERO_REGISTROS de tipo de datos "linea" trans_1 var_transaccion[NUMERO_REGISTROS]; //Almacenamos las transacciones en el vector de estructura "var_transaccion" fila = 0; while (feof(archivo) == 0) { //Funcion que lee linea por linea e imprime por pantalla su resultado. fgets(caracteres,TAMANO_LINEA,archivo); strcpy(var_transaccion[fila].transaccion,caracteres); fila++; } trans_2 var_transaccion2[NUMERO_REGISTROS]; fila = 0; while (feof(archivo1) == 0) { //Funcion que lee linea por linea e imprime por pantalla su resultado. fgets(caracteres,TAMANO_LINEA,archivo1); strcpy(var_transaccion2[fila].transaccion,caracteres); fila++; } trans_3 var_transaccion3[NUMERO_REGISTROS]; fila = 0; while (feof(archivo2) == 0) { //Funcion que lee linea por linea e imprime por pantalla su resultado. fgets(caracteres,TAMANO_LINEA,archivo2); strcpy(var_transaccion3[fila].transaccion,caracteres); fila++; } // Se definen vectores de estructura transaccion ventas[NUMERO_REGISTROS]; producto prods[NUMERO_PRODUCTOS]; local loc[10]; //Proceso de extraccion for( i = 0; i < NUMERO_REGISTROS ; i++) { //Extraer dia pos_ini = 1; pos_fin = Buscar_String( var_transaccion[i].transaccion, caracter_buscado, pos_ini+1 ); cantidad_caracteres = ((pos_fin - pos_ini) - 1); substring(variable_destino,var_transaccion[i].transaccion,pos_ini+1,cantidad_caracteres); //Almacenamos el variable extraida a la estructura ventas[i].dia = atoi(variable_destino); //Extraer mes pos_ini = pos_fin; pos_fin = Buscar_String( var_transaccion[i].transaccion, caracter_buscado, pos_ini+1 ); cantidad_caracteres = ((pos_fin - pos_ini) - 1); substring(variable_destino,var_transaccion[i].transaccion,pos_ini+1,cantidad_caracteres); //Almacenamos el variable extraida a la estructura ventas[i].mes = atoi(variable_destino); //Extraer año pos_ini = pos_fin; pos_fin = Buscar_String( var_transaccion[i].transaccion, caracter_buscado, pos_ini+1 ); cantidad_caracteres = ((pos_fin - pos_ini) - 1); substring(variable_destino,var_transaccion[i].transaccion,pos_ini+1,cantidad_caracteres); //Almacenamos el variable extraida a la estructura ventas[i].anio = atoi(variable_destino); //Extraer id local pos_ini = pos_fin; pos_fin = Buscar_String( var_transaccion[i].transaccion, caracter_buscado, pos_ini+1 ); cantidad_caracteres = ((pos_fin - pos_ini) - 1); substring(variable_destino,var_transaccion[i].transaccion,pos_ini+1,cantidad_caracteres); //Almacenamos el variable extraida a la estructura ventas[i].id_local = atoi(variable_destino); //Extraer id producto pos_ini = pos_fin; pos_fin = Buscar_String( var_transaccion[i].transaccion, caracter_buscado, pos_ini+1 ); cantidad_caracteres = ((pos_fin - pos_ini) - 1); substring(variable_destino,var_transaccion[i].transaccion,pos_ini+1,cantidad_caracteres); //Almacenamos el variable extraida a la estructura ventas[i].id_producto = atoi(variable_destino); //Extraer cantidad pos_ini = pos_fin; pos_fin = Buscar_String( var_transaccion[i].transaccion, caracter_buscado, pos_ini+1 ); cantidad_caracteres = ((pos_fin - pos_ini) - 1); substring(variable_destino,var_transaccion[i].transaccion,pos_ini+1,cantidad_caracteres); //Almacenamos el variable extraida a la estructura ventas[i].cantidad = atoi(variable_destino); } //CERRAMOS EL ARCHIVO fclose(archivo); //Proceso de extraccion for(i=0;i<NUMERO_PRODUCTOS;i++) { //Extraer id producto pos_ini = 1; pos_fin = Buscar_String( var_transaccion2[i].transaccion, caracter_buscado, pos_ini+1 ); cantidad_caracteres = ((pos_fin - pos_ini) - 1); substring(variable_destino,var_transaccion2[i].transaccion,pos_ini+1,cantidad_caracteres); //Almacenamos el variable extraida a la estructura prods[i].id_producto = atoi(variable_destino); //Extraer nombre producto pos_ini = pos_fin; pos_fin = Buscar_String( var_transaccion2[i].transaccion, caracter_buscado, pos_ini+1 ); cantidad_caracteres = ((pos_fin - pos_ini) - 1); substring(variable_destino,var_transaccion2[i].transaccion,pos_ini+1,cantidad_caracteres); //Almacenamos el variable extraida a la estructura strcpy(prods[i].nombre_producto,variable_destino); //Extraer precio unitario pos_ini = pos_fin; pos_fin = Buscar_String( var_transaccion2[i].transaccion, caracter_buscado, pos_ini+1 ); cantidad_caracteres = ((pos_fin - pos_ini) - 1); substring(variable_destino,var_transaccion2[i].transaccion,pos_ini+1,cantidad_caracteres); //Almacenamos el variable extraida a la estructura prods[i].precio_unitario = atoi(variable_destino); } //CERRAMOS EL FILE fclose(archivo1); //Proceso de extraccion for( i = 0 ; i < 10 ; i++) { //Extraer id local pos_ini = 1; pos_fin = Buscar_String( var_transaccion3[i].transaccion, caracter_buscado, pos_ini+1 ); cantidad_caracteres = ((pos_fin - pos_ini) - 1); substring(variable_destino,var_transaccion3[i].transaccion,pos_ini+1,cantidad_caracteres); //Almacenamos el variable extraida a la estructura loc[i].id_local = atoi(variable_destino); //Extraer nombre local pos_ini = pos_fin; pos_fin = Buscar_String( var_transaccion3[i].transaccion, caracter_buscado, pos_ini+1 ); cantidad_caracteres = ((pos_fin - pos_ini) - 1); substring(variable_destino,var_transaccion3[i].transaccion,pos_ini+1,cantidad_caracteres); //Almacenamos el variable extraida a la estructura strcpy(loc[i].nombre_local,variable_destino); } //CERRAMOS EL ARCHIVO fclose(archivo2); char option; while(tolower((option=menu()))!='x'){ switch (option){ case 'a': //caso1 clearScreen(); int mes; printf("Ingrese un mes entre 1-12: \n"); scanf("%d", &mes); printf("\n"); if(mes>0 && mes<13) printf("MES: %s\nTOTAL: $%d\n", meses[mes-1], ventas_mes(ventas, prods, mes)); else printf("No no no xD, ingresaste un mes fuera de range[1-12]!!!!, mes ingresado ->%d\n", mes ); printf("\n"); system("pause"); clearScreen(); break; case 'b': //caso2 printf(""); int cod_buscado; printf("Ingrese Cod sucursal: \n"); scanf("%d", &cod_buscado); printf("\n"); buscar_sucursal(loc, cod_buscado); printf("\n"); system("pause"); clearScreen(); break; case 'c': //caso3 printf(""); int dia_b, mes_b, cod_b;//cod local printf("Ingresar dia: \n"); scanf("%d", &dia_b); printf("Ingresar mes: \n"); scanf("%d", &mes_b); if(date_is_valid(dia_b, mes_b)){ printf("Ingresar cod local: \n"); scanf("%d", &cod_b); printf("\n"); //existe local? if(!existe_local(loc, cod_b)) transacciones_buscadas(ventas, loc, prods, dia_b, mes_b, cod_b); else printf("Hey el codigo local -> %d, no es valido\n", cod_b); }else{ printf("FECHA INVALIDA, INGRESASTE %d-%d\n", dia_b, mes_b); } system("pause"); clearScreen(); break; default: printf("Comando invalido\n\n"); system("pause"); clearScreen(); break; } } return 0; }
static int linenoiseEdit(struct current *current) { int history_index = 0; /* The latest history entry is always our current buffer, that * initially is just an empty string. */ linenoiseHistoryAdd(""); set_current(current, ""); refreshLine(current->prompt, current); while(1) { int dir = -1; int c = fd_read(current); #ifndef NO_COMPLETION /* Only autocomplete when the callback is set. It returns < 0 when * there was an error reading from fd. Otherwise it will return the * character that should be handled next. */ if (c == '\t' && current->pos == current->chars && completionCallback != NULL) { c = completeLine(current); /* Return on errors */ if (c < 0) return current->len; /* Read next character when 0 */ if (c == 0) continue; } #endif process_char: if (c == -1) return current->len; #ifdef USE_TERMIOS if (c == 27) { /* escape sequence */ c = check_special(current->fd); } #endif switch(c) { case '\r': /* enter */ history_len--; free(history[history_len]); return current->len; case ctrl('C'): /* ctrl-c */ errno = EAGAIN; return -1; case 127: /* backspace */ case ctrl('H'): if (remove_char(current, current->pos - 1) == 1) { refreshLine(current->prompt, current); } break; case ctrl('D'): /* ctrl-d */ if (current->len == 0) { /* Empty line, so EOF */ history_len--; free(history[history_len]); return -1; } /* Otherwise fall through to delete char to right of cursor */ case SPECIAL_DELETE: if (remove_char(current, current->pos) == 1) { refreshLine(current->prompt, current); } break; case SPECIAL_INSERT: /* Ignore. Expansion Hook. * Future possibility: Toggle Insert/Overwrite Modes */ break; case ctrl('W'): /* ctrl-w, delete word at left. save deleted chars */ /* eat any spaces on the left */ { int pos = current->pos; while (pos > 0 && get_char(current, pos - 1) == ' ') { pos--; } /* now eat any non-spaces on the left */ while (pos > 0 && get_char(current, pos - 1) != ' ') { pos--; } if (remove_chars(current, pos, current->pos - pos)) { refreshLine(current->prompt, current); } } break; case ctrl('R'): /* ctrl-r */ { /* Display the reverse-i-search prompt and process chars */ char rbuf[50]; char rprompt[80]; int rchars = 0; int rlen = 0; int searchpos = history_len - 1; rbuf[0] = 0; while (1) { int n = 0; const char *p = NULL; int skipsame = 0; int searchdir = -1; snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf); refreshLine(rprompt, current); c = fd_read(current); if (c == ctrl('H') || c == 127) { if (rchars) { int p = utf8_index(rbuf, --rchars); rbuf[p] = 0; rlen = strlen(rbuf); } continue; } #ifdef USE_TERMIOS if (c == 27) { c = check_special(current->fd); } #endif if (c == ctrl('P') || c == SPECIAL_UP) { /* Search for the previous (earlier) match */ if (searchpos > 0) { searchpos--; } skipsame = 1; } else if (c == ctrl('N') || c == SPECIAL_DOWN) { /* Search for the next (later) match */ if (searchpos < history_len) { searchpos++; } searchdir = 1; skipsame = 1; } else if (c >= ' ') { if (rlen >= (int)sizeof(rbuf) + 3) { continue; } n = utf8_getchars(rbuf + rlen, c); rlen += n; rchars++; rbuf[rlen] = 0; /* Adding a new char resets the search location */ searchpos = history_len - 1; } else { /* Exit from incremental search mode */ break; } /* Now search through the history for a match */ for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) { p = strstr(history[searchpos], rbuf); if (p) { /* Found a match */ if (skipsame && strcmp(history[searchpos], current->buf) == 0) { /* But it is identical, so skip it */ continue; } /* Copy the matching line and set the cursor position */ set_current(current,history[searchpos]); current->pos = utf8_strlen(history[searchpos], p - history[searchpos]); break; } } if (!p && n) { /* No match, so don't add it */ rchars--; rlen -= n; rbuf[rlen] = 0; } } if (c == ctrl('G') || c == ctrl('C')) { /* ctrl-g terminates the search with no effect */ set_current(current, ""); c = 0; } else if (c == ctrl('J')) { /* ctrl-j terminates the search leaving the buffer in place */ c = 0; } /* Go process the char normally */ refreshLine(current->prompt, current); goto process_char; } break; case ctrl('T'): /* ctrl-t */ if (current->pos > 0 && current->pos <= current->chars) { /* If cursor is at end, transpose the previous two chars */ int fixer = (current->pos == current->chars); c = get_char(current, current->pos - fixer); remove_char(current, current->pos - fixer); insert_char(current, current->pos - 1, c); refreshLine(current->prompt, current); } break; case ctrl('V'): /* ctrl-v */ if (has_room(current, 3)) { /* Insert the ^V first */ if (insert_char(current, current->pos, c)) { refreshLine(current->prompt, current); /* Now wait for the next char. Can insert anything except \0 */ c = fd_read(current); /* Remove the ^V first */ remove_char(current, current->pos - 1); if (c != -1) { /* Insert the actual char */ insert_char(current, current->pos, c); } refreshLine(current->prompt, current); } } break; case ctrl('B'): case SPECIAL_LEFT: if (current->pos > 0) { current->pos--; refreshLine(current->prompt, current); } break; case ctrl('F'): case SPECIAL_RIGHT: if (current->pos < current->chars) { current->pos++; refreshLine(current->prompt, current); } break; case SPECIAL_PAGE_UP: dir = history_len - history_index - 1; /* move to start of history */ goto history_navigation; case SPECIAL_PAGE_DOWN: dir = -history_index; /* move to 0 == end of history, i.e. current */ goto history_navigation; case ctrl('P'): case SPECIAL_UP: dir = 1; goto history_navigation; case ctrl('N'): case SPECIAL_DOWN: history_navigation: if (history_len > 1) { /* Update the current history entry before to * overwrite it with tne next one. */ free(history[history_len - 1 - history_index]); history[history_len - 1 - history_index] = strdup(current->buf); /* Show the new entry */ history_index += dir; if (history_index < 0) { history_index = 0; break; } else if (history_index >= history_len) { history_index = history_len - 1; break; } set_current(current, history[history_len - 1 - history_index]); refreshLine(current->prompt, current); } break; case ctrl('A'): /* Ctrl+a, go to the start of the line */ case SPECIAL_HOME: current->pos = 0; refreshLine(current->prompt, current); break; case ctrl('E'): /* ctrl+e, go to the end of the line */ case SPECIAL_END: current->pos = current->chars; refreshLine(current->prompt, current); break; case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */ if (remove_chars(current, 0, current->pos)) { refreshLine(current->prompt, current); } break; case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */ if (remove_chars(current, current->pos, current->chars - current->pos)) { refreshLine(current->prompt, current); } break; case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */ if (current->capture && insert_chars(current, current->pos, current->capture)) { refreshLine(current->prompt, current); } break; case ctrl('L'): /* Ctrl+L, clear screen */ clearScreen(current); /* Force recalc of window size for serial terminals */ current->cols = 0; refreshLine(current->prompt, current); break; default: /* Only tab is allowed without ^V */ if (c == '\t' || c >= ' ') { if (insert_char(current, current->pos, c) == 1) { refreshLine(current->prompt, current); } } break; } } return current->len; }
void user_init(void) { uint8_t i; UartDev.data_bits = EIGHT_BITS; UartDev.parity = NONE_BITS; UartDev.stop_bits = ONE_STOP_BIT; uart_init(BIT_RATE_9600, BIT_RATE_9600); i2c_init(); SSD1306Init(); clearScreen(); stringDraw(1, 1, "SDK ver:"); stringDraw(1, 48, (char*)system_get_sdk_version()); ets_uart_printf("reset reason: %d\n", reset_info->reason); ets_uart_printf("Booting...\n"); ets_uart_printf("SDK version:%s\n", system_get_sdk_version()); setup_wifi_st_mode(); if(wifi_get_phy_mode() != PHY_MODE_11N) wifi_set_phy_mode(PHY_MODE_11N); if(wifi_station_get_auto_connect() == 0) wifi_station_set_auto_connect(1); #ifdef CONFIG_DYNAMIC flash_param_t *flash_param; flash_param_init(); flash_param = flash_param_get(); UartDev.data_bits = GETUART_DATABITS(flash_param->uartconf0); UartDev.parity = GETUART_PARITYMODE(flash_param->uartconf0); UartDev.stop_bits = GETUART_STOPBITS(flash_param->uartconf0); uart_init(flash_param->baud, BIT_RATE_115200); #else #endif ets_uart_printf("size flash_param_t %d\n", sizeof(flash_param_t)); #ifdef CONFIG_GPIO config_gpio(); #endif // os_timer_disarm(&timer_1); // os_timer_setfn(&timer_1, (os_timer_func_t *)timer_1_int, NULL); // os_timer_arm(&timer_1, 1000, 1); // Wait for Wi-Fi connection os_timer_disarm(&WiFiLinker); os_timer_setfn(&WiFiLinker, (os_timer_func_t *)wifi_check_ip, NULL); os_timer_arm(&WiFiLinker, 1000, 0); system_os_task(recvTask, recvTaskPrio, recvTaskQueue, recvTaskQueueLen); }
int qArrive(Queue *q, productList *products) { int code, quantity; char id[10]; char input; Customer *c = newCustomer(); Product *p; basketItem *item; printf("\n\tEnter customer id:\n\t"); scanf("%s", id); customerInit(c, id); clearScreen(); do { clearScreen(); printf("\n\tAdd items to bill of '%s'\n", id); printf("\n\t\tEnter product code: \t(0: quit)\n\t\t"); scanf("%d", &code); if(code==0) break; p=findProductByCode(code, products); if(p==NULL) { printf("Error: Cannot add item to basket."); wait(); continue; } printf("\n\t\tEnter quantity:\n\t\t"); scanf("%d", &quantity); addToBasket(c, newBasketItem(p, quantity)); printf("\n\t\t%d of %s were added to the basket.", quantity, getProductName(p)); printf("\n\n\t\t[backspace: undo 0: done 1: continue]\n\t\t"); input = getch(); if(input=='\b') { remFromBasket(c); printf("\n\t\tLast item was removed successfully!"); wait(); continue; } }while(input!='0'); queueInsert(q, c); }
int main(int argc, char *argv[]) { /* initialize SDL and its subsystems */ if (SDL_Init(SDL_INIT_EVERYTHING) == -1) die(); if (TTF_Init() == -1) die(); /* set the height and width of the main window, as well as the number of bits per pixel; this needs to be done prior to initializing the main window (*screen, below) */ initWindowAttributes(); /* the frame buffer */ SDL_Surface *screen = SDL_SetVideoMode(W_WIDTH, W_HEIGHT, W_COLOR_DEPTH, SDL_HWSURFACE|SDL_FULLSCREEN); if (!screen) die(); /* hide the mouse cursor */ SDL_ShowCursor(SDL_DISABLE); /* the background color of the screen */ const Uint32 clearColor = CLEAR_COLOR(screen->format); clearScreen(screen, clearColor); /* clearColor as an SDL_Color, for use with TTF */ Uint8 r, g, b; SDL_GetRGB(clearColor, screen->format, &r, &g, &b); SDL_Color bgColor = { r: r, g: g, b: b }; /* the score font */ TTF_Font *font = TTF_OpenFont("resources/VeraMono.ttf", FONT_SIZE); if (!font) die(); SDL_Color fontColor = FONT_COLOR; /* the score text; we'll allow three digits plus the terminating '\0' */ char *lScoreStr = malloc(sizeof(char) * 4); char *rScoreStr = malloc(sizeof(char) * 4); if (!lScoreStr || !rScoreStr) die(); SDL_Surface *lScore = NULL, *rScore = NULL; SDL_Rect lScorePos = { x: C_X+FONT_SIZE, y: C_HEIGHT/5, w: F_WIDTH, h: F_HEIGHT }; SDL_Rect rScorePos = { x: (C_X+C_WIDTH)-3*FONT_SIZE, y: C_HEIGHT/5, w: F_WIDTH, h: F_HEIGHT }; /* set up the playing court */ Court *court = makeCourt(screen); if (!court) die(); /* set up the players and their paddles */ Player *lPlayer = makePlayer(screen); Player *rPlayer = makePlayer(screen); if (!lPlayer || !rPlayer) die(); rPlayer->paddle.rect.x = C_X + C_WIDTH - P_WIDTH; /* add the ball */ Ball *ball = makeBall(screen); if (!ball) die(); /* because SDL_KEY(UP|DOWN) occurs only once, not continuously while the key is pressed, we need to keep track of whether a key is (still) pressed */ bool lPlayerShouldMoveUp = false, lPlayerShouldMoveDown = false, rPlayerShouldMoveUp = false, rPlayerShouldMoveDown = false; Uint32 startTime; /* denotes the beginning of each iteration of the main event loop */ bool running = true; /* true till the application should exit */ while (running) { startTime = SDL_GetTicks(); /* clear the previous frame's paddles and ball */ SDL_FillRect(screen, &lPlayer->paddle.rect, clearColor); SDL_FillRect(screen, &rPlayer->paddle.rect, clearColor); SDL_FillRect(screen, &ball->rect, clearColor); /* clear the previous frame's score */ SDL_FillRect(screen, &lScorePos, clearColor); SDL_FillRect(screen, &rScorePos, clearColor); /* redraw the walls in case they were clipped by the ball in a previous frame */ SDL_FillRect(screen, &court->upperWall, court->color); SDL_FillRect(screen, &court->lowerWall, court->color); /* get the current state of the players' controls */ readPlayerInput(&running, &lPlayerShouldMoveUp, &lPlayerShouldMoveDown, &rPlayerShouldMoveUp, &rPlayerShouldMoveDown); /* save the current position of the paddles */ lPlayer->paddle.prevY = lPlayer->paddle.rect.y; rPlayer->paddle.prevY = rPlayer->paddle.rect.y; /* move the paddles if appropriate */ if (lPlayerShouldMoveUp) movePaddle(court, &lPlayer->paddle, UP); else if (lPlayerShouldMoveDown) movePaddle(court, &lPlayer->paddle, DOWN); if (rPlayerShouldMoveUp) movePaddle(court, &rPlayer->paddle, UP); else if (rPlayerShouldMoveDown) movePaddle(court, &rPlayer->paddle, DOWN); /* move the ball */ moveBall(court, ball, lPlayer, rPlayer); /* update the score */ updateScore(ball, lPlayer, rPlayer); /* update the on-screen score */ if (lScore) SDL_FreeSurface(lScore); snprintf(lScoreStr, 4, "%2d", lPlayer->points); lScore = TTF_RenderText_Shaded(font, lScoreStr, fontColor, bgColor); if (rScore) SDL_FreeSurface(rScore); snprintf(rScoreStr, 4, "%2d", rPlayer->points); rScore = TTF_RenderText_Shaded(font, rScoreStr, fontColor, bgColor); /* draw the score */ SDL_BlitSurface(lScore, NULL, screen, &lScorePos); SDL_BlitSurface(rScore, NULL, screen, &rScorePos); /* draw the paddles */ SDL_FillRect(screen, &lPlayer->paddle.rect, lPlayer->paddle.color); SDL_FillRect(screen, &rPlayer->paddle.rect, rPlayer->paddle.color); /* draw the ball */ SDL_FillRect(screen, &ball->rect, ball->color); /* render frame to screen */ SDL_Flip(screen); /* keep a steady frame rate */ Uint8 elapsedTime = SDL_GetTicks() - startTime; if (elapsedTime < FRAME_DURATION) SDL_Delay(FRAME_DURATION - elapsedTime); } /* free resources */ free(lScoreStr); free(rScoreStr); free(court); free(lPlayer); free(rPlayer); free(ball); TTF_CloseFont(font); TTF_Quit(); SDL_FreeSurface(lScore); SDL_FreeSurface(rScore); SDL_Quit(); return EXIT_SUCCESS; }
void loadSplash(void){ clearScreen(); fileRead(fb->top_left, "/rei/splash.bin", 0x46500); }
int qFront(Queue *q) { clearScreen(); printBill(queueFront(q)); wait(); }
void Game::play() { Player* p = mLevels[0]->player(); if (p == NULL) { mLevels[0]->display(); return; } string msg; bool message, compmessage; do { p->heal(); mLevels[currentlvl]->check_dead_monsters(); clearScreen(); mLevels[currentlvl]->display(); if (message) { cout << msg << endl; message = false; } else if (compmessage) { cout << msg << endl; compmessage = false; } msg = ""; char move = getCharacter(); if (!p->is_sleep()) { switch (move) { case 'c': //cheat p->cheat(); break; case 'g': //pick up items message = mLevels[currentlvl]->pick_up(msg); break; case 'w': //view use weapons message = p->showInvent('w', msg); break; case 'r': //view scrolls message = p->showInvent('r', msg); break; case 'i': //view inventory message = p->showInvent('i', msg); break; case ARROW_LEFT: case ARROW_RIGHT: case ARROW_UP: case ARROW_DOWN: message = p->move(move, msg); break; case '>': if(mLevels[currentlvl]->next_level()) { currentlvl++; mLevels[currentlvl] = new Levels(currentlvl, p); mLevels[currentlvl]->add_player(); } break; case 'q': exit(1); default: break; } } p->changeSleep(-1); compmessage = mLevels[currentlvl]->move_monsters(msg); } while (!mLevels[currentlvl]->player()->is_dead()); clearScreen(); mLevels[currentlvl]->display(); cout << msg; cout << "Press q to exit game. " << endl; char a; while (a != 'q') { a = getCharacter(); if (a == 'q') exit(1); } }
kmain() { clearScreen(); print("================================================================================\n",0x0F); print(" Welcome to Q OS\n\n",0x0F); print("================================================================================\n",0x0F); while (1) { print("\nQ-Kernel> ",0x0F); string ch = readStr(); if(strEql(ch,"help ")) { print("\nShowing Help for Q OS ",0x0F); } else if(strEql(ch,"do")) { print("\n> ",0x0F); string tmp = readStr(); if(strEql(tmp,"repeat")) { print("\nrepeat> ",0x0F); string tmp = readStr(); nano = 1; while(1) { printch('\n',0x0F); print(tmp,0x0F); } } if(strEql(tmp,"execute")) { print("\n",0x0F); } else { print("The 'do' command does not support the command you entered or it does not exist ",0x0F); } } else if(strEql(ch,"ls")) { print("\nNo Files Found on Disk ",0x0F); } else if(strEql(ch,"cd")) { print("\nThe specified directory was not found ",0x0F); } else if(strEql(ch,"nano")) { nano = 1; clearScreen(); print(" Q-OS Nano Text Editor Version 0.1 ",0xF0); print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",0x0F); print(" Built for Q-OS by Raph Hennessy ",0xF0); cursorX = 0; cursorY = 1; updateCursor(); string nanoOutput = readStr(); } else if(strEql(ch,"clear")) { clearScreen(); } else if(strEql(ch,"sudo")) { print("\n",0x0F); } else if(strEql(ch,"exit")) { print("\n",0x0F); } else if(strEql(ch,"run")) { print("\n",0x0F); } else { print("\nCommand Not Found ",0x0F); } print("\n",0x0F); } }
void planeBall() { unsigned char x; clearScreen(black); // draw a red plane for (x = 0; x < 5; x++) { drawLine3D(x, 0, 1, x, 4, 1, red); } fade(5, 10); swapAndWait(1000); setVoxel((voxel) {2, 2, 5}, green); swapAndWait(100); setVoxel((voxel) {2, 2, 5}, black); setVoxel((voxel) {2, 2, 4}, green); swapAndWait(100); setVoxel((voxel) {2, 2, 4}, black); setVoxel((voxel) {2, 2, 3}, green); swapAndWait(100); setVoxel((voxel) {2, 2, 3}, black); setVoxel((voxel) {2, 2, 2}, green); swapAndWait(100); setVoxel((voxel) {2, 2, 2}, black); setVoxel((voxel) {2, 2, 3}, green); swapAndWait(100); setVoxel((voxel) {2, 2, 3}, black); setVoxel((voxel) {2, 2, 2}, green); swapAndWait(1000); clearImage(black); for (x = 0; x < 5; x++) { drawLine3D(x, 0, 0, x, 4, 2, red); } fade(5, 5); // now the ball has to roll to y = 0 swapAndWait(400); setVoxel((voxel) {2, 2, 2}, black); setVoxel((voxel) {2, 1, 2}, green); swapAndWait(200); setVoxel((voxel) {2, 1, 2}, black); setVoxel((voxel) {2, 0, 1}, green); swapAndWait(1000); clearImage(black); for (x = 0; x < 5; x++) { drawLine3D(x, 0, 1, x, 4, 1, red); } setVoxel((voxel) {2, 0, 2}, green); fade(5, 5); swapAndWait(400); clearImage(black); for (x = 0; x < 5; x++) { drawLine3D(x, 0, 2, x, 4, 0, red); } setVoxel((voxel) {2, 0, 3}, green); fade(5, 5); swapAndWait(400); setVoxel((voxel) {2, 0, 3}, black); setVoxel((voxel) {2, 1, 2}, green); swapAndWait(200); setVoxel((voxel) {2, 1, 2}, black); setVoxel((voxel) {2, 2, 2}, green); swapAndWait(200); setVoxel((voxel) {2, 2, 2}, black); setVoxel((voxel) {2, 3, 1}, green); swapAndWait(200); setVoxel((voxel) {2, 3, 1}, black); setVoxel((voxel) {2, 4, 1}, green); swapAndWait(200); setVoxel((voxel) {2, 2, 2}, black); setVoxel((voxel) {2, 3, 1}, green); swapAndWait(200); setVoxel((voxel) {2, 3, 1}, black); setVoxel((voxel) {2, 4, 1}, green); swapAndWait(200); swapAndWait(1000); clearImage(black); for (x = 0; x < 5; x++) { drawLine3D(x, 0, 1, x, 4, 1, red); } setVoxel((voxel) {2, 4, 2}, green); fade(5, 5); }
void movingCubes() { // Startpoint of the cube voxel cube1 = {0, 0, 0}, cube2 = {3, 3, 3}, cube3 = {0, 3, 3}; direction way[] = {up, right, up, right, up, right, forward, forward, forward, down, left, back, down, back, back, down, left, left, up, right, down, left, 0}; unsigned char i, j; for (j = 0; j < 5; j++) { i = 0; while(way[i]) { switch (way[i++]) { case up: cube1.z++; cube2.x--; cube3.z--; if (cube1.z > MAX_Z-1) cube1.z = 0; if (cube2.x > MAX_X-1) cube2.x = 0; if (cube3.z > MAX_Z-1) cube3.z = 0; break; case down: cube1.z--; cube2.x++; cube3.z++; if (cube1.z > MAX_Z-1) cube1.z = 0; if (cube2.x > MAX_X-1) cube2.x = 0; if (cube3.z > MAX_Z-1) cube3.z = 0; break; case right: cube1.x++; cube2.z--; cube3.x++; if (cube1.x > MAX_X-1) cube1.z = 0; if (cube2.z > MAX_Z-1) cube2.x = 0; if (cube3.x > MAX_X-1) cube3.x = 0; break; case left: cube1.x--; cube2.z++; cube3.x--; if (cube1.x > MAX_X-1) cube1.x = 0; if (cube2.z > MAX_Z-1) cube2.z = 0; if (cube3.x > MAX_X-1) cube3.x = 0; break; case forward: cube1.y++; cube2.y--; cube3.y--; if (cube1.y > MAX_Y-1) cube1.y = 0; if (cube2.y > MAX_Y-1) cube2.y = 0; if (cube3.y > MAX_Y-1) cube3.y = 0; break; case back: cube1.y--; cube2.y++; cube3.y++; if (cube1.y > MAX_Y-1) cube1.y = 0; if (cube2.y > MAX_Y-1) cube2.y = 0; if (cube3.y > MAX_Y-1) cube3.y = 0; break; default: break; } drawCube(cube1, 0); drawCube(cube2, 1); drawCube(cube3, 2); swapAndWait(110); clearScreen(black); } } }
/* * Emulate a single CPU cycle. Frequency = 60 Hz. */ void Chip8::emulateCycle() { // Fetch the opcode (two bytes, from "pc" location) current_opcode = memory[pc] << 8 | memory[pc+1]; //We don't need to draw unless 0x00E0 or 0xDXYN are executed. draw_flag = 0; v_registers[0xF] = 0; // Decode and execute the opcode // "https://en.wikipedia.org/wiki/CHIP-8#Opcode_table" switch(current_opcode & 0xF000) { case 0x0000: switch(current_opcode & 0x00FF) { case 0x00E0: { // 00E0 "Clears the screen." clearScreen(); draw_flag = 1; pc = pc + 2; break; } case 0x00EE: { // 00EE "Returns from a subroutine." // Set pc to the address at the top of the stack. // Subtract one from the stack pointer. pc = stack[sp]; sp = sp - 1; break; } default: { // 0NNN "Calls RCA 1802 program at address NNN. Not necessary for most ROMs." pc = (current_opcode & 0x0FFF); break; } } break; case 0x1000: { // 1NNN "Jumps to address NNN." pc = (current_opcode & 0x0FFF); break; } case 0x2000: { // 2NNN "Calls subroutine at NNN." // The stack pointer is incremented by 1. // The address of the next instruction (current pc + 2) is put on the stack. // The pc value is set to NNN. sp = sp + 1; stack[sp] = pc + 2; pc = (current_opcode & 0x0FFF); break; } case 0x3000: { // 3XNN "Skips the next instruction if VX equals NN." int registerIndex = (current_opcode & 0x0F00) >> 8; int immediateVale = (current_opcode & 0x00FF); if (v_registers[registerIndex] == immediateVale) { pc = pc + 4; } else { pc = pc + 2; } break; } case 0x4000: { // 4XNN "Skips the next instruction if VX doesn't equal NN." int registerIndex = (current_opcode & 0x0F00) >> 8; int immediateVale = (current_opcode & 0x00FF); if (v_registers[registerIndex] != immediateVale) { pc = pc + 4; } else { pc = pc + 2; } break; } case 0x5000: { // 5XY0 "Skips the next instruction if VX equals VY." int registerIndex = (current_opcode & 0x0F00) >> 8; int registerIndex2 = (current_opcode & 0x00F0) >> 4; if (v_registers[registerIndex] == v_registers[registerIndex2]) { pc = pc + 4; } else { pc = pc + 2; } break; } case 0x6000: { // 6XNN "Set VX to NN." int registerIndex = (current_opcode & 0x0F00) >> 8; int immediateVale = (current_opcode & 0x00FF); v_registers[registerIndex] = immediateVale; pc = pc + 2; break; } case 0x7000: { // 7XNN "Adds NN to VX." int registerIndex = (current_opcode & 0x0F00) >> 8; int immediateValue = (current_opcode & 0x00FF); v_registers[registerIndex] += immediateValue; pc = pc + 2; break; } case 0x8000: { switch (current_opcode & 0x000F) { case 0x0000: { // 8XY0 "Sets VX to the value of VY." // TODO Chip8::unsupportedOpcode(current_opcode, pc); break; } case 0x0001: { // 8XY1 "Sets VX to VX OR VY." // TODO Chip8::unsupportedOpcode(current_opcode, pc); break; } case 0x0002: { // 8XY2 "Sets VX to VX AND VY." // TODO Chip8::unsupportedOpcode(current_opcode, pc); break; } case 0x0003: { // 8XY3 ""Sets VX to VX XOR VY. // TODO Chip8::unsupportedOpcode(current_opcode, pc); break; } case 0x0004: { // 8XY4 "Adds VY to VX. VF is set to 1 if there is a carry, 0 otherwise." int registerIndex = (current_opcode & 0x0F00) >> 8; int registerIndex2 = (current_opcode & 0x00F0) >> 4; int sum = v_registers[registerIndex] + v_registers[registerIndex2]; if (sum > 255) { v_registers[0xF] = 1; v_registers[registerIndex] = (sum & 0xFF); } else { v_registers[0xF] = 0; v_registers[registerIndex] = sum; } pc = pc + 2; break; } case 0x0005: { // 8XY5 "VY is subtracted fro VX. VF is set to 0 if there is a borrow, 1 otherwise." // TODO Chip8::unsupportedOpcode(current_opcode, pc); break; } case 0x0006: { // 8XY6 "Shifts VX right by one. VF is set to the value of the LSB of VX before the shift." // TODO Chip8::unsupportedOpcode(current_opcode, pc); break; } case 0x0007: { // 8XY7 "Sets VX to VY minux VX. VF is set to 0 if there is a borrow, 1 otherwise." // TODO Chip8::unsupportedOpcode(current_opcode, pc); break; } case 0x000E: { // 8XYE "Shift VX left by one. VF is set to the value of the MSB of VX before the shift." // TODO Chip8::unsupportedOpcode(current_opcode, pc); break; } default: { std::cout << "Unknown instruction: " << current_opcode << std::endl; break; } } break; } case 0x9000: { // 9XY0 "Skips the next instruction if VX doesn't equal VY." int registerIndex = (current_opcode & 0x0F00) >> 8; int registerIndex2 = (current_opcode & 0x00F0) >> 4; if (v_registers[registerIndex] != v_registers[registerIndex2]) { pc = pc + 4; } else { pc = pc + 2; } break; } case 0xA000: { // ANNN "Sets I to the address NNN." index_reg = (current_opcode & 0x0FFF); pc = pc + 2; break; } case 0xB000: { // BNNN "Jumps to the address NNN plus V0." pc = v_registers[0] + (current_opcode & 0x0FFF); break; } case 0xC000: { // CXNN "Sets VX to the result of a bitwise AND operation on a random number and NN." // Generate a random number from 0 to 255, AND it with NN, set result in V[X] int randNum = rand() % 0xFF; int immediateValue = (current_opcode & 0x00FF); int registerIndex = (current_opcode & 0x0F00) >> 8; randNum = randNum & immediateValue; v_registers[registerIndex] = randNum; pc = pc + 2; break; } case 0xD000: { // DXYN "Draw a sprite at position VX, VY with N bytes of sprite data starting at the address stored in I." int column = v_registers[(current_opcode & 0x0F00) >> 8]; int row = v_registers[(current_opcode & 0x00F0) >> 4]; int numRows = current_opcode & 0x000F; for (int i = 0; i < numRows; i++) { for (int j = 0; j < 8; j++) { // Each byte is a row, each bit is a pixel int bitValue = (memory[index_reg + i] >> (7-j)) & 0b00000001; if (bitValue == 1) { if (screen[row + i][column + j] == 1) { //Set VF register v_registers[0xF] = 1; screen[row + i][column + j] = 0; } else { screen[row + i][column + j] = 1; } } } } pc = pc + 2; draw_flag = 1; break; } case 0xE000: { switch(current_opcode & 0x00FF) { case 0x009E: { // EX9E "Skips the next instruction if the key stored in VX is pressed." // TODO Chip8::unsupportedOpcode(current_opcode, pc); break; } case 0x00A1: { // EXA1 "Skips the next instruction if the key stored in VX isn't pressed." // TODO Chip8::unsupportedOpcode(current_opcode, pc); break; } default: { std::cout << "Unknown instruction: " << current_opcode << std::endl; break; } } break; } case 0xF000: { switch(current_opcode & 0x0FF) { case 0x0007: { // FX07 "Sets VX to the value of the delay timer. int registerIndex = (current_opcode &0x0F00) >> 8; v_registers[registerIndex] = delay_timer; pc = pc + 2; break; } case 0x000A: { // FX0A "A key press is awaited and then stored in VX." // TODO Chip8::unsupportedOpcode(current_opcode, pc); break; } case 0x0015: { // FX15 "Sets the delay timer to VX." int registerIndex = (current_opcode & 0x0F00) >> 8; delay_timer = v_registers[registerIndex]; pc = pc + 2; break; } case 0x0018: { // FX18 "Sets the sound timer to VX." int registerIndex = (current_opcode & 0x0F00) >> 8; sound_timer = v_registers[registerIndex]; pc = pc + 2; break; } case 0x001E: { // FX1E "Adds VX to I." // TODO Chip8::unsupportedOpcode(current_opcode, pc); break; } case 0x0029: { // FX29 "Sets I to the location of the sprite for the character in VX. // TODO Chip8::unsupportedOpcode(current_opcode, pc); break; } case 0x0033: { // FX33 "Store the binary-coded decimal equivalent of the value stored in register VX at addresses I, I+1, and I+2." // TODO Chip8::unsupportedOpcode(current_opcode, pc); break; } case 0x0055: { // FX55 "Stores V0 to VX in memory starting at address I." // TODO Chip8::unsupportedOpcode(current_opcode, pc); break; } case 0x0065: { // FX65 "Fills V0 to VX with values from memory starting at address I." // TODO Chip8::unsupportedOpcode(current_opcode, pc); break; } default: { std::cout << "Unknown instruction: " << current_opcode << std::endl; break; } } break; } default: { std::cout << "Unknown instruction: " << current_opcode << std::endl; break; } } // Update timers if (delay_timer > 0) { delay_timer--; } if (sound_timer > 0) { sound_timer--; } }
int main(int argc, char **argv) { SDL_Window *win; SDL_Renderer *g; int win_width = 1152, win_height = 720; int flag_forceinwin = 1, dtime = 1000; struct color *renderColor = &GHETTO_WHITE; struct color *backgroundColor = &GHETTO_BLACK; // dem args int c; while ((c = getopt(argc, argv, "t:yh")) != -1) { switch (c) { case 't': // reset delay time dtime = atoi(optarg); printf("Delay time set to: %ims\n", dtime); break; case 'y': // yolo mode flag_forceinwin = 0; printf("YOLO mode intiated\n"); break; case 'h': printHelp(argv[0]); return 0; default: break; } } // seed dat RNG srand((unsigned int) time(NULL)); initSDL(); // grab a window and a renderer win = getWindow(win_width, win_height); g = getRenderer(win); // clear screen setClearColor(backgroundColor); clearScreen(g); // blue lines (for now) setColor(g, renderColor); // line number; used to decide direction // start at 1 int lineNo = 1; // necesary line node structures for linked list: // root line node in list struct node *root = malloc(sizeof(struct node)); // previously generated line node struct node *previous; // line node undergoing generation struct node *current; // first line, start at middle, rand length, go from there struct line *firstLine = genNextLine(NULL, lineNo); // move line to center (genNextLine starts at (0, 0) when // previous is NULL) translateLine(firstLine, win_width / 2, win_height / 2); root->line = firstLine; root->next = current; previous = root; clearScreen(g); drawLine(g, root->line); render(g); // increment line count so loop starts on horizonal lineNo++; delay(dtime); while (1) { if (!handleEvents()) break; // allocate memory for new node current = malloc(sizeof(struct node)); // add to linked list; // new is old's next previous->next = current; if (flag_forceinwin) { // keep line bound to window bounds while (1) { current->line = genNextLine(previous->line, lineNo); if (current->line->x2 > win_width || current->line->y2 > win_height) free(current->line); else break; } } else { // line can do whatever tf it wants current->line = genNextLine(previous->line, lineNo); } // THIS is very necessary; // in rendering: // iterate through linked list until next is NULL // if you don't set new next to null, it thinks theres another // value (will be reset to next element in next iteration of loop) current->next = NULL; clearScreen(g); drawAllLines(g, root); render(g); previous = current; lineNo++; // break up sleeping into smaller segments // to allow user to exit faster int i; for (i = 0; i < 10; i++) { if (!handleEvents()) break; delay(dtime / 10); } if (i < 10) break; } freeLineList(root); cleanup(g, win); return 0; }
void drawTitleScreen(char* str) { clearScreen(0x00); centerString("HANS",0); renderString(str, 0, 40); }
/*! * \fn void exportCsu() * Export a csu file into a csv or pdf file */ void exportCsu() { csuStruct *ptr_csu_struct; char filename[SIZE_MAX_FILE_NAME]; char export_filename[SIZE_MAX_FILE_NAME]; FileType type; clearScreen(); // Get the filename menuFileName(filename); #ifndef PORTABLE if(readSystemPath(filename)==false) return; #endif // PORTABLE ptr_csu_struct=readCsuFile(filename); // Read the file if (ptr_csu_struct == NULL) { systemPause(); return; } // Prepare the exportation strcpy(export_filename,filename); removeFileExtension(export_filename); type = menuChooseExportFileType(); if (type == pdf_file) { addFilePdfExtension(export_filename); if (exportToPdf(ptr_csu_struct,export_filename)) printf(_("The file was well export to %s\n"),export_filename); else printf(_("There is an error when exporting the file %s into a pdf file.\n"),filename); } else if (type == gnuplot_file) { if (exportToGnuplotFile(ptr_csu_struct,export_filename)) printf(_("The file was well export to %s\n"),export_filename); else printf(_("There is an error when exporting the file %s into gnuplot files.\n"),filename); } else if (type == csv_file) { addFileCsvExtension(export_filename); if (exportToCsv(ptr_csu_struct,export_filename)) printf(_("The file was well export to %s\n"),export_filename); else printf(_("There is an error when exporting the file %s into a csv file.\n"),filename); } else { addFileExtension(export_filename,"m"); if (exportToM(ptr_csu_struct,export_filename)) printf(_("The file was well export to %s\n"),export_filename); else printf(_("There is an error when exporting the file %s into a m file.\n"),filename); } closeCsuStruct(ptr_csu_struct); systemPause(); }
int single_game(){ Audio RRR; openAudioFile(".\\wav\\RRR.wav", &RRR); initializeKeyInput(); Character yg = characterMaking1(".\\pic\\yg.pixel",".\\pic\\yg.color"); int key_val[NUM_KEYS]={VK_A,VK_D,VK_ESCAPE}; int stand=0,score=0,standBrick,pDown1,pDown2; double drop=0,scoreCount=0; Brick bricks[15]; int i,j,k; char scoreStr[4]={'0'}; for(i=0;i<10;i++){ bricks[i].y=-1; bricks[i].w=40; bricks[i].h=2; if(i%2==0)bricks[i].color=15; else if(i<=5)bricks[i].color=8; else if(i>5)bricks[i].color=12; else bricks[i].color=10; } bricks[0].x=0; bricks[0].y=100; Font *large_font=read_font("font.txt"); float lastbrick=0; int hp = 10,second=0; float rate=0.15; while(1){ clearScreen(); srand(clock()); for(i=0;i<10;i++){ if(bricks[i].y>0)bricks[i].y--; else if(bricks[i].y==0)bricks[i].y=-100; for(k=0;k<2;k++){ for(j=0;j<bricks[k].w;j++){ putString(bricks[i].x+j,bricks[i].y+k,"=",bricks[i].color,0); } } } if(score>50){ rate = 0.2; } else if(score>75){ rate = 0.25; } else if(score>100){ rate = 0.3; } if((float)clock()/(float)CLOCKS_PER_SEC-(float)lastbrick>rate&&rand()%10==1){ for(i=0;i<10;i++){ if(bricks[i].y<0){ bricks[i].y=170; bricks[i].x=rand()%185; lastbrick=(float)clock()/(float)CLOCKS_PER_SEC; for(k=0;k<2;k++){ for(j=0;j<bricks[i].w;j++){ putString(bricks[i].x+j,bricks[i].y+k,"=",bricks[i].color,0); } } break; } } } for(k=0;k<10;k++){ if(abs(yg.y+yg.h-bricks[k].y)<=2&&( (yg.x+yg.w>bricks[k].x&&yg.x+yg.w<bricks[k].x+bricks[k].w)|| (yg.x>bricks[k].x&&yg.x<bricks[k].x+bricks[k].w))){ stand=1; standBrick=k; yg.y=bricks[k].y-yg.h; break; } else if(k==9){ stand=0; standBrick=-1; } } if(stand==1){ drop=0; second++; if(bricks[standBrick].color==15&&second==15){ second=0; if(hp<10)hp++; } else if(bricks[standBrick].color==12){ second++; if(second==20){ second=0; hp--; playAudio(&RRR); } } else if(bricks[standBrick].color==8){ if(second==10){ second=0; bricks[standBrick].y=-100; } } } else{ if(drop<2)drop+=0.5; yg.y+=(int)drop; second=0; } if(yg.y<0){ yg.y+=10; drop=3; hp-=4; playAudio(&RRR); } for (k = 0 ; k < NUM_KEYS ; k++){ if(KEY_DOWN(key_val[k])){ switch (key_val[k]){ case VK_A: if(yg.x>=0)yg.x-=5; break; case VK_D: if(yg.x+yg.w<225)yg.x+=5; break; case VK_ESCAPE: return 3; break; } } } show_image(yg.pic,yg.x,yg.y); for(i=0;i<225;i++){ for(j=151;j<=170;j++){ putString(i,j," ",0,0); } } putStringLarge(large_font,159,158,"HP ",15); putStringLarge(large_font,159,152,"STAGE ",15); scoreCount++; score = (pow(scoreCount/300,1.5)); scoreStr[0]=score/100+'0'; scoreStr[1]=score/10%10+'0'; scoreStr[2]=score%10+'0'; putStringLarge(large_font,201,152,scoreStr,15); for(i=0;i<hp;i++){ for(j=1;j<5;j++){ for(k=0;k<=4;k++)putString(180+i*4+j,158+k,"|",12,0); } } for(i=0;i<225;i++)putString(i,0,"V",12,0); for(i=0;i<225;i++){ putString(i,149,"=",12,0); } for(i=0;i<150;i++){ putString(0,i,"|",0,12); putString(224,i,"|",0,12); } drawCmdWindow(); if(yg.y>150||hp<=0){ break; }; if(KEY_UP(VK_P)&&pDown1)pDown1=0; if(KEY_UP(VK_P)&&pDown2)pDown2=0; if(KEY_DOWN(VK_P)&&!pDown1){ pDown1=1; putStringLarge(large_font,45,70,"Press P to continue",12); drawCmdWindow(); Sleep(500); while(1){ if(KEY_DOWN(VK_P)&&!pDown2){ pDown2=1; break; } } } Sleep(20); } pauseAudio(&RRR); Image * jh =read_image(".\\pic\\jh.pixel",".\\pic\\jh.color"); show_image(jh,15,30); putStringLarge(large_font,75,80,"SCORE ",15); putStringLarge(large_font,120,80,scoreStr,15); drawCmdWindow(); Audio *barbar; openAudioFile(".\\wav\\88wav.wav",&barbar); playAudio(&barbar); Sleep(3500); int flagg = 1; putStringLarge(large_font, 45, 90, "Press esc to exit", 15); drawCmdWindow(); while(flagg){ if(KEY_DOWN(VK_ESCAPE))return 3; } clearScreen(); }
/** * * Function to control the iRobot depending on the character pressed, call it like keyboardInput(serial_getc()); * @param c the character that would determine if the iRobot moves, uses serial_getc() */ void keyboardInput(char c) { // toggle precision mode, if activated, move is 5 cm and 5 degrees if(c == 'T') { if(precision == 0){ serial_puts("PRECISION ACTIVATED\n\r\n\r"); precision = 1; } else{ serial_puts("PRECISION DEACTIVATED\n\r\n\r"); precision = 0; } } // move the iRobot forward, 10 cm else if(c == 'W') { if(precision) { serial_puts("MOVING FORWARD 5 CM\n\r\n\r"); moveFowardUpdate(sensor_data, 5); } else { serial_puts("MOVING FORWARD 10 CM\n\r\n\r"); moveFowardUpdate(sensor_data, 10); } wait_ms(100); } // move the iRobot backwards, 10 cm else if(c == 'S') { if(precision) { serial_puts("MOVING BACKWARD 5 CM\n\r\n\r"); moveBackward(sensor_data, 5); } else { serial_puts("MOVING BACKWARD 10 CM\n\r\n\r"); moveBackward(sensor_data, 10); } wait_ms(100); } // rotate the iRobot counter clockwise, 15 degrees else if(c == 'A') { if(precision) { serial_puts("TURNING COUNTER CLOCKWISE 5 DEGREES\n\r\n\r"); turn_counter_clockwise(sensor_data, 5); // TODO } else { serial_puts("TURNING COUNTER CLOCKWISE 15 DEGREES\n\r\n\r"); turn_counter_clockwise(sensor_data, 15); // TODO } wait_ms(100); } // rotate the iRobot clockwise, 15 degrees else if(c == 'D') { if(precision) { serial_puts("TURNING CLOCKWISE 5 DEGREEES\n\r\n\r"); turn_clockwise(sensor_data, 5); // TODO } else { serial_puts("TURNING CLOCKWISE 15 DEGREEES\n\r\n\r"); turn_clockwise(sensor_data, 15); // TODO } wait_ms(100); } // start sweeping for ir and sonar data else if(c == ' ') { oi_play_song(0); serial_puts("SWEEPING FOR OBJECTS\n\r"); smallestObjectSweep(); wait_ms(100); } // clear screen else if(c == '-') { clearScreen(); wait_ms(100); } // finish command else if(c == 'f') { if(serial_getc == 'i') { if(serial_getc == 'n') { if(serial_getc == 'i') { if(serial_getc == 's') { if(serial_getc == 'h') { isFinished = 1; } } } } } } // if any other key is pressed, nothing happens }
main() { int reg = 0, option = 0; struct { char name[50]; char address[50]; int age; char phone[20]; } customer; clearScreen(); reg = appMainMenu(); clearScreen(); option = appMenu(); if (reg == CUSTOMER) { switch (option) { case INSERT: clearScreen(); printf("CLIENTES - CADASTRO\n======================\n\n"); printf("Nome: "); scanf(" %[^\n]s", &customer.name); //getchar(); printf("Endereço: "); scanf(" %50[^\n]s", &customer.address); //getchar(); printf("Idade: "); scanf(" %d", &customer.age); //getchar(); printf("Telefone: "); scanf(" %20[^\n]s", &customer.phone); //getchar(); FILE *fp; fp = fopen("files/customer.txt", "a+"); char *record, *age; sprintf(age, "%d", customer.age); strcpy(record, "\n"); strcat(record, "1\t\t\t\t"); strcat(record, customer.name); strcat(record, "\t\t\t\t"); strcat(record, customer.address); strcat(record, "\t\t\t\t"); strcat(record, age); strcat(record, "\t\t\t\t"); strcat(record, customer.phone); fprintf(fp, record); fclose(fp); break; case EDIT: appPrintf("EDITAR CLIENTE"); break; case DELETE: appPrintf("APAGAR CLIENTE"); break; case SELECT: appPrintf("SELECIONAR UM CLIENTE"); break; default: appPrintf("LISTAR TODOS"); } } }
/** * Main function. */ int main(int argc, const char *argv[]) { int value; void *cards[6]; initializeAllegroStuff(); zoneAllocatorInitialize(); initializeWadFile(WAD_FILE_PATH); initializeStaticGraphicsData(); initializeStaticWidgetData(); systemGraphicsSetPalette((unsigned char *)getWadFileLumpContentsByName("PLAYPAL")); clearScreen(); cards[0] = getWadFileLumpContentsByName("STKEYS0"); cards[1] = getWadFileLumpContentsByName("STKEYS1"); cards[2] = getWadFileLumpContentsByName("STKEYS2"); cards[3] = getWadFileLumpContentsByName("STKEYS3"); cards[4] = getWadFileLumpContentsByName("STKEYS4"); cards[5] = getWadFileLumpContentsByName("STKEYS5"); initializeNumberWidget(&numberWidget, NUMBER_WIDGET_STYLE_SMALL, 100, 10, 10, &value); value = 1; drawNumberWidget(&numberWidget); numberWidget.y = 20; value = 2; drawNumberWidget(&numberWidget); numberWidget.y = 30; value = 0x80000000; drawNumberWidget(&numberWidget); numberWidget.y = 40; value = 4; drawNumberWidget(&numberWidget); numberWidget.y = 50; numberWidget.style = NUMBER_WIDGET_STYLE_LARGE; value = 5; drawNumberWidget(&numberWidget); numberWidget.y = 70; value = -6; drawNumberWidget(&numberWidget); numberWidget.y = 90; value = 12345; drawNumberWidget(&numberWidget); numberWidget.y = 110; value = -67890; drawNumberWidget(&numberWidget); numberWidget.y = 130; numberWidget.style = NUMBER_WIDGET_STYLE_SMALL; value = 12345; drawNumberWidget(&numberWidget); numberWidget.y = 140; value = 67890; drawNumberWidget(&numberWidget); numberWidget.y = 150; numberWidget.style = NUMBER_WIDGET_STYLE_LARGE_PERCENT; value = 50; drawNumberWidget(&numberWidget); initializeChoiceWidget(&choiceWidget, cards, 10, 170, &value); value = 0; drawChoiceWidget(&choiceWidget); choiceWidget.x = 20; value = 1; drawChoiceWidget(&choiceWidget); choiceWidget.x = 30; value = 2; drawChoiceWidget(&choiceWidget); choiceWidget.x = 40; value = -1; drawChoiceWidget(&choiceWidget); choiceWidget.x = 50; value = 3; drawChoiceWidget(&choiceWidget); choiceWidget.x = 60; value = 4; drawChoiceWidget(&choiceWidget); choiceWidget.x = 70; value = 5; drawChoiceWidget(&choiceWidget); initializeOnOffWidget(&onOffWidget, cards[0], 10, 180, &value); value = 0; drawOnOffWidget(&onOffWidget); onOffWidget.x = 20; value = 1; drawOnOffWidget(&onOffWidget); numberWidget.x = 100; numberWidget.y = 200; numberWidget.style = NUMBER_WIDGET_STYLE_INTERMISSION; value = 12345; drawNumberWidget(&numberWidget); numberWidget.y = 220; value = -67890; drawNumberWidget(&numberWidget); numberWidget.y = 240; numberWidget.style = NUMBER_WIDGET_STYLE_INTERMISSION_PERCENT; value = 50; drawNumberWidget(&numberWidget); readkey(); return 0; }
static int generate_pwd_shares(sc_card_t *card, char **pwd, int *pwdlen, int password_shares_threshold, int password_shares_total) { int r, i; BIGNUM *prime; BIGNUM *secret; unsigned char buf[64]; char hex[64]; int l; secret_share_t *shares = NULL; secret_share_t *sp; u8 rngseed[16]; if ((password_shares_threshold == -1) || (password_shares_total == -1)) { fprintf(stderr, "Must specify both, --pwd-shares-total and --pwd-shares-threshold\n"); return -1; } if (password_shares_total < 3) { fprintf(stderr, "--pwd-shares-total must be 3 or larger\n"); return -1; } if (password_shares_threshold < 2) { fprintf(stderr, "--pwd-shares-threshold must 2 or larger\n"); return -1; } if (password_shares_threshold > password_shares_total) { fprintf(stderr, "--pwd-shares-threshold must be smaller or equal to --pwd-shares-total\n"); return -1; } printf( "\nThe DKEK will be enciphered using a randomly generated 64 bit password.\n"); printf( "This password is split using a (%i-of-%i) threshold scheme.\n\n", password_shares_threshold, password_shares_total); printf( "Please keep the generated and encrypted DKEK file in a safe location. We also recommend \n"); printf( "to keep a paper printout, in case the electronic version becomes unavailable. A printable version\n"); printf( "of the file can be generated using \"openssl base64 -in <filename>\".\n"); printf("\n\nPress <enter> to continue"); waitForEnterKeyPressed(); *pwd = calloc(1, 8); *pwdlen = 8; r = sc_get_challenge(card, (unsigned char *)*pwd, 8); if (r < 0) { printf("Error generating random key failed with %s", sc_strerror(r)); OPENSSL_cleanse(*pwd, *pwdlen); free(*pwd); return r; } **pwd &= 0x7F; // Make sure the bit size of the secret is not bigger than 63 bits /* * Initialize prime and secret */ prime = BN_new(); secret = BN_new(); /* * Encode the secret value */ BN_bin2bn((unsigned char *)*pwd, *pwdlen, secret); /* * Generate seed and calculate a prime depending on the size of the secret */ r = sc_get_challenge(card, rngseed, SEED_LENGTH); if (r < 0) { printf("Error generating random seed failed with %s", sc_strerror(r)); OPENSSL_cleanse(*pwd, *pwdlen); free(*pwd); return r; } r = generatePrime(prime, secret, 64, rngseed, SEED_LENGTH); if (r < 0) { printf("Error generating valid prime number. Please try again."); OPENSSL_cleanse(*pwd, *pwdlen); free(*pwd); return r; } // Allocate data buffer for the generated shares shares = malloc(password_shares_total * sizeof(secret_share_t)); createShares(secret, password_shares_threshold, password_shares_total, prime, shares); sp = shares; for (i = 0; i < password_shares_total; i++) { clearScreen(); printf("Press <enter> to display key share %i of %i\n\n", i + 1, password_shares_total); waitForEnterKeyPressed(); clearScreen(); printf("Share %i of %i\n\n", i + 1, password_shares_total); l = BN_bn2bin(prime, buf); sc_bin_to_hex(buf, l, hex, 64, ':'); printf("\nPrime : %s\n", hex); printf("Share ID : %s\n", BN_bn2dec((sp->x))); l = BN_bn2bin((sp->y), buf); sc_bin_to_hex(buf, l, hex, 64, ':'); printf("Share value : %s\n", hex); printf("\n\nPlease note ALL values above and press <enter> when finished"); waitForEnterKeyPressed(); sp++; } clearScreen(); cleanUpShares(shares, password_shares_total); BN_clear_free(prime); BN_clear_free(secret); return 0; }
int qRear(Queue *q) { clearScreen(); printBill(queueRear(q)); wait(); }
static int recreate_password_from_shares(char **pwd, int *pwdlen, int num_of_password_shares) { int r, i; BIGNUM *prime; BIGNUM *secret; BIGNUM *p; char inbuf[64]; unsigned char bin[64]; size_t binlen = 0; unsigned char *ip; secret_share_t *shares = NULL; secret_share_t *sp; if (num_of_password_shares < 2) { fprintf(stderr, "--pwd-shares-total must 2 or larger\n"); return -1; } // Allocate data buffer for the shares shares = malloc(num_of_password_shares * sizeof(secret_share_t)); if (!shares) return -1; /* * Initialize prime and secret */ prime = BN_new(); secret = BN_new(); printf("\nDeciphering the DKEK for import into the SmartCard-HSM requires %i key custodians", num_of_password_shares); printf("\nto present their share. Only the first key custodian needs to enter the public prime."); printf("\nPlease remember to present the share id as well as the share value."); printf("\n\nPlease enter prime: "); memset(inbuf, 0, sizeof(inbuf)); if (fgets(inbuf, sizeof(inbuf), stdin) == NULL) { fprintf(stderr, "Input aborted\n"); free(shares); return -1; } binlen = 64; sc_hex_to_bin(inbuf, bin, &binlen); BN_bin2bn(bin, binlen, prime); sp = shares; for (i = 0; i < num_of_password_shares; i++) { clearScreen(); printf("Press <enter> to enter share %i of %i\n\n", i + 1, num_of_password_shares); waitForEnterKeyPressed(); clearScreen(); sp->x = BN_new(); sp->y = BN_new(); printf("Share %i of %i\n\n", i + 1, num_of_password_shares); printf("Please enter share ID: "); memset(inbuf, 0, sizeof(inbuf)); if (fgets(inbuf, sizeof(inbuf), stdin) == NULL) { fprintf(stderr, "Input aborted\n"); free(shares); return -1; } p = (sp->x); BN_hex2bn(&p, inbuf); printf("Please enter share value: "); memset(inbuf, 0, sizeof(inbuf)); if (fgets(inbuf, sizeof(inbuf), stdin) == NULL) { fprintf(stderr, "Input aborted\n"); free(shares); return -1; } binlen = 64; sc_hex_to_bin(inbuf, bin, &binlen); BN_bin2bn(bin, binlen, (sp->y)); sp++; } clearScreen(); r = reconstructSecret(shares, num_of_password_shares, prime, secret); if (r < 0) { printf("\nError during reconstruction of secret. Wrong shares?\n"); cleanUpShares(shares, num_of_password_shares); return r; } /* * Encode the secret value */ ip = (unsigned char *) inbuf; *pwdlen = BN_bn2bin(secret, ip); *pwd = calloc(1, *pwdlen); if (*pwd) { memcpy(*pwd, ip, *pwdlen); } cleanUpShares(shares, num_of_password_shares); BN_clear_free(prime); BN_clear_free(secret); return *pwd ? 0 : -1; }
int main(int argc, char *argv[]) { gpio pins[NB_PINS]; FILE *toolsFile, *systemFile; char batteryStatus[BUFFER], networkName[BUFFER], toolsData[BUFFER]; char batterieData[BUFFER], ressourceData[BUFFER], networkData[BUFFER], charge[BUFFER]; int ram, nbConnections; float cpu; initLCD(pins, NB_PINS); clearScreen(pins, NB_PINS); if (argc == 2 && strcmp(argv[1], "restore") == 0) { writeLine(0, "[ INSERT MICRO-SD ]", pins, NB_PINS); writeLine(1, "Before restoration, ", pins, NB_PINS); writeLine(2, "save your data , or", pins, NB_PINS); writeLine(3, "they will be lost !!", pins, NB_PINS); } else if (argc == 2 && strcmp(argv[1], "update") == 0) { writeLine(0, "====================", pins, NB_PINS); writeLine(1, " SYSTEM UPDATE ", pins, NB_PINS); writeLine(2, "====================", pins, NB_PINS); writeLine(3, "DO NOT DISCONNECT...", pins, NB_PINS); } else if (argc == 2 && strcmp(argv[1], "restore-wait") == 0) { writeLine(0, "====================", pins, NB_PINS); writeLine(1, " RESTORE. WAIT. ", pins, NB_PINS); writeLine(2, "====================", pins, NB_PINS); writeLine(3, " FORMATING SD CARD ", pins, NB_PINS); } else if (argc == 2 && strcmp(argv[1], "shutdown") == 0) { writeLine(0, "====================", pins, NB_PINS); writeLine(1, " NO MICROSD CARD ", pins, NB_PINS); writeLine(2, "====================", pins, NB_PINS); writeLine(3, "SYSTEM WILL SHUTDOWN", pins, NB_PINS); } else if (argc == 2 && strcmp(argv[1], "reboot") == 0) { writeLine(0, "====================", pins, NB_PINS); writeLine(1, " SYTEM WILL REBOOT ", pins, NB_PINS); writeLine(2, "====================", pins, NB_PINS); writeLine(3, "DO NOT DISCONNECT...", pins, NB_PINS); } else if (argc == 2 && strcmp(argv[1], "boot") == 0) { writeLine(0, "====================", pins, NB_PINS); writeLine(1, " COWBOX ", pins, NB_PINS); writeLine(2, "====================", pins, NB_PINS); writeLine(3, "SYSTEM IS BOOTING...", pins, NB_PINS); } else if (argc >= 3) { while (1) { toolsFile = fopen(argv[1], "r"); systemFile = fopen(argv[2], "r"); if (systemFile != NULL && toolsFile != NULL) { backToBegin(pins, NB_PINS, DURATION); fscanf(systemFile, "battery_status=%255s\n", batteryStatus); fscanf(systemFile, "battery_level=%255s\n", charge); fscanf(systemFile, "network=%255s\n", networkName); fscanf(systemFile, "nb_connected=%255d\n", &nbConnections); fscanf(systemFile, "cpu_used=%255f\n", &cpu); fscanf(systemFile, "ram_used=%255d\n", &ram); fscanf(toolsFile, "%255s\n", toolsData); fclose(systemFile); fclose(toolsFile); sprintf(batterieData, "%3s%% %15s", charge, batteryStatus); sprintf(networkData, "%20s", networkName); sprintf(ressourceData, "CPU %03d%% RAM %03d%%", (int)(100 - cpu), (int)((811 - ram/1000.0)/100.0)); sprintf(toolsData, "Connected: %9d" , nbConnections); writeLine(0, batterieData, pins, NB_PINS); writeLine(1, networkData, pins, NB_PINS); writeLine(2, ressourceData, pins, NB_PINS); writeLine(3, toolsData, pins, NB_PINS); shutdownLCD(pins, NB_PINS); sleep(PAUSE); initLCD(pins, NB_PINS); clearScreen(pins, NB_PINS); } } } shutdownLCD(pins, NB_PINS); return EXIT_SUCCESS; }
int main(){ /* KAMUS */ Queuepemain players; char namapemain[30]; gedung posisi[20]; int turn,langkah,dadu1,dadu2,dadusama,nplayers,i; pemain x; /* ALGORITMA */ printf("Masukkan jumlah pemain : "); scanf("%d",&nplayers); createqueuepemain(&players,nplayers); for(i=1;i<=nplayers;i++){ printf("Nama pemain %d :",i); scanf("%s",namapemain); x=createpemain(namapemain,i); addpemain(&players,x); } printf("\n"); srand(time(NULL)); isigedung(posisi); turn=1; while(!isgame(players)){ do{ usleep(10000000); clearScreen(); viewboard(players); gotoxy(2,37); usleep(500000); viewstatuspemain(players); usleep(500000); printf("*****LOG PERMAINAN*****\n"); printf("-----Turn %d-----\n",turn); printf("Giliran : %s\n",players.t[players.head].nama); dadusama=0; kocokdadu(&dadu1,&dadu2); usleep(500000); if(letakpemain(players)!=5){ langkah=(dadu1+dadu2); viewgamelog(&players,posisi,langkah); }else{ if((isdadusama(dadu1,dadu2))||((players.t[players.head].npenjara==0))){ players.t[players.head].npenjara=0; printf("%s keluar dari penjara.\n",players.t[players.head].nama); langkah=(dadu1+dadu2); viewgamelog(&players,posisi,langkah); }else { printf("Angka dadu tidak sama, %s keluar dari penjara setelah %d putaran.\n",players.t[players.head].nama,players.t[players.head].npenjara); players.t[players.head].npenjara=players.t[players.head].npenjara-1; langkah=0;//tidak bisa melangkah } } if((isdadusama(dadu1,dadu2))&&(letakpemain(players)!=5)){ printf("%s mendapatkan dadu yang sama.\n",players.t[players.head].nama); dadusama++; } if(dadusama==3){ players.t[players.head].letak=5; players.t[players.head].npenjara=2; printf("%s mendapatkan dadu yang sama tiga kali berturut-turut, %s masuk penjara.\n",players.t[players.head].nama,players.t[players.head].nama); } }while((isdadusama(dadu1,dadu2))&&(dadusama<=3)&&(letakpemain(players)!=5)); changeturn(&players); turn++; } printf("%s MEMENANGKAN PERMAINAN!\n",players.t[players.tail].nama); return 0; }
/* You must call makeInterrupt21() before this function will work. */ void handleInterrupt21(int ax, int bx, int cx, int dx) { switch(ax) { case 0: printString(bx); break; case 1: readString(bx); break; case 2: readSector(bx,cx); break; case 3: readFile(bx,cx,dx); break; case 4: runProgram(bx,cx); break; case 5: stop(); break; case 6: writeSector(bx,cx); break; case 7: deleteFile(bx); break; case 8: writeFile(bx,cx,dx); break; case 11: interrupt(25,0,0,0,0); break; case 12: clearScreen(bx, cx); break; case 13: writeInt(bx); break; case 14: readInt(bx); break; case 15: error(bx); break; default: printString("ERROR: Requested service does not exist."); } }
void launchShell() { initialize_calc(); //allocate some memory for command string buffer. 1kB should be enough for now const int bufSize = 128; char bufStr[bufSize];//Store sanitized user command (no arguments) char rawCommand[bufSize];//Gets user raw command from command line char arguments[bufSize/2][bufSize/2];//Store command arguments int fs = 1;//First space (first word means actual command) int ay = -1;//Y location for arguments int ax = 0;//X location for argumetns //prepare variable for(int i = 0; i < bufSize; ++i){ bufStr[i] = 0; } for(int y = 0; y < bufSize; ++y){ for(int x = 0; x < bufSize; ++x){ arguments[y][x] = 0; } } #define TIP print("\nTip: If enter key does not work, it might mean that the input is too long",0x0F); #define HELP print("\nWorking Commands in Q OS: \nwriter\nclear\nexecute\nhi\nskip (the no action)\nfiles\ncat\nreboot\ncalc", 0x0F); #define BIGHELP kbHelp(); TIP; HELP; #define SYSTEMMAN system(arguments); #define SAYHI print("\nHello!", 0x3F); #define CATFILE print("\nFile Name> ", 0x0F); readStr(bufStr, bufSize); ASSERT(strlength(bufStr) < MAX_FNAME_LEN); cat(finddir_fs(fs_root, bufStr)); #define SWITCHDIR print("\nThe specified directory was not found ", 0x0F); #define CALCULATE calc(arguments); #define BIGCLEAR clearScreen(); printIntro(); #define MKDIR print("\nThis Command is Reserved for when we have a FAT32 or better FileSystem...", 0x3F); #define RMFILE print("\nThis Command is Reserved for when we have a FAT32 or better FileSystem...", 0x3F); #define SKIP skip(rawCommand); #define FILEMAN files(arguments); #define WRITE writer(arguments); #define ME me(rawCommand); #define CMDNOTFOUND print("\n", 0x0F); print(bufStr, 0x0F); print(": Command Not Found ", 0x0F); while (true) { print("\nQ-Kernel> ", 0x08); typingCmd = true; newCmd = true; readStr(rawCommand, bufSize); typingCmd = false; for(int i = 0; i < bufSize; ++i){ bufStr[i] = 0; } for(int y = 0; y < bufSize; ++y){ for(int x = 0; x < bufSize; ++x){ arguments[y][x] = 0; } } fs = 1; ay = -1; ax = 0; if(MULTI_ARG_DEBUG == true) { //Sanitize raw input. Move first word to bufStr and move the rest of the word to arguments for(int i = 0; i < bufSize; ++i) { if(rawCommand[i] != 0 || rawCommand[i] != 10) { if(fs == 1) bufStr[i] = rawCommand[i]; else if(fs == 0) arguments[ay][ax] = rawCommand[i]; if(i < bufSize && rawCommand[i+1] == 32) { fs = 0; ay++; } } else break; } } else { //Sanitize raw input. Move first word to bufStr and move the rest of the word to arguments for(int i = 0; i < bufSize; ++i) { if(rawCommand[i] != 0 || rawCommand[i] != 10) { if(fs == 1) bufStr[i] = rawCommand[i]; if(i < bufSize && rawCommand[i+1] == 32) { fs = 0; ay++; ax = 0; } else if(fs == 0) { arguments[ay][ax] = rawCommand[i]; ax++; } } else break; } } if (strEql(strTrim(bufStr), "")) { HELP; } else if(strEql(bufStr, "help")) { BIGHELP; } else if(strEql(bufStr, "system")) { SYSTEMMAN; } else if(strEql(bufStr, "skip")) { SKIP; } else if(strEql(bufStr, "hi")) { SAYHI; } else if(strEql(bufStr, "files")) { FILEMAN; } else if(strEql(bufStr, "cat")) { CATFILE; } else if(strEql(bufStr,"execute")) { execute(); } else if(strEql(bufStr,"switch")) { SWITCHDIR; } else if(strEql(bufStr,"writer")) { WRITE; } else if(strEql(bufStr, "calc")) { CALCULATE; } else if(strEql(bufStr, "clear")) { clearScreen(); } else if(strEql(bufStr, "clear -i")) { BIGCLEAR; } else if(strEql(bufStr, "newdir")) { MKDIR; } else if(strEql(bufStr, "erase")) { RMFILE; } else if(strEql(bufStr, "me")) { ME; } else if(strEql(bufStr, "search")) { print("\nDictionary File Name> ", 0x0F); readStr(bufStr, bufSize); ASSERT(strlength(bufStr) < MAX_FNAME_LEN); findInDictionary(finddir_fs(fs_root, bufStr),1013,"ACCEPT"); } else { CMDNOTFOUND; } newline(); } }
void TouchScreenController::init(){ _tft->init(); //init TFT library clearScreen(); }
/******************************************************\ * Description: Determines the screen size of the the * * terminal and prompts for the user to * * change the screen. * \******************************************************/ RETSIGTYPE checkScreenSize(int sig) { int count; /* Avoid unused variable warning */ UNUSED(sig); clearScreen(windows); endwin(); init_screen(); /* init visuals */ slk_clear(); /* init menu bar */ slk_restore(); /* restore bottom menu*/ slk_noutrefresh(); doupdate(); /* recacl these values*/ BASE = (COLS - 6 - MIN_ADDR_LENGTH) / 4; /*base for the number */ hex_outline_width = (BASE * 3) + 3 + MIN_ADDR_LENGTH; MAXY = LINES - 3; hex_win_width = BASE * 3; ascii_outline_width = BASE + 2; ascii_win_width = BASE; maxlines = maxLines((fpIN != NULL) ? maxLoc(fpIN) : 0); currentLine = 0; SIZE_CH = TRUE; /* check for term size*/ if ((COLS < MIN_COLS) || (LINES < MIN_LINES)) { /* endwin(); printf("\n\n\n\nscreen size too small\n"); exit(0); */ init_fkeys(); /* define menu bar */ init_menu(windows); /* init windows */ clearScreen(windows); slk_clear(); mvwprintw(windows->hex, 0, 0, "Your screen is too small"); /*mvwprintw(windows->hex, 1, 2, "Resize it to continue");*/ refreshall(windows); doupdate(); } else { init_fkeys(); /* define menu bar */ init_menu(windows); /* init windows */ wmove(windows->hex,0,0); if (fpIN) /* if a file is open */ { for (count = 0; count <= MAXY && count <= maxLines(maxLoc(fpIN)); count++) outline(fpIN, count); mvwprintw(windows->cur_address, 0, 0, "%0*d", MIN_ADDR_LENGTH, 0); wmove(windows->hex,0,0); } refreshall(windows); wnoutrefresh(windows->cur_address); /* this next refresh is to put the cursor in the correct window */ wnoutrefresh(windows->hex); doupdate(); } }
void launchShell() { //allocate some memory for command string buffer. 1kB should be enough for now const int bufSize = 128; char bufStr[bufSize]; while (true) { print("\nQ-Kernel> ", 0x08); typingCmd = true; newCmd = true; readStr(bufStr, bufSize); typingCmd = false; if (strEql(strTrim(bufStr), "")) { print(COMMAND_HELP, 0x0F); } else if(strEql(bufStr, "help")) { kbHelp(); println(PRO_TIP, 0x0F); print(COMMAND_HELP, 0x0F); } else if(strEql(bufStr, "reboot")) { //reboots the computer reboot(); } else if(strEql(bufStr, "skip")) { // It literally does nothing... (Useful at callback) } else if(strEql(bufStr, "hi")) { print("\nHello!", 0x3F); } else if(strEql(bufStr, "files")) { newline(); listTree(); } else if(strEql(bufStr, "cat")) { print("\nFile Name> ", 0x0F); readStr(bufStr, bufSize); ASSERT(strlength(bufStr) < MAX_FNAME_LEN); catFile(finddir_fs(fs_root, bufStr)); } else if(strEql(bufStr,"execute")) { execute(); } else if(strEql(bufStr,"switch")) { print("\nThe specified directory was not found ", 0x0F); } else if(strEql(bufStr,"writer")) { writer(); } else if(strEql(bufStr, "writer -h")) { writerHelp(); } else if(strEql(bufStr, "calc")){ calc(); } else if(strEql(bufStr, "calc -h")){ calcHelp(); } else if(strEql(bufStr, "clear")) { clearScreen(); cursorX = 0; cursorY = 0; updateCursor(); } else if(strEql(bufStr, "clear -i")) { clearScreen(); printIntro(); } else if(strEql(bufStr, "newdir")) { print("\nReserved", 0x0F); } else if(strEql(bufStr, "erase")) { print("\nReserved", 0x0F); } else { print("\nCommand Not Found ", 0x0F); } newline(); } }
void start() { int count=1; int ok=0; Image *start; int time=20;//29 while(time--) { clearScreen(); switch(count) { case 1: start= read_image("start1.pixel","start1.color"); break; case 2: start= read_image("start2.pixel","start2.color"); break; case 3: start= read_image("start3.pixel","start3.color"); break; case 4: start= read_image("start4.pixel","start4.color"); break; case 5: start= read_image("start5.pixel","start5.color"); break; case 6: start= read_image("start6.pixel","start6.color"); break; case 7: start= read_image("start7.pixel","start7.color"); break; case 8: start= read_image("start8.pixel","start8.color"); break; case 9: start= read_image("start9.pixel","start9.color"); break; case 10: start= read_image("start10.pixel","start10.color"); break; case 11: start= read_image("start11.pixel","start11.color"); break; case 12: start= read_image("start12.pixel","start12.color"); break; case 13: start= read_image("start13.pixel","start13.color"); break; case 14: start= read_image("start14.pixel","start14.color"); break; case 15: start= read_image("start15.pixel","start15.color"); break; case 16: start= read_image("start16.pixel","start16.color"); break; default: break; } if(count==16) { ok=1; } if(ok) { // count=(count+1)%16+10; if(count==15) { count=16; } else { count=15; } } else { count++; } show_image(start,125,35); drawCmdWindow(); int i=0; for(i=0; i<1; i++) { playAudio(&audio[0]); //Sleep(500); } Sleep(500); } destroy_image(start); }