int main (int argc, char** argv) { int pitch; float length; char buf[16]; seq_opened = 0; if (argc > 1) seq_client = atoi(argv[1]); seq_open(); while (fgets(buf, 16, stdin) != NULL) { if (sscanf (buf, "%d %f", &pitch, &length)) { /* a single short note */ if (length <= 0) { if ((pitch > 0) && (pitch == (pitch % 128))) { //seq_open(); play_note (pitch, 0.1); //seq_close(); } } else { //seq_open(); if ((pitch > 0) && (pitch == (pitch % 128))) play_note (pitch, length); else play_rest (length); } } } seq_close(); return 0; }
static void button_readState() { /* middle button - pause */ int button_press; int button_release; button_press = get_single_debounced_button_press(ANY_BUTTON); button_release = get_single_debounced_button_release(ANY_BUTTON); switch (g_middle_button.state) { case BUTTON_STATE_RELEASED: if (button_press & MIDDLE_BUTTON) { g_middle_button.state = BUTTON_STATE_PRESSED; if (g_motor_state.enabled) { g_motor_state.enabled = false; g_motor_state.direction = DIRECTION_FORWARD; play_note(A(5), 200, 12); } else { g_motor_state.enabled = true; play_note(A(5), 200, 12); } } break; case BUTTON_STATE_PRESSED: if (button_release & MIDDLE_BUTTON) { g_middle_button.state = BUTTON_STATE_RELEASED; } break; } /* bottom button - speed down */ switch (g_bottom_button.state) { case BUTTON_STATE_RELEASED: if (button_press & BOTTOM_BUTTON) { g_bottom_button.state = BUTTON_STATE_PRESSED; g_motor_state.speed = MIN(g_motor_state.speed + 5, 255); } break; case BUTTON_STATE_PRESSED: if (button_release & BOTTOM_BUTTON) { g_bottom_button.state = BUTTON_STATE_RELEASED; } break; } /* top button - speed up */ switch (g_top_button.state) { case BUTTON_STATE_RELEASED: if (button_press & TOP_BUTTON) { g_top_button.state = BUTTON_STATE_PRESSED; g_motor_state.speed = MAX(g_motor_state.speed - 5, 0); } break; case BUTTON_STATE_PRESSED: if (button_release & TOP_BUTTON) { g_top_button.state = BUTTON_STATE_RELEASED; } break; } }
void handler_func(){ /*мелодия играет 1 раз*/ if(!melody_played){ melody_counter++; if(!melody_started){ if(melody_counter>=ticks_in_ms(ring_interval)){ melody_started=true; melody_counter-=ticks_in_ms(ring_interval); /*если звучит тик, нужно его выключить*/ if(tick_started){ tick_started=false; } note_index=0; play_note(); } } else { /*нота закончила звучать*/ if(melody_counter>=ticks_in_ms(notes[note_index].duration)){ melody_counter-=ticks_in_ms(notes[note_index].duration); note_index++; if(note_index==num_notes){ stop_sound(); melody_started=false; melody_played=true; } else { play_note(); } } } } /*даже если мелодия начала играть, тики все равно отсчитываются, но не звучат*/ tick_counter++; if(tick_started){ if(tick_counter>=ticks_in_ms(tick_duration)){ tick_started=false; tick_counter-=ticks_in_ms(tick_duration); if(!melody_started){ stop_sound(); } } } else { uint16_t actual_interval=tick_interval; if(tick_occured){ actual_interval-=tick_duration; } if(tick_counter>=ticks_in_ms(actual_interval)){ tick_counter-=ticks_in_ms(actual_interval); if(!melody_started){ tick_started=tick_occured=true; play_sound(TICK_FREQ); } } } }
void loop() // run over and over again { // wait here for one of the three buttons to be pushed unsigned char button = wait_for_button(ANY_BUTTON); clear(); if (button == TOP_BUTTON) { play_from_program_space(fugue); print("Fugue!"); lcd_goto_xy(0, 1); print("flash ->"); } if (button == MIDDLE_BUTTON) { play("! V8 cdefgab>cbagfedc"); print("C Major"); lcd_goto_xy(0, 1); print("RAM ->"); } if (button == BOTTOM_BUTTON) { if (is_playing()) { stop_playing(); print("stopped"); } else { play_note(A(5), 200, 15); print("note A5"); } } }
static void play_note(int i, int freq, int vol) { if (!getflag(F_sound_on)) vol = 0; else if (vol && opt.soundemu == SOUND_EMU_PC) vol = 160; chn[i].phase = 0; chn[i].freq = freq; chn[i].vol = vol; chn[i].env = 0x10000; chn[i].adsr = AGI_SOUND_ENV_ATTACK; #ifdef USE_CHORUS /* Add chorus ;) */ if (chn[i].type == AGI_SOUND_4CHN && opt.soundemu == SOUND_EMU_NONE && i < 3) { int newfreq = freq * 1007 / 1000; if (freq == newfreq) newfreq++; play_note(i + 4, newfreq, vol * 2 / 3); } #endif #ifdef __TURBOC__ if (i == 0) sound(freq); #endif }
int main(int argc, char *argv[]) { ao_device *device; ao_sample_format fmt; double duration = NOTE_LENGTH; float octave_mult = 1.0f; if (argc == 2); // do nothing else if (argc == 3) { sscanf(argv[2], "%lf", &duration); if (duration < 0) { printf("Note length can't be negative!\n"); return 1; } } else { printf("Usage: %s notes [length]\n", argv[0]); return 3; } fmt.bits = 16; fmt.rate = SAMPLE_RATE; fmt.channels = 1; fmt.byte_format = AO_FMT_NATIVE; fmt.matrix = NULL; ao_initialize(); device = ao_open_live(ao_default_driver_id(), &fmt, NULL); if (!device) { printf("Error %d opening audio device!\n", errno); return 2; } int i; for (i=0; i<strlen(argv[1]); i++) { char ch = argv[1][i]; char capital; switch (ch) { case '-': octave_mult *= 0.5f; break; case '+': octave_mult *= 2.0f; break; default: capital = ('A' <= ch && ch <= 'G'); if (capital) octave_mult *= 2.0f; play_note(device, tofreq(ch) * octave_mult, duration); if (capital) octave_mult *= 0.5f; break; //not needed, but good practice } } ao_close(device); ao_shutdown(); return 0; }
void keyboard_disable(void) { ps2_disable(); play_note(6, "b", 4, 100); keyboard_mode = KEYBOARD_DISABLED; uart_putchar('\n'); }
void play_file(FILE * infp, FILE * outfp) { struct note note; int linenum = 0, n; const size_t bufsiz = 1024; char buf[bufsiz]; char *s, *p; while (fgets(buf, bufsiz, infp) != NULL) { ++linenum; s = skip_space(buf); if (*s == '\0') { if (dflag) printf("BLANK LINE\n"); continue; } if (*s == '#') { if (dflag) printf("COMMENT\n"); continue; } if (starts_with(buf, "octave")) { if ((p = strchr(s, ' ')) == NULL && (p = strchr(s, '\t')) == NULL) { syntax_error(linenum, "'octave' directive with no operand"); exit(1); } else { octave = atoi(p); if (!IS_VALID_OCTAVE(octave)) { syntax_error(linenum, "octave must be between %i and %i", MIN_OCTAVE, MAX_OCTAVE); exit(1); } if (dflag) printf("OCTAVE: %i\n", octave); } continue; } if (starts_with(buf, "baseoctave")) { if ((p = strchr(s, ' ')) == NULL && (p = strchr(s, '\t')) == NULL) { syntax_error(linenum, "'baseoctave' directive with no operand"); exit(1); } else { baseoctave = atoi(p); if (dflag) printf("BASEOCTAVE: %i\n", baseoctave); } continue; } note = read_note(s, linenum); if (outfp) fwrite(¬e, sizeof(struct note), 1, outfp); else play_note(note); } }
void click(uint16_t freq, uint16_t duration){ #ifdef AUDIO_ENABLE if(freq >= 100 && freq <= 20000 && duration < 100){ play_note(freq, 10); for (uint16_t i = 0; i < duration; i++){ _delay_ms(1); } stop_all_notes(); } #endif }
void process_action_user(keyrecord_t *record) { if (IS_LAYER_ON(_MUSIC)) { if (record->event.pressed) { play_note(((double)220.0)*pow(2.0, -4.0)*pow(2.0,(starting_note + SCALE[record->event.key.col + offset])/12.0+(MATRIX_ROWS - record->event.key.row)), 0xF); } else { stop_note(((double)220.0)*pow(2.0, -4.0)*pow(2.0,(starting_note + SCALE[record->event.key.col + offset])/12.0+(MATRIX_ROWS - record->event.key.row))); } } }
void play_song(Song *s) { int i; for(i=0; i < s->lenght; i++) { play_note(&(s->notes[i])); printf("FAZ\n"); mili_sleep(s->pause); } }
int main(int argc, char** argv) { fftw_real out[N], in[N]; rfftw_plan plan_backward; buffer_t buffer[N]; int i, time = 0; song_t* head; song_t* next; print_prologoue(N, SR); next = head = read_song("song.txt"); dump_song(head); plan_backward = rfftw_create_plan(N, FFTW_COMPLEX_TO_REAL, FFTW_ESTIMATE); while ( next ) { // clear out for ( i = 0; i < N; i++ ) out[i] = 0.0f; i = 0; while (i < ACCORD_SIZE && next->accord[i] != 0) play_note(next->accord[i++], ADSR(time, next->duration), out); rfftw_one(plan_backward, out, in); for ( i = 0; i < N; i++ ) buffer[i] = limit_output(in[i]);; write(1, buffer, N* sizeof(buffer_t)); time ++; if ( time == next->duration ) { // play next note next = next->next; time = 0; // loop: if (next == NULL) next = head; } } rfftw_destroy_plan(plan_backward); free_song(head); print_epilogue(); return 0; }
void matrix_scan_user(void) { #ifdef AUDIO_ENABLE if (muse_mode) { if (muse_counter == 0) { uint8_t muse_note = muse_offset + SCALE[muse_clock_pulse()]; if (muse_note != last_muse_note) { stop_note(compute_freq_for_midi_note(last_muse_note)); play_note(compute_freq_for_midi_note(muse_note), 0xF); last_muse_note = muse_note; } } muse_counter = (muse_counter + 1) % muse_tempo; } #endif }
//The interface function to the playing part of the program. //Input: // fp: file descriptor for the sound device // freqs, containing (int)frequency*1000 of the notes you want //to play. // duration, containing the duration of the note in ms. // num_els, total number of elements in freqs and duration arrays. //Some integers in freqs are special codes for more advanced commands: //-1: Play pause with the corresponding length in duration-array. // void play_sequence(int fp, int freqs[], double duration[], int num_els) { int i; int duration_int; for (i=0; i<num_els; i++) { duration_int = (int)duration[i]; if (freqs[i] == -1) { play_pause(duration_int); } else { play_note(fp, freqs[i], duration_int); } } }
int main() // run once, when the sketch starts { currentIdx = 0; print("Music!"); while(1) // run over and over again { // if we haven't finished playing the song and // the buzzer is ready for the next note, play the next note if (currentIdx < MELODY_LENGTH && !is_playing()) { // play note at max volume play_note(note[currentIdx], duration[currentIdx], 15); // optional LCD feedback (for fun) lcd_goto_xy(0, 1); // go to start of the second LCD line if(note[currentIdx] != 255) // display blank for rests print_long(note[currentIdx]); // print integer value of the current note print(" "); // overwrite any left over characters currentIdx++; } // Insert some other useful code here... // the melody will play normally while the rest of your code executes // as long as it executes quickly enough to keep from inserting delays // between the notes. // For example, let the top user pushbutton function as a stop/reset melody button if (button_is_pressed(TOP_BUTTON)) { stop_playing(); // silence the buzzer if (currentIdx < MELODY_LENGTH) currentIdx = MELODY_LENGTH; // terminate the melody else currentIdx = 0; // restart the melody wait_for_button_release(TOP_BUTTON); // wait here for the button to be released } } }
/* Format: <Note><Octave><Duration> Note: C, Db, D, ... Octave: [1..8] Duration: 1, 2, 4, ... - semibreve, half, quarter, ... */ void play_token(const char *tok, int len, WaveFile *wav) { tnote note; int octave; float duration; note = parse_note(tok[0]); octave = tok[1] - '0'; if (tok[1] == 'b') { --note; octave = tok[2] - '0'; duration = (float)(tok[3] - '0'); } else if (tok[1] == '#') { ++note; octave = tok[2] - '0'; duration = (float)(tok[3] - '0'); } else duration = (float)(tok[2] - '0'); duration = 1.0 / duration; // fprintf(stderr, "Note: %d; Octave: %d; Duration: %f\n", note, octave, duration); play_note(note, octave, duration, wav); }
int main() { lcd_init_printf(); clear(); // clear the LCD printf("Time: "); while (1) { unsigned char button = get_single_debounced_button_press(ANY_BUTTON); switch (button) { case BUTTON_A: play_note(A(4), 50, 10); break; case BUTTON_B: play_note(B(4), 50, 10); break; case BUTTON_C: play_note(C(5), 50, 10); } button = get_single_debounced_button_release(ANY_BUTTON); switch (button) { case BUTTON_A: play_note(A(5), 50, 10); break; case BUTTON_B: play_note(B(5), 50, 10); break; case BUTTON_C: play_note(C(6), 50, 10); } unsigned long ms = get_ms(); // get elapsed milliseconds // convert to the current time in minutes, seconds, and hundredths of seconds unsigned char centiseconds = (ms / 10) % 100; unsigned char seconds = (ms / 1000) % 60; unsigned char minutes = (ms / 60000) % 60; lcd_goto_xy(0, 1); // go to the start of the second LCD row // print as [m]m:ss.cc (m = minute, s = second, c = hundredth of second) printf("%2u:%02u.%02u", minutes, seconds, centiseconds); } }
void action_function(keyrecord_t *record, uint8_t id, uint8_t opt) { if (id != 0) { if (record->event.pressed) { midi_send_noteon(&midi_device, opt, (id & 0xFF), 127); } else { midi_send_noteoff(&midi_device, opt, (id & 0xFF), 127); } } if (record->event.key.col == (MATRIX_COLS - 1) && record->event.key.row == (MATRIX_ROWS - 1)) { if (record->event.pressed) { starting_note++; play_note(((double)261.626)*pow(2.0, -1.0)*pow(2.0,(starting_note + SCALE[0 + offset])/12.0+(MATRIX_ROWS - 1)), 0xC); midi_send_cc(&midi_device, 0, 0x7B, 0); midi_send_cc(&midi_device, 1, 0x7B, 0); midi_send_cc(&midi_device, 2, 0x7B, 0); midi_send_cc(&midi_device, 3, 0x7B, 0); midi_send_cc(&midi_device, 4, 0x7B, 0); return; } else { stop_note(((double)261.626)*pow(2.0, -1.0)*pow(2.0,(starting_note + SCALE[0 + offset])/12.0+(MATRIX_ROWS - 1))); stop_all_notes(); return; } } if (record->event.key.col == (MATRIX_COLS - 2) && record->event.key.row == (MATRIX_ROWS - 1)) { if (record->event.pressed) { starting_note--; play_note(((double)261.626)*pow(2.0, -1.0)*pow(2.0,(starting_note + SCALE[0 + offset])/12.0+(MATRIX_ROWS - 1)), 0xC); midi_send_cc(&midi_device, 0, 0x7B, 0); midi_send_cc(&midi_device, 1, 0x7B, 0); midi_send_cc(&midi_device, 2, 0x7B, 0); midi_send_cc(&midi_device, 3, 0x7B, 0); midi_send_cc(&midi_device, 4, 0x7B, 0); return; } else { stop_note(((double)261.626)*pow(2.0, -1.0)*pow(2.0,(starting_note + SCALE[0 + offset])/12.0+(MATRIX_ROWS - 1))); stop_all_notes(); return; } } if (record->event.key.col == (MATRIX_COLS - 3) && record->event.key.row == (MATRIX_ROWS - 1) && record->event.pressed) { offset++; midi_send_cc(&midi_device, 0, 0x7B, 0); midi_send_cc(&midi_device, 1, 0x7B, 0); midi_send_cc(&midi_device, 2, 0x7B, 0); midi_send_cc(&midi_device, 3, 0x7B, 0); midi_send_cc(&midi_device, 4, 0x7B, 0); stop_all_notes(); for (int i = 0; i <= 7; i++) { play_note(((double)261.626)*pow(2.0, -1.0)*pow(2.0,(starting_note + SCALE[i + offset])/12.0+(MATRIX_ROWS - 1)), 0xC); _delay_us(80000); stop_note(((double)261.626)*pow(2.0, -1.0)*pow(2.0,(starting_note + SCALE[i + offset])/12.0+(MATRIX_ROWS - 1))); _delay_us(8000); } return; } if (record->event.key.col == (MATRIX_COLS - 4) && record->event.key.row == (MATRIX_ROWS - 1) && record->event.pressed) { offset--; midi_send_cc(&midi_device, 0, 0x7B, 0); midi_send_cc(&midi_device, 1, 0x7B, 0); midi_send_cc(&midi_device, 2, 0x7B, 0); midi_send_cc(&midi_device, 3, 0x7B, 0); midi_send_cc(&midi_device, 4, 0x7B, 0); stop_all_notes(); for (int i = 0; i <= 7; i++) { play_note(((double)261.626)*pow(2.0, -1.0)*pow(2.0,(starting_note + SCALE[i + offset])/12.0+(MATRIX_ROWS - 1)), 0xC); _delay_us(80000); stop_note(((double)261.626)*pow(2.0, -1.0)*pow(2.0,(starting_note + SCALE[i + offset])/12.0+(MATRIX_ROWS - 1))); _delay_us(8000); } return; } if (record->event.pressed) { // midi_send_noteon(&midi_device, record->event.key.row, starting_note + SCALE[record->event.key.col], 127); midi_send_noteon(&midi_device, 0, (starting_note + SCALE[record->event.key.col + offset])+12*(MATRIX_ROWS - record->event.key.row), 127); play_note(((double)261.626)*pow(2.0, -1.0)*pow(2.0,(starting_note + SCALE[record->event.key.col + offset])/12.0+(MATRIX_ROWS - record->event.key.row)), 0xF); } else { // midi_send_noteoff(&midi_device, record->event.key.row, starting_note + SCALE[record->event.key.col], 127); midi_send_noteoff(&midi_device, 0, (starting_note + SCALE[record->event.key.col + offset])+12*(MATRIX_ROWS - record->event.key.row), 127); stop_note(((double)261.626)*pow(2.0, -1.0)*pow(2.0,(starting_note + SCALE[record->event.key.col + offset])/12.0+(MATRIX_ROWS - record->event.key.row))); } }
void main () { UBYTE keys; UBYTE pos, old_pos = 0; UBYTE note, old_note = 0; UBYTE relative_octave = 0; UBYTE absolute_octave; UBYTE waveform = pulse_50; UBYTE mode = 0; UBYTE root = C; SCALE scale[8]; font_t big_font, small_font; font_init (); big_font = font_load (font_ibm); small_font = font_load (font_spect); font_set (big_font); printf (";; Boueux v%s\n", BOUEUX_VERSION); INIT_SOUND; MASTER_VOLUME = OFF; update_waveform (waveform); MASTER_VOLUME = HIGH; build_scale_mode (scale, root, mode); for (;;) { keys = joypad (); pos = scale_position (keys); if (pos) { note = scale[pos - 1] + relative_octave*OCTAVE_LEN; /* Raise by perfect 4th */ if (PRESSED (B)) note += 5; /* a perfect fourth = 5 semitones */ /* Lower by semitone */ if (PRESSED (A)) note -= 1; } /* Change octave */ if (PRESSED (START)) { relative_octave = !relative_octave; printf ("\n;; rel octave +%d\n", relative_octave); WAIT_KEY_UP (START); } if (PRESSED (SELECT)) { /* Change mode */ if (PRESSED (RIGHT)) { mode = (mode + 1) % NUM_MODES; WAIT_KEY_UP (RIGHT); build_scale_mode (scale, root, mode); } /* Change waveform */ if (PRESSED (LEFT)) { WAIT_KEY_UP (LEFT); waveform = (waveform + 1) % NUM_WAVEFORMS; update_waveform (waveform); } /* Increment root note */ if (PRESSED (UP)) { WAIT_KEY_UP (UP); root = (root + 1) % OCTAVE_LEN; build_scale_mode (scale, root, mode); } /* Decrement root note */ if (PRESSED (DOWN)) { WAIT_KEY_UP (DOWN); if (root == 0) root = OCTAVE_LEN - 1; else root = (root - 1) % OCTAVE_LEN; build_scale_mode (scale, root, mode); } continue; } if ((note != old_note) || (pos != old_pos)) { if (pos) /* Note will be played */ { CH1_VOL = HIGH; CH2_VOL = HIGH; play_note (note, waveform); font_set (small_font); printf (note_names[note % OCTAVE_LEN]); absolute_octave = note/OCTAVE_LEN + 3; printf ("%d", absolute_octave); printf (" "); font_set (big_font); } else /* Stop note */ { CH1_VOL = OFF; CH2_VOL = OFF; printf (". "); } } if (waveform == wawa) wawa_update(); old_note = note; old_pos = pos; } }
int move_ball(Sprite *bola, Vector *vec_blocos) { //>>>>>>>>>>>>>>>>>>>>>> actualiza o bloco que simula a nave como um bloco para as colisões Bloco *nave_block = (Bloco*)get_back_element(vec_blocos); nave_block->sprite->x = nave_pos.x; nave_block->sprite->y = nave_pos.y; //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> infos speed = sqrt(bola->xspeed * bola->xspeed + bola->yspeed * bola->yspeed); drawIntAt(pontuation, SCORE_X_POS, SCORE_Y_POS, NUMBER_FOREGROUND_COLOR, COUNTER_BACKGROUND, CHAR_SCALE, VIDEO_BASE_ADDRESS, codepage); drawIntAt(speed , SPEED_X_POS, SPEED_Y_POS, NUMBER_FOREGROUND_COLOR, COUNTER_BACKGROUND, CHAR_SCALE, VIDEO_BASE_ADDRESS, codepage); drawIntAt(lives, LIFES_X_POS, LIFES_Y_POS, NUMBER_FOREGROUND_COLOR, COUNTER_BACKGROUND, CHAR_SCALE, VIDEO_BASE_ADDRESS, codepage); //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> colisão com as paredes Bool first_hit = true; //lado direito while ((bola->x + bola->width + COLLISION_DETECTION_OFFSET) > MAX_GAME_WINDOWS_X) { int new_xspeed = -abs(bola->xspeed); bola->xspeed = new_xspeed; animate_sprite(bola, VIDEO_BASE_ADDRESS); if (first_hit == true) play_note(&wall_hit); //mili_sleep(5000); } first_hit = true; //lado esquerdo while ((bola->x - COLLISION_DETECTION_OFFSET) < MIN_GAME_WINDOWS_X) { int new_xspeed = abs(bola->xspeed); bola->xspeed = new_xspeed; animate_sprite(bola, VIDEO_BASE_ADDRESS); if (first_hit == true) play_note(&wall_hit); //mili_sleep(5000); first_hit = false; } first_hit = true; //baixo while ((bola->y + bola->height + COLLISION_DETECTION_OFFSET) > MAX_GAME_WINDOWS_Y) { int new_yspeed = -abs(bola->yspeed); bola->yspeed = new_yspeed; animate_sprite(bola, VIDEO_BASE_ADDRESS); if (first_hit == true) play_note(&ground_hit); --lives; mili_sleep(10); delete_sprite(bola, VIDEO_BASE_ADDRESS); bola->x = (nave_pos.x + nave_parada->width / 2); bola->y = VRES * 0.82; bola->xspeed = 1; bola->yspeed = -2; first_hit = false; } first_hit = true; //cima while ((bola->y - COLLISION_DETECTION_OFFSET) < MIN_GAME_WINDOWS_Y) { int new_yspeed = abs(bola->yspeed); bola->yspeed = new_yspeed; animate_sprite(bola, VIDEO_BASE_ADDRESS); if (first_hit == true) play_note(&wall_hit); //mili_sleep(5000); first_hit = false; } //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Tipos de movimentos da bola para saber como calcular a colisao com os blocos unsigned int collision_type; if ((bola->xspeed >= 0) && (bola->yspeed <= 0)) collision_type = 0; if ((bola->xspeed <= 0) && (bola->yspeed < 0)) collision_type = 1; if ((bola->xspeed < 0) && (bola->yspeed >= 0)) collision_type = 2; if ((bola->xspeed > 0) && (bola->yspeed > 0)) collision_type = 3; //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Calcula se ocorre colisão unsigned int size_vec_blocos = sizeVector(vec_blocos); unsigned int i; switch(collision_type) { case 0: { // bola a mover-se para NE (nordeste) for (i = 0; i < size_vec_blocos; ++i) { Bloco* block = (Bloco*)elementAtVector(vec_blocos, i); //verifica se houve colisão (+-COLLISION_DETECTION_OFFSET para evitar sobreposição da bola com os blocos) if( (block->sprite->on_screen == true) && (abs(bola->x + bola->width) > (block->sprite->x - COLLISION_DETECTION_OFFSET)) && (abs(bola->x) < (block->sprite->x + block->sprite->width)) && (((bola->y + bola->height) > block->sprite->y)) && ((bola->y < (block->sprite->y + block->sprite->height + COLLISION_DETECTION_OFFSET))) ) { //determina o lado em que bateu a bola int dx = abs(bola->x + bola->width - block->sprite->x); int dy = abs(bola->y - (block->sprite->y + block->sprite->height)); //actualiza a velocidade da bola //Caso embata na nave considera apenas a parte da xpm que tem a nave if (block->nave == true) { if ((block->sprite->x < (block->sprite->width - NAVE_LEFT_OFFSET_IN_XPM - NAVE_RIGHT_OFFSET_IN_XPM)) //caso em que a nave esta do lado esquerdo || ((dx > NAVE_LEFT_OFFSET_IN_XPM) && (abs(block->sprite->x + block->sprite->width - bola->x) > NAVE_RIGHT_OFFSET_IN_XPM))) { if (dx > dy) { //bateu da parte de baixo do bloco int new_yspeed = -bola->yspeed; bola->yspeed = new_yspeed; } else { //bateu do lado esquerdo do bloco int new_xspeed = -bola->xspeed; bola->xspeed = new_xspeed; } play_note(&nave_hit); } } else { if (dx > dy) { //bateu da parte de baixo do bloco int new_yspeed = -bola->yspeed; bola->yspeed = new_yspeed; } else { //bateu do lado esquerdo do bloco int new_xspeed = -bola->xspeed; bola->xspeed = new_xspeed; } play_note(&block_hit); } animate_sprite(bola, VIDEO_BASE_ADDRESS); //apaga bloco se não for a nave if (block->nave == false) { //mili_sleep(5000); block->sprite->on_screen = false; delete_sprite(block->sprite, VIDEO_BASE_ADDRESS); //acrescenta à pontuação o valor do bloco pontuation += block->pontuation; //actualiza o numeros de blocos que já foram destruidos ++blocos_destruidos; } return 0; } } break; } case 1: { // bola a mover-se para NO (noroeste) for (i = 0; i < size_vec_blocos; ++i) { Bloco* block = (Bloco*)elementAtVector(vec_blocos, i); //verifica se houve colisão (+-COLLISION_DETECTION_OFFSET para evitar sobreposição da bola com os blocos) if( (block->sprite->on_screen == true) && (abs(bola->x + bola->width) > block->sprite->x) && (abs(bola->x) < (block->sprite->x + block->sprite->width + COLLISION_DETECTION_OFFSET)) && ((bola->y + bola->height) > block->sprite->y) && ((bola->y < (block->sprite->y + block->sprite->height + COLLISION_DETECTION_OFFSET))) ) { //determina o lado em que bateu a bola int dx = abs(block->sprite->x + block->sprite->width - bola->x); int dy = abs(block->sprite->y + block->sprite->height - bola->y); //actualiza a velocidade da bola //Caso embata na nave considera apenas a parte da xpm que tem a nave if (block->nave == true) { if ((block->sprite->x < (block->sprite->width - NAVE_LEFT_OFFSET_IN_XPM - NAVE_RIGHT_OFFSET_IN_XPM)) //caso em que a nave esta do lado esquerdo || ((dx > NAVE_RIGHT_OFFSET_IN_XPM) && (abs(bola->x + bola->width - block->sprite->x) > NAVE_LEFT_OFFSET_IN_XPM))) { if (dx > dy) { //bateu da parte de baixo do bloco int new_yspeed = -bola->yspeed; bola->yspeed = new_yspeed; } else { //bateu do lado direito do bloco int new_xspeed = -bola->xspeed; bola->xspeed = new_xspeed; } play_note(&nave_hit); } } else { if (dx > dy) { //bateu da parte de baixo do bloco int new_yspeed = -bola->yspeed; bola->yspeed = new_yspeed; } else { //bateu do lado direito do bloco int new_xspeed = -bola->xspeed; bola->xspeed = new_xspeed; } play_note(&block_hit); } animate_sprite(bola, VIDEO_BASE_ADDRESS); //apaga bloco se não for a nave if (block->nave == false) { //mili_sleep(5000); block->sprite->on_screen = false; delete_sprite(block->sprite, VIDEO_BASE_ADDRESS); //acrescenta à pontuação o valor do bloco pontuation += block->pontuation; //actualiza o numeros de blocos que já foram destruidos ++blocos_destruidos; } return 0; } } break; } case 2: { // bola a mover-se para SO (sudueste) for (i = 0; i < size_vec_blocos; ++i) { Bloco* block = (Bloco*)elementAtVector(vec_blocos, i); //verifica se houve colisão (+-COLLISION_DETECTION_OFFSET para evitar sobreposição da bola com os blocos) if( (block->sprite->on_screen == true) && (abs(bola->x + bola->width) > block->sprite->x) && (abs(bola->x) < (block->sprite->x + block->sprite->width + COLLISION_DETECTION_OFFSET)) && ((bola->y + bola->height) > (block->sprite->y - COLLISION_DETECTION_OFFSET)) && (bola->y < (block->sprite->y + block->sprite->height)) ) { //determina o lado em que bateu a bola int dx = abs(block->sprite->x + block->sprite->width - bola->x); int dy = abs(bola->y + bola->height - block->sprite->y); //actualiza a velocidade da bola //Caso embata na nave considera apenas a parte da xpm que tem a nave if (block->nave == true) { if ((block->sprite->x < (block->sprite->width - NAVE_LEFT_OFFSET_IN_XPM - NAVE_RIGHT_OFFSET_IN_XPM)) //caso em que a nave esta do lado esquerdo || ((dx > NAVE_RIGHT_OFFSET_IN_XPM) && (abs(bola->x + bola->width - block->sprite->x)) > NAVE_LEFT_OFFSET_IN_XPM)) { if (dx > dy) { //bateu da parte de cima do bloco int new_yspeed = -bola->yspeed; bola->yspeed = new_yspeed; } else { //bateu do lado direito do bloco int new_xspeed = -bola->xspeed; bola->xspeed = new_xspeed; } play_note(&nave_hit); } } else { if (dx > dy) { //bateu da parte de cima do bloco int new_yspeed = -bola->yspeed; bola->yspeed = new_yspeed; } else { //bateu do lado direito do bloco int new_xspeed = -bola->xspeed; bola->xspeed = new_xspeed; } play_note(&block_hit); } animate_sprite(bola, VIDEO_BASE_ADDRESS); //apaga bloco se não for a nave if (block->nave == false) { //mili_sleep(5000); block->sprite->on_screen = false; delete_sprite(block->sprite, VIDEO_BASE_ADDRESS); //acrescenta à pontuação o valor do bloco pontuation += block->pontuation; //actualiza o numeros de blocos que já foram destruidos ++blocos_destruidos; } return 0; } } break; } case 3: { // bola a mover-se para SE (sodeste) for (i = 0; i < size_vec_blocos; ++i) { Bloco* block = (Bloco*)elementAtVector(vec_blocos, i); //verifica se houve colisão (+-COLLISION_DETECTION_OFFSET para evitar sobreposição da bola com os blocos) if( (block->sprite->on_screen == true) && (abs(bola->x + bola->width) > (block->sprite->x - COLLISION_DETECTION_OFFSET)) && (abs(bola->x) < (block->sprite->x + block->sprite->width)) && ((bola->y + bola->height) > (block->sprite->y - COLLISION_DETECTION_OFFSET)) && (bola->y < (block->sprite->y + block->sprite->height)) ) { //determina o lado em que bateu a bola int dx = abs(bola->x + bola->width - block->sprite->x); int dy = abs(bola->y + bola->height - block->sprite->y); //actualiza a velocidade da bola if (block->nave == true) { if ((block->sprite->x < (block->sprite->width - NAVE_LEFT_OFFSET_IN_XPM - NAVE_RIGHT_OFFSET_IN_XPM)) //caso em que a nave esta do lado esquerdo || ((dx > NAVE_LEFT_OFFSET_IN_XPM) && (abs(block->sprite->x + block->sprite->width - bola->x)) > NAVE_RIGHT_OFFSET_IN_XPM)) { if (dx > dy) { //bateu da parte de cima do bloco int new_yspeed = -bola->yspeed; bola->yspeed = new_yspeed; } else { //bateu do lado esquerdo do bloco int new_xspeed = -bola->xspeed; bola->xspeed = new_xspeed; } play_note(&nave_hit); } } else { if (dx > dy) { //bateu da parte de cima do bloco int new_yspeed = -bola->yspeed; bola->yspeed = new_yspeed; } else { //bateu do lado esquerdo do bloco int new_xspeed = -bola->xspeed; bola->xspeed = new_xspeed; } play_note(&block_hit); } animate_sprite(bola, VIDEO_BASE_ADDRESS); //apaga bloco se não for a nave if (block->nave == false) { //mili_sleep(5000); block->sprite->on_screen = false; delete_sprite(block->sprite, VIDEO_BASE_ADDRESS); //acrescenta à pontuação o valor do bloco pontuation += block->pontuation; //actualiza o numeros de blocos que já foram destruidos ++blocos_destruidos; } return 0; } } break; } } animate_sprite(bola, VIDEO_BASE_ADDRESS); if (blocos_destruidos == (sizeVector(vec_blocos) - 1)) return 1; else if (lives < 0) return 2; else return 0; }
//return the value of perform_command if executed or "" if keypress is part of a two-key shortcut, or NULL toherwise gchar * process_key_event (GdkEventKey * event, gchar * perform_command ()) { keymap *the_keymap = Denemo.map; //g_debug("\n********\nCaps Lock %x?\n\n********\nShifted %x?\n", event->state&GDK_LOCK_MASK, event->state&GDK_SHIFT_MASK ); { gint state; state = (lock_mask (event->keyval) ^ event->state); if (state || ((event->keyval == GDK_Caps_Lock) || (event->keyval == GDK_Num_Lock))) set_cursor_for (state); // MUST LOOK AHEAD to state after keypress HERE CATCH modifiers and set the cursor for them..... } dnm_clean_event (event); if (isModifier (event)) return NULL; /* Look up the keystroke in the keymap and execute the appropriate * function */ static GString *prefix_store = NULL; if (!prefix_store) prefix_store = g_string_new (""); gint command_idx = lookup_command_for_keyevent (event); if ((prefix_store->len == 0) && (command_idx != -1)) { const gchar *command_name = lookup_name_from_idx (the_keymap, command_idx); if (command_name) { if (Denemo.prefs.learning) { gchar *name = dnm_accelerator_name (event->keyval, event->state); KeyStrokeShow (name, command_idx, TRUE); g_free (name); } if (Denemo.ScriptRecording) if (idx_has_callback (the_keymap, command_idx)) { append_scheme_call ((gchar *) command_name); } //g_debug("Single Key shortcut %s invokes %s\n", dnm_accelerator_name(event->keyval, event->state), command_name); return perform_command (command_name, event); } else { g_warning ("Error: action %i has no name", command_idx); return NULL; } } /* we create a store for the prefix char and look to see if it is populated when a keystroke is received. If it is populated, we try for the two-key combination, {???else we try for the single key, and if that fails populate the store. OR if it fails clear store}. If the two-key combination works we clear the store. If the two-key combination fails we try for the single key, if that succeeds we clear the store if it fails we set the store to the unresolved keystroke. */ gchar *ret = NULL; if (prefix_store->len) { gchar *name = dnm_accelerator_name (event->keyval, event->state); //g_debug("second key %s\n", name); g_string_append_printf (prefix_store, "%c%s", ',', name); command_idx = lookup_command_for_keybinding_name (Denemo.map, prefix_store->str); if (command_idx != -1) { const gchar *command_name = lookup_name_from_idx (the_keymap, command_idx); if (command_name) { if (Denemo.prefs.learning) { KeyStrokeShow (prefix_store->str, command_idx, FALSE); } if (Denemo.ScriptRecording) if (idx_has_callback (the_keymap, command_idx)) { append_scheme_call ((gchar *) command_name); } ret = perform_command (command_name, event); } } else { //Two key name was not a binding ret = NULL; write_status (Denemo.project); if ((Denemo.project->view != DENEMO_MENU_VIEW) || Denemo.prefs.learning) { Denemo.prefs.learning = TRUE; KeyStrokeDecline (prefix_store->str); } toggle_to_drawing_area (TRUE); //restore menus, in case the user is lost and needs to look up a keypress if (Denemo.project->view != DENEMO_MENU_VIEW) toggle_to_drawing_area (TRUE); } g_string_assign (prefix_store, ""); Denemo.continuations = NULL; return ret; } else { //no prefix stored gchar *name = dnm_accelerator_name (event->keyval, event->state); //FIXME free name if ((Denemo.continuations = (GList *) g_hash_table_lookup (Denemo.map->continuations_table, name))) { GList *g; GString *continuations = g_string_new (""); for (g = Denemo.continuations; g; g = g->next) g_string_append_printf (continuations, "%s%s", (gchar *) g->data, _(", or ")); g_string_printf (prefix_store, _( "Prefix Key %s, waiting for key %stype Esc to abort"), name, continuations->str); g_string_free (continuations, TRUE); if (Denemo.prefs.immediateplayback) play_note (DEFAULT_BACKEND, 0, 9, 61, 300, 127 * Denemo.project->movement->master_volume); //gtk_statusbar_pop (GTK_STATUSBAR (Denemo.statusbar), Denemo.status_context_id); gtk_label_set_text (GTK_LABEL (Denemo.statuslabel), prefix_store->str); g_string_assign (prefix_store, name); if (Denemo.prefs.learning) { KeyStrokeAwait (name); } return ""; //continuation available } else { if ((Denemo.project->view != DENEMO_MENU_VIEW) || Denemo.prefs.learning) { Denemo.prefs.learning = TRUE; KeyStrokeDecline (name); } toggle_to_drawing_area (TRUE); //restore menus, in case the user is lost and needs to look up a keypress if (Denemo.project->view != DENEMO_MENU_VIEW) toggle_to_drawing_area (TRUE); } return NULL; } return NULL; }
/* Play multiple sets of notes */ void play_song(uint8_t sz, uint8_t notes[20][3], uint8_t szs[20], uint8_t durations[20]) { for(i=0; i<sz;++i) { play_note(szs[i], notes[i], durations[i]); } }
/* take an action for the passed note. Enter/edit/check the score following the mode and keyboard state. */ static gint midiaction (gint notenum) { gboolean new_measure = Denemo.project->movement->cursoroffend; DenemoProject *gui = Denemo.project; if (gui == NULL) return TRUE; if (gui->movement == NULL) return TRUE; DenemoStaff *curstaffstruct = (DenemoStaff *) gui->movement->currentstaff->data; enharmonic enote, prevenote; gboolean have_previous; //g_print("midiaction Adding mask %x, Chord mask %x\n", (Denemo.keyboard_state & ADDING_MASK) , (Denemo.keyboard_state & CHORD_MASK)); notenum2enharmonic (notenum, &enote.mid_c_offset, &enote.enshift, &enote.octave); if (Denemo.project->movement->cursor_appending) have_previous = get_current (&prevenote); else have_previous = get_previous (&prevenote); if (!(Denemo.keyboard_state & CHECKING_MASK)) stage_undo (gui->movement, ACTION_STAGE_END); //undo is a queue so this is the end :) if ((gui->mode & INPUTEDIT) || (Denemo.keyboard_state & CHECKING_MASK)) { static gboolean beep = FALSE; gboolean is_tied = FALSE; gint measure = gui->movement->currentmeasurenum; if (Denemo.project->movement->currentobject) { DenemoObject *curObj = Denemo.project->movement->currentobject->data; if (curObj->type == CHORD) { do { curObj = Denemo.project->movement->currentobject->data; chord *thechord = (chord *) curObj->object; is_tied = (!Denemo.prefs.ignore_ties) && thechord->is_tied; //#define check_midi_note(a,b,c,d) ((a->mid_c_offset==b)&&(a->enshift==c))?playnote(a,curstaffstruct->midi_channel):gdk_beep(); if ((Denemo.keyboard_state & CHECKING_MASK) && thechord->notes) { //later - find note nearest cursor and note *thenote = (note *) thechord->notes->data; // check_midi_note(thenote, enote.mid_c_offset + 7 *(enote.octave), enote.enshift, enote.octave); if ((!curObj->isinvisible) && (thenote->mid_c_offset == (enote.mid_c_offset + 7 * (enote.octave))) && (thenote->enshift == enote.enshift)) { gint midi = dia_to_midinote (thenote->mid_c_offset) + thenote->enshift; play_note (DEFAULT_BACKEND, 0 /*port */ , curstaffstruct->midi_channel, midi, 300 /*duration */ , 0); } else { gdk_beep (); break; //do not move on to next note } } else { do_one_note (enote.mid_c_offset, enote.enshift, enote.octave); } if (Denemo.project->movement->cursor_appending) break; curObj = Denemo.project->movement->currentobject->data; thechord = (chord *) curObj->object; is_tied = (!Denemo.prefs.ignore_ties) && thechord->is_tied; } while ((!(Denemo.keyboard_state & ADDING_MASK)) && next_editable_note () && is_tied); } else //there is a current object that is not a chord { if (gui->movement->cursor_appending) { do_one_note (enote.mid_c_offset, enote.enshift, enote.octave); next_insert_or_editable_note(); //in some circumstance this fails to advance to the next editable note, the following checks for that. if (Denemo.project->movement->currentobject) { curObj = Denemo.project->movement->currentobject->data; if(!curObj->isinvisible) next_editable_note (); } } else gdk_beep (); } if (gui->mode & INPUTRHYTHM) { //g_print("measure was %d now %d with appending %d\n", measure, gui->movement->currentmeasurenum, gui->movement->cursor_appending); if (!beep && (measure != gui->movement->currentmeasurenum) && !gui->movement->cursor_appending) beep = TRUE; else if (beep) signal_measure_end (), beep = FALSE; } } else { // no current object do_one_note (enote.mid_c_offset, enote.enshift, enote.octave); next_insert_or_editable_note();//next_editable_note ();//if we have gone back from an empty measure we need this. } } else { // not INPUTEDIT action_note_into_score (enote.mid_c_offset, enote.enshift, enote.octave); } if (!(Denemo.keyboard_state & CHECKING_MASK)) { stage_undo (gui->movement, ACTION_STAGE_START); } draw_score_area(); //just for advancing the cursor. if (!(Denemo.keyboard_state & CHECKING_MASK)) { if (Denemo.prefs.immediateplayback) { gint channel = curstaffstruct->midi_channel; if (have_previous && check_interval (enote.mid_c_offset, enote.enshift, prevenote.mid_c_offset, prevenote.enshift)) channel = Denemo.prefs.pitchspellingchannel; play_note (DEFAULT_BACKEND, 0 /*port */ , channel, notenum, 300 /*duration */ , 0); if(new_measure) signal_measure_end(); } } return TRUE; }
/* Startup */ int main(void) { uint16_t i; /* port IO values */ DDRB = 0xFF; // portb(0..7) => r2r DDRD = 0x00; // portd(2..5) <= controller PORTB = 0x00; /* 16-bit timer setup */ TCCR1A = (1<<COM1A1); // reset timer-counter on trigger TCCR1B = 0; // disable for now TIMSK = (1<<OCIE1A); // use timer compare counter A /* Running state */ reset(); global_note = 0; /* Wait for MCU *///1000 for (i=0; i<(1000*20); i++) asm("nop"); // #if (DEBUG) global_note = 1; play_note(); #endif // /* run forever using interrupts */ sei(); while(1) { /* output testing */ #if DEBUG if (!plays_left) { cli(); global_note++; if (global_note == 9) global_note = 1; play_note(); sei(); } #endif /* Chip communication */ #if (!DEBUG) // wait for line high while(!(PORTD & PIN_WAIT)) { asm("nop"); } //debounce if (debounce_port(&PORTD, PIN_WAIT, 10)) { //pin change! cli(); //disable/enable notes if (PORTD & PIN_RUN) { //enable note if (!global_note) global_note = 1; play_note(); } else { //temporary stop if (!(PORTD & PIN_NEXT)) reset(); } //next note if (PORTD & PIN_NEXT) { if (global_note) global_note++; if (global_note == 9) global_note = 1; } //reset if (PORTD & PIN_RESET) { //perma-stop reset(); global_note = 0; } // sei(); } // wait for line low while(PORTD & PIN_WAIT) { asm("nop"); } #endif } while(1); return 0; }
void keyboard_read(int mode) { unsigned char c; int release; int extended; ps2_enable(); play_note(6, "a", 4, 100); release = 0; extended = 0; keyboard_mode = mode; memset(key_map, 0, NUM_KEYS); while(keyboard_mode) { while(((c = ps2_read_char()) == 0) && keyboard_mode) { ; } //scan code mode if(keyboard_mode == KEYBOARD_SCAN) { if(c == KEY_RELEASE) { release = 1; } else if(release) { key_map[c] = 0; release = 0; } else if(!key_map[c]) { key_map[c] = 1; } else { continue; } uart_printf("0x%.2X ", (unsigned int)c); } //typing mode else if(keyboard_mode == KEYBOARD_TYPE) { if(c == KEY_RELEASE) { release = 1; continue; } else if(c == KEY_EXTENDED) { extended = 1; continue; } //key release else if(release) { key_map[c] = 0; release = 0; } else { key_map[c] = 1; if(c == KEY_LSHIFT || c == KEY_RSHIFT) { continue; } else if(c == KEY_CTRL) { continue; } else if(c == KEY_ESCAPE) { break; } else { if(key_map[KEY_CTRL]) { uart_printf("ctl-"); } if(key_map[KEY_LSHIFT] || key_map[KEY_RSHIFT]) { uart_putchar(scancode_shift_map[c]); } else { uart_putchar(scancode_map[c]); } } } } } keyboard_disable(); }
int main(void) { unsigned char new_state, old_state; unsigned char a, b; int count = 0; // Count to display char count_str[30]; int note; // Initialize DDR and PORT registers and LCD DDRC &= ~(1<<1) | ~(1<<5); DDRB |= (1<<4); PORTC |= (1<<1) | (1<<5); lcd_init(); // Write a splash screen to the LCD lcd_writecommand(1); lcd_stringout("Melissa Ahn"); // Use lcd_moveto to start at an appropriate column //in the bottom row to appear centered lcd_moveto(1, 4); lcd_stringout("ee109 Lab7"); // Delay 1 second _delay_ms(1000); lcd_writecommand(1); // Read the A and B inputs to determine the initial state // Warning: Do NOT read A and B separately. You should read BOTH inputs // at the same time, then determine the A and B values from that value. lcd_moveto(0, 0); lcd_writedata(count); unsigned char temp = PORTC; b = temp & (1<< 5); a = temp & (1<< 1); if (!b && !a) old_state = 0; else if (!b && a) old_state = 1; else if (b && !a) old_state = 2; else old_state = 3; new_state = old_state; while (1) { /*unsigned char i; for (i = 0; i < 8; i++) { play_note(frequency[i]); _delay_ms(200); }*/ // Read the input bits and determine A and B temp = PINC; b = temp & (1<< 5); a = temp & (1<< 1); if (old_state == 0) { // Handle A and B inputs for state 0 if (!b && a) new_state = 1; else if (b && !a) new_state = 3; } else if (old_state == 1) { // Handle A and B inputs for state 1 if (b && a) new_state = 2; else if (!b && !a) new_state = 0; } else if (old_state == 2) { // Handle A and B inputs for state 2 if (b && !a) new_state = 3; else if (!b && a) new_state = 1; } else { // old_state = 3 // Handle A and B inputs for state 3 if (!b && !a) new_state = 0; else if (b && a) new_state = 2; } if (new_state != old_state) { // Did state change? // Output count to LCD if (new_state > old_state) count++; else count--; lcd_writecommand(1); snprintf(count_str, 30, "%03d", count); lcd_stringout(count_str); old_state = new_state; // Do we play a note? if ((count % 8) == 0) { // Determine which note (0-7) to play note = (abs(count) % 64) / 8; // Find the frequency of the note unsigned short freq = frequency[note]; // Call play_note and pass it the frequency play_note(freq); } } } }