Beispiel #1
0
NETHER::NETHER(char *mapname)
{

#ifdef _WRITE_REPORT_
	debug_fp=fopen("report.txt","w");
	fprintf(debug_fp,"Creating game...\n");
	fflush(debug_fp);
#endif

	if (shadows==1) {
		lightpos[0]=-1000;
		lightpos[1]=-3000;
		lightpos[2]=5000;
		lightpos[3]=1;
		lightposv.x=lightpos[0];
		lightposv.y=lightpos[1];
		lightposv.z=lightpos[2];
	} else {
		lightpos[0]=0;
		lightpos[1]=0;
		lightpos[2]=5000;
		lightpos[3]=1;
		lightposv.x=lightpos[0];
		lightposv.y=lightpos[1];
		lightposv.z=lightpos[2];
	} /* if */ 

#ifdef _WRITE_REPORT_
	fprintf(debug_fp,"loading objects...\n");
	fflush(debug_fp);
#endif

	loadobjects();
		
#ifdef _WRITE_REPORT_
	fprintf(debug_fp,"loading map...\n");
	fflush(debug_fp);
#endif

	/* Load map: */ 
	if (!loadmap(mapname)) {
		map_w=map_h=0;
		map=0;
	} /* if */ 

#ifdef _WRITE_REPORT_
	fprintf(debug_fp,"Initializing game variables...\n");
	fflush(debug_fp);
#endif

	/* Set camera: */ 
	viewp.x=map_w/2;
	viewp.y=0;
	camera.x=6;
	camera.y=-6;
	camera.z=11;
	zoom=1;

	/* Init game: */ 
	day=0;
	hour=0;
	minute=0;
	second=0;
	shipp.x=4.0;
	shipp.y=2.0;
	shipp.z=3.0;
	ship_op=OP_NONE;
	ship_op2=OP_NONE;
	ship_timemoving=0;

	resources[0][0]=20;
	resources[0][1]=0;
	resources[0][2]=0;
	resources[0][3]=0;
	resources[0][4]=0;
	resources[0][5]=0;
	resources[0][6]=0;
	resources[1][0]=20;
	resources[1][1]=0;
	resources[1][2]=0;
	resources[1][3]=0;
	resources[1][4]=0;
	resources[1][5]=0;
	resources[1][6]=0;
	statistics[0][0]=0;
	statistics[0][1]=0;
	statistics[0][2]=0;
	statistics[0][3]=0;
	statistics[0][4]=0;
	statistics[0][5]=0;
	statistics[0][6]=0;
	statistics[0][7]=0;
	statistics[1][0]=0;
	statistics[1][1]=0;
	statistics[1][2]=0;
	statistics[1][3]=0;
	statistics[1][4]=0;
	statistics[1][5]=0;
	statistics[1][6]=0;
	statistics[1][7]=0;
	recomputestatistics=true;

	game_state=STATE_PLAYING;
	animation_timer=0;
	construction_pointer=0;
	controlled=0;
	game_finished=0;
	game_started=INTRO_TIME;

#ifdef _WRITE_REPORT_
	fprintf(debug_fp,"Creating menus...\n");
	fflush(debug_fp);
#endif

	/* Init status: */ 
	newmenu(GENERAL_MENU);
	redrawmenu=2;
	redrawradar=1;

#ifdef _WRITE_REPORT_
	fprintf(debug_fp,"Initializing AI...\n");
	fflush(debug_fp);
#endif

	/* Init AI: */ 
	AI_precomputations();

#ifdef _WRITE_REPORT_
	fprintf(debug_fp,"Loading sounds...\n");
	fflush(debug_fp);
#endif

	/* Load sounds: */ 
	S_shot=Mix_LoadWAV("/usr/local/share/netherearth/sound/shot.wav");
	S_explosion=Mix_LoadWAV("/usr/local/share/netherearth/sound/explosion.wav");
	S_select=Mix_LoadWAV("/usr/local/share/netherearth/sound/select.wav");
	S_wrong=Mix_LoadWAV("/usr/local/share/netherearth/sound/wrong.wav");
	S_construction=Mix_LoadWAV("/usr/local/share/netherearth/sound/construction.wav");

#ifdef _WRITE_REPORT_
	fprintf(debug_fp,"Game created.\n");
	fflush(debug_fp);
#endif

} /* NETHER::NETHER */ 
Beispiel #2
0
void ItemDatabase::loadSounds() {

	sfx[SFX_BOOK] = Mix_LoadWAV((PATH_DATA + "soundfx/inventory/inventory_book.ogg").c_str());
	sfx[SFX_CLOTH] = Mix_LoadWAV((PATH_DATA + "soundfx/inventory/inventory_cloth.ogg").c_str());
	sfx[SFX_COINS] = Mix_LoadWAV((PATH_DATA + "soundfx/inventory/inventory_coins.ogg").c_str());
	sfx[SFX_GEM] = Mix_LoadWAV((PATH_DATA + "soundfx/inventory/inventory_gem.ogg").c_str());
	sfx[SFX_LEATHER] = Mix_LoadWAV((PATH_DATA + "soundfx/inventory/inventory_leather.ogg").c_str());
	sfx[SFX_METAL] = Mix_LoadWAV((PATH_DATA + "soundfx/inventory/inventory_metal.ogg").c_str());
	sfx[SFX_PAGE] = Mix_LoadWAV((PATH_DATA + "soundfx/inventory/inventory_page.ogg").c_str());
	sfx[SFX_MAILLE] = Mix_LoadWAV((PATH_DATA + "soundfx/inventory/inventory_maille.ogg").c_str());
	sfx[SFX_OBJECT] = Mix_LoadWAV((PATH_DATA + "soundfx/inventory/inventory_object.ogg").c_str());
	sfx[SFX_HEAVY] = Mix_LoadWAV((PATH_DATA + "soundfx/inventory/inventory_heavy.ogg").c_str());
	sfx[SFX_WOOD] = Mix_LoadWAV((PATH_DATA + "soundfx/inventory/inventory_wood.ogg").c_str());
	sfx[SFX_POTION] = Mix_LoadWAV((PATH_DATA + "soundfx/inventory/inventory_potion.ogg").c_str());
	
}
bool Vista::loadMedia() {
	/**Creo el dibujo del pasto**/

	vector<dibujo_t> pastos;
	for (int nroTextura = 1; nroTextura <= MAX_NRO_TEXTURA; nroTextura++) {

		Entidad* entidadPasto =
				this->modelo->juego->escenario->getTexturaDefault(nroTextura);
		this->factory->crear_dibujo_tile(entidadPasto->objetoMapa->imagen);
		dibujo_t pasto_id = this->factory->ultimo_dibujo();
		pastos.push_back(pasto_id);

		delete entidadPasto;

	}

	std::map<std::string, ObjetoMapa*>::iterator it;
	std::map<std::string, dibujo_t> hashDibujos;

	Configuracion* configuracion = this->modelo->juego->conf;
	for (it = modelo->juego->tipos.begin(); it != modelo->juego->tipos.end();
			it++) {
		ObjetoMapa* tipo = it->second;
		vector<int> v1d =
				{ tipo->pixelsReferencia->x, tipo->pixelsReferencia->y };
		if (tipo->fps == 0) {
			this->factory->crear_dibujo_estatico(tipo->imagen, v1d);
		} else if (tipo->delay != 0) {
			this->factory->crear_dibujo_animado(tipo->imagen, v1d, tipo->fps,
					tipo->delay);
		} else {
			this->factory->crear_dibujo_personaje(tipo->imagen, tipo->musica,MOVIMIENTOS, CANTIDAD_DE_IMAGENES, tipo->fps); //el ultimo parametro es velocidad
		}
		dibujo_t dibujo_id = this->factory->ultimo_dibujo();
		hashDibujos[tipo->nombre] = dibujo_id;
	}
	this->factory->setHashDibujos(hashDibujos);
	/**Dibujo el mapa**/
	int largo = this->modelo->get_alto_mapa();
	int ancho = this->modelo->get_ancho_mapa();
	vector<vector<dibujo_t>> filas(ancho, pastos);
	vector<vector<vector<dibujo_t>>> tiles(largo, filas);
	vector<dibujo_t> filas_escenario(ancho, 0);
	vector<vector<dibujo_t>> escenario(largo, filas_escenario);

	//***********DIBUJOS (ENTIDADES ESTATICAS Y DINAMICAS EN YAML)*****************
	for (unsigned i = 0; i < this->modelo->juego->escenario->entidades.size();
			i++) {
		Entidad* entidad = this->modelo->juego->escenario->entidades[i];
		escenario[entidad->posicion->getX()][entidad->posicion->getY()] =
				hashDibujos[entidad->objetoMapa->nombre];
	}
	modelo->setDibujoMapa(escenario, tiles); //MEZCLA VISTA CON MODELO

	this->barra->load(gRenderer, "font.ttf", this->ancho_por_celda(),
			this->altura_por_celda());
	musica_creacion = Mix_LoadWAV( "img/1elfos/CREACION.wav" );
	musicaLoading = Mix_LoadWAV( "img/extras/loading.wav" );
	music_ganador_elfo=Mix_LoadWAV( "img/1elfos/GANADOR.wav" );
	musica_ganador_hobbit=Mix_LoadWAV( "img/2hobbit/GANADOR.wav" );
	musica_ganador_humanos=Mix_LoadWAV( "img/3humanos/GANADOR.wav" );
	musica_ganador_mordor=Mix_LoadWAV( "img/4mordor/GANADOR.wav" );

	return true;
}
Beispiel #4
0
Mix_Chunk *ml_mix_load_clip(const char *path) {
  Mix_Chunk *ret = Mix_LoadWAV(path);
  return ret;
}
Beispiel #5
0
 void ParticleCache::addSound(string file) {
   fileSound = file;
   sound = Mix_LoadWAV(file.c_str());
 }
Beispiel #6
0
static Mix_Chunk *loadSound(char *filename)
{
	return Mix_LoadWAV(getFileLocation(filename));
}
Beispiel #7
0
bool TMASound::load(const char *filename)
{
    unload();
    psound = Mix_LoadWAV(filename);
    return (psound!=NULL);
}
Beispiel #8
0
{
    return INT2BOOL(Mix_Playing(NUM2INT(channel)));
}

static VALUE Mixer_s_playing_channels(VALUE mod)
{
    return INT2NUM(Mix_Playing(-1));
}

static VALUE Wave_s_load(VALUE class, VALUE filename)
{
    Mix_Chunk *chunk;

    ExportFilenameStringValue(filename);

    chunk = Mix_LoadWAV(RSTRING_PTR(filename));
    if( chunk == NULL ) {
        rb_raise(eSDLError, "Couldn't load wave file %s: %s",
                 RSTRING_PTR(filename), SDL_GetError());
    }
    return Wave_create(chunk);
}

static VALUE Wave_s_loadFromIO(VALUE class, VALUE io)
{
    Mix_Chunk *wave;
    wave = Mix_LoadWAV_RW(rubysdl_RWops_from_ruby_obj(io), 1);
    if( wave == NULL ) {
        rb_raise(eSDLError, "Couldn't load wave file from IO: %s",
                 Mix_GetError());
    }
Beispiel #9
0
int main(int argc, char *argv[])
{
    int audio_rate;
    Uint16 audio_format;
    int audio_channels;
    int loops = 0;
    int i;
    int reverse_stereo = 0;
    int reverse_sample = 0;

#ifdef HAVE_SETBUF
    setbuf(stdout, NULL);    /* rcg06132001 for debugging purposes. */
    setbuf(stderr, NULL);    /* rcg06192001 for debugging purposes, too. */
#endif
    output_test_warnings();

    /* Initialize variables */
    audio_rate = MIX_DEFAULT_FREQUENCY;
    audio_format = MIX_DEFAULT_FORMAT;
    audio_channels = 2;

    /* Check command line usage */
    for ( i=1; argv[i] && (*argv[i] == '-'); ++i ) {
        if ( (strcmp(argv[i], "-r") == 0) && argv[i+1] ) {
            ++i;
            audio_rate = atoi(argv[i]);
        } else if ( strcmp(argv[i], "-m") == 0 ) {
            audio_channels = 1;
        } else if ( (strcmp(argv[i], "-c") == 0) && argv[i+1] ) {
            ++i;
            audio_channels = atoi(argv[i]);
        } else if ( strcmp(argv[i], "-l") == 0 ) {
            loops = -1;
        } else if ( strcmp(argv[i], "-8") == 0 ) {
            audio_format = AUDIO_U8;
        } else if ( strcmp(argv[i], "-f") == 0 ) { /* rcg06122001 flip stereo */
            reverse_stereo = 1;
        } else if ( strcmp(argv[i], "-F") == 0 ) { /* rcg06172001 flip sample */
            reverse_sample = 1;
        } else {
            Usage(argv[0]);
            return(1);
        }
    }
    if ( ! argv[i] ) {
        Usage(argv[0]);
        return(1);
    }

    /* Initialize the SDL library */
    if ( SDL_Init(SDL_INIT_AUDIO) < 0 ) {
        fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError());
        return(255);
    }
#ifdef HAVE_SIGNAL_H
    signal(SIGINT, CleanUp);
    signal(SIGTERM, CleanUp);
#endif

    /* Open the audio device */
    if (Mix_OpenAudio(audio_rate, audio_format, audio_channels, 4096) < 0) {
        fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
        CleanUp(2);
    } else {
        Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels);
        printf("Opened audio at %d Hz %d bit %s", audio_rate,
               (audio_format&0xFF),
               (audio_channels > 2) ? "surround" :
               (audio_channels > 1) ? "stereo" : "mono");
        if ( loops ) {
            printf(" (looping)\n");
        } else {
            putchar('\n');
        }
    }
    audio_open = 1;

#if (defined TEST_MIX_VERSIONS)
    test_versions();
#endif

#if (defined TEST_MIX_DECODERS)
    report_decoders();
#endif

    /* Load the requested wave file */
    wave = Mix_LoadWAV(argv[i]);
    if ( wave == NULL ) {
        fprintf(stderr, "Couldn't load %s: %s\n",
                argv[i], SDL_GetError());
        CleanUp(2);
    }

    if (reverse_sample) {
        flip_sample(wave);
    }

#ifdef TEST_MIX_CHANNELFINISHED  /* rcg06072001 */
    Mix_ChannelFinished(channel_complete_callback);
#endif

    if ( (!Mix_SetReverseStereo(MIX_CHANNEL_POST, reverse_stereo)) &&
            (reverse_stereo) )
    {
        printf("Failed to set up reverse stereo effect!\n");
        printf("Reason: [%s].\n", Mix_GetError());
    }

    /* Play and then exit */
    Mix_PlayChannel(0, wave, loops);

    while (still_playing()) {

#if (defined TEST_MIX_PANNING)  /* rcg06132001 */
        do_panning_update();
#endif

#if (defined TEST_MIX_DISTANCE) /* rcg06192001 */
        do_distance_update();
#endif

#if (defined TEST_MIX_POSITION) /* rcg06202001 */
        do_position_update();
#endif

        SDL_Delay(1);

    } /* while still_playing() loop... */

    CleanUp(0);

    /* Not reached, but fixes compiler warnings */
    return 0;
}
Beispiel #10
0
int main(int argc, char *argv[])
{
	SDL_Init(SDL_INIT_VIDEO);
	displayWindow = SDL_CreateWindow("Final Project", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
	SDL_GL_MakeCurrent(displayWindow, context);
#ifdef _WINDOWS
	glewInit();
#endif

	ShaderProgram* program = new ShaderProgram(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl");

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	glViewport(0, 0, 640, 480);

	Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096);

	Matrix modelMatrix;
	Matrix textMatrix;
	Matrix viewMatrix;
	Matrix projectionMatrix;
	projectionMatrix.setOrthoProjection(-10.0f, 10.0f, -7.5f, 7.5f, -1.0f, 1.0f);
	
	std::vector<Entity> entities;

	int lastWinner;

	// Load player sprites
	GLint paddleBlue = LoadTextureClamp(RESOURCE_FOLDER"assets\\paddleBlu.png");
	GLint paddleRed = LoadTextureClamp(RESOURCE_FOLDER"assets\\paddleRed.png");
	// Load item sprites
	GLint coinCopperSprite = LoadTextureClamp(RESOURCE_FOLDER"assets\\coinCopper.png");
	GLint coinSilverSprite = LoadTextureClamp(RESOURCE_FOLDER"assets\\coinSilver.png");
	GLint coinGoldSprite = LoadTextureClamp(RESOURCE_FOLDER"assets\\coinGold.png");
	GLint coinPlatinumSprite = LoadTextureClamp(RESOURCE_FOLDER"assets\\coinPlatinum.png");
	GLint starCopperSprite = LoadTextureClamp(RESOURCE_FOLDER"assets\\starCopper.png");
	GLint starSilverSprite = LoadTextureClamp(RESOURCE_FOLDER"assets\\starSilver.png");
	GLint starGoldSprite = LoadTextureClamp(RESOURCE_FOLDER"assets\\starGold.png");
	GLint starPlatinumSprite = LoadTextureClamp(RESOURCE_FOLDER"assets\\starPlatinum.png");
	// Load font
	GLuint fontSheet = LoadTextureClamp(RESOURCE_FOLDER"assets\\font1.png");
	// Load level bg
	GLint mainBG = LoadTextureRepeat(RESOURCE_FOLDER"assets\\bg_main.png");
	GLint levelBG = LoadTextureRepeat(RESOURCE_FOLDER"assets\\bg_level.png");
	GLint overBG = LoadTextureRepeat(RESOURCE_FOLDER"assets\\bg_over.png");

	// Load music
	Mix_Music *music1;
	music1 = Mix_LoadMUS(RESOURCE_FOLDER"assets\\Im Free.mp3");
	Mix_Music *music2;
	music2 = Mix_LoadMUS(RESOURCE_FOLDER"assets\\Lagrima.mp3");
	Mix_Music *music3;
	music3 = Mix_LoadMUS(RESOURCE_FOLDER"assets\\The Old Song.mp3");
	Mix_Music *music4;
	music4 = Mix_LoadMUS(RESOURCE_FOLDER"assets\\FASE.mp3");
	// Load sounds
	Mix_Chunk* itemHit;
	itemHit = Mix_LoadWAV(RESOURCE_FOLDER"hit.wav");
	Mix_Chunk* buttonPress;
	buttonPress = Mix_LoadWAV(RESOURCE_FOLDER"Menu Selection Click.wav");


	// Initialize players
	Entity playerBlue(ENTITY_PLAYER, paddleBlue, fontSheet, SDL_SCANCODE_A, SDL_SCANCODE_D, -5.0f);
	Entity playerRed(ENTITY_PLAYER, paddleRed, fontSheet, SDL_SCANCODE_LEFT, SDL_SCANCODE_RIGHT, 5.0f);

	Entity coinCopper(ENTITY_ITEM, coinCopperSprite, fontSheet, 10, buttonPress);
	Entity coinSilver(ENTITY_ITEM, coinSilverSprite, fontSheet, 25, buttonPress);
	Entity coinGold(ENTITY_ITEM, coinGoldSprite, fontSheet, 50, buttonPress);
	Entity coinPlatinum(ENTITY_ITEM, coinPlatinumSprite, fontSheet, 100, buttonPress);
	Entity starCopper(ENTITY_ITEM, starCopperSprite, fontSheet, 100, buttonPress);
	Entity starSilver(ENTITY_ITEM, starSilverSprite, fontSheet, 250, buttonPress);
	Entity starGold(ENTITY_ITEM, starGoldSprite, fontSheet, 500, buttonPress);
	Entity starPlatinum(ENTITY_ITEM, starPlatinumSprite, fontSheet, 1000, buttonPress);

	entities.push_back(playerBlue);
	entities.push_back(playerRed);
	entities.push_back(coinCopper);
	entities.push_back(coinSilver);
	entities.push_back(coinGold);
	entities.push_back(coinPlatinum);
	entities.push_back(starCopper);
	entities.push_back(starSilver);
	entities.push_back(starGold);
	entities.push_back(starPlatinum);

	Level level1(LEVEL_FREEPLAY, fontSheet, levelBG, music3, entities);
	Level level2(LEVEL_CLOCKED, fontSheet, levelBG, music4, entities);
	Level level3(LEVEL_SCORED, fontSheet, levelBG, music1, entities);

	Mix_PlayMusic(music3, -1);

	SDL_Event event;
	bool done = false;
	while (!done) {
		while (SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
				done = true;
			}
		}
		glClear(GL_COLOR_BUFFER_BIT);

		program->setModelMatrix(modelMatrix);
		program->setViewMatrix(viewMatrix);
		program->setProjectionMatrix(projectionMatrix);
		glUseProgram(program->programID);

		switch (state)
		{
		case MAIN_MENU:
			RenderBG(program, mainBG);
			if (keys[SDL_SCANCODE_1]) { // Press 1 to get into game level
				state = GAME_LEVEL_1;
				Mix_PlayChannel(-1, buttonPress, 0);
				Mix_PlayMusic(level1.getBgm(), -1);
			}
			if (keys[SDL_SCANCODE_2]) { // Press 2 to get into game level
				state = GAME_LEVEL_2;
				Mix_PlayChannel(-1, buttonPress, 0);
				Mix_PlayMusic(level2.getBgm(), -1);
			}
			if (keys[SDL_SCANCODE_3]) { // Press 3 to get into game level
				state = GAME_LEVEL_3;
				Mix_PlayChannel(-1, buttonPress, 0);
				Mix_PlayMusic(level3.getBgm(), -1);
			}
			if (keys[SDL_SCANCODE_ESCAPE]){
				done = true;
			}
			break;
		case GAME_LEVEL_1:
			if (!level1.isComplete()){
				level1.Update();
				level1.FixedUpdate();
				level1.Render(program);
				level1.RenderText(program);
			}
			else {
				lastWinner = level1.getWinner();
				state = MAIN_MENU;
				level1.reset();
				Mix_PlayMusic(music3, -1);
			}
			break;
		case GAME_LEVEL_2:
			if (!level2.isComplete()){
				level2.Update();
				level2.FixedUpdate();
				level2.Render(program);
				level2.RenderText(program);
			}
			else {
				lastWinner = level2.getWinner();
				state = GAME_OVER;
				level2.reset();
				Mix_PlayMusic(music3, -1);
			}
			break;
		case GAME_LEVEL_3:
			if (!level3.isComplete()){
				level3.Update();
				level3.FixedUpdate();
				level3.Render(program);
				level3.RenderText(program);
			}
			else {
				lastWinner = level3.getWinner();
				state = GAME_OVER;
				level3.reset();
				Mix_PlayMusic(music3, -1);
			}
			break;
		case GAME_OVER:
			RenderBG(program, overBG);
			program->setModelMatrix(textMatrix);
			textMatrix.identity();
			textMatrix.Translate(-7.5f, 0.0f, 0.0f);
			if (lastWinner == 0)
				DrawText(program, fontSheet, "Blue Player wins!", 1.0f, 0.005f);
			else if (lastWinner == 1)
				DrawText(program, fontSheet, "Red Player wins!", 1.0f, 0.005f);
			if (keys[SDL_SCANCODE_RETURN]) {
				level1.reset();
				level2.reset();
				level3.reset();
				state = MAIN_MENU;
				Mix_PlayChannel(-1, buttonPress, 0);
			}
			else if (keys[SDL_SCANCODE_ESCAPE]) {
				done = true;
			}
			break;
		}

		SDL_GL_SwapWindow(displayWindow);
	}

	SDL_Quit();
	return 0;
}
Beispiel #11
0
HUD::HUD()
{
	m_GameText[0] = "GAME OVER";
	m_GameText[1] = "N KEY TO START OR RESTART GAME";
	m_GameText[2] = "ARROW KEYS TO CONTROL SHIP UP FOR THRUST";
	m_GameText[3] = "LEFT CTRL KEY OR SPACE TO FIRE";
	m_GameText[4] = "RIGHT CTRL KEY FOR HYPERSPACE";
	m_GameText[5] = "HIGH SCORE HEROES";
	m_GameText[6] = "NEW HIGH SCORE";
	m_GameText[7] = "ARROW KEYS TO SELECT LETTER FIRE KEY WHEN DONE";

	m_PlayerHighScore = 0;
	m_PlayerHitsLeft = 0;
	m_PlayerScore = 0;
	m_NumberOfNewShips = 0;
	m_HighScoreDisplay = 0;
	m_HighScoreLetterEditing = 0; //What letter is being edited
	m_HighScoreLetterChoice = 0; //The letter that is being edited, what it is.

	m_GameOver = true;
	m_GameOverLocation.x = Window::GetWindowSize().x / 2;
	m_GameOverLocation.y = Window::GetWindowSize().y / 2 - 200;
	m_GameTextLocation.x = Window::GetWindowSize().x / 2;
	m_GameTextLocation.y = Window::GetWindowSize().y / 2 + 180;
	m_HitsLocation = Vector2i(100, 30);
	m_BottomY = Window::GetWindowSize().y - 30;
	m_PlayerScoreLocation = Vector2i(100, 10);
	m_PlayerHighScoreLocation = Vector2i(Window::GetWindowSize().x / 2, 10);
	m_HighScoreListLocaiton = Vector2i(Window::GetWindowSize().x / 2 + 30, Window::GetWindowSize().y / 2 -60);

	InitializeNumberLine();
	InitializeLetterLine();

	//Color of letters and numbers.
	m_Color.Red = 165;
	m_Color.Green = 165;
	m_Color.Blue = 255;
	m_Color.Alpha = 255;

	//Player Ship
	pShip = new PlayerShip();
	ShipColor.Red = 165;
	ShipColor.Green = 165;
	ShipColor.Blue = 255;
	ShipColor.Alpha = 255;

	p_Bonus = Mix_LoadWAV("Bonus.wav");

	p_Timer = new Timer();
	p_Timer->Start();
	m_HighScoreTimerAmount = 5;
	m_HighScoreTimer = p_Timer->Seconds() + m_HighScoreTimerAmount;

	//High Scores Setup
	// for loop to set all high scores to zero
	for (int rank = 0; rank < 10; rank++)
	{
		for (int name = 0; name < 3; name++)
		{
			m_HiScores[rank].Name[name] = 0;
		}

		m_HiScores[rank].Score = (rank * -2000) + 20000;
	}

	//Read high scores from file, if exist.
	m_SaveFileName = "HighScores";
	std::ifstream file(m_SaveFileName, std::ios::binary);

	if (file)
	{		
		file.read((char *)&m_HiScores, sizeof(m_HiScores));
	}

	file.close();

	// Temp high score test.
	m_PlayerHighScore = m_HiScores[0].Score;
}
Beispiel #12
0
int main() {
  int playAgain = 1;
  
  Uint32 waitTime = 1000.0f/30;
  Uint32 frameStartTime = 0;
  Sint32 delayTime;
  Uint32 idleTime = 0;

  Mix_Chunk* welcome   = NULL;
  Mix_Chunk* spinNoise = NULL;

  bool running = true;

  if (Mix_OpenAudio(44100, AUDIO_S16SYS, 2, 4096)) {
    cerr << "Unable to open audio" << endl;
    return false;
  }

  string temp;
  temp      = string(ROULETTE_DIR)+
    string("/sounds/welcome.wav");
  welcome   = Mix_LoadWAV(temp.c_str());
  temp      = string(ROULETTE_DIR)+
    string("/sounds/roulette_spin.wav");
  spinNoise = Mix_LoadWAV(temp.c_str());

  Mix_PlayChannel(-1, welcome, 0);

  while (playAgain == 1 && running == true) {

    SDL_Surface *screen = startupInit();

    int goodSpin = 0;
    int last_spin = -1;
    int spinningWheel = 0;

    int userInput[3] = {1,0,0};
    float dragDistance = 0;
    int startPress[2] = {0,0};

    int betSelection = -1;
    int numSelection = -1;
    int padNumber = 0;
    int playerCash = 2000;

    displayDigits(playerCash, screen, 0);

    int exit = 0;

    while (userExit(userInput) && playerCash > 0 && running == true) {

      delayTime = waitTime - (SDL_GetTicks() - frameStartTime);

      if (isRouletteWheel(userInput) == 1) {
	if (padNumber == 0) {
	  displayBetMoney(screen);
	}
	else if (betSelection == -1) {
	  displayChooseNumber(screen);
	}
	else if (numSelection != 11) {
	  displayPressEnter(screen);
	}
	else if (padNumber > playerCash) {
	  displayDontHaveCash(screen);
	}
	else {
	  clearText(screen);
	  spinningWheel = 1;
	  goodSpin = 1;
	  copyCoordinates(startPress, userInput);
	}
      }
      else if (spinningWheel && !isRouletteWheel(userInput) 
	       && userInput[0] ==3) {
	goodSpin = 0;
      }
      else if (spinningWheel && userInput[0] == 2 &&
	       (!goodSpin ||
		!calculateDistance(startPress[0], startPress[1],
				   userInput[1],userInput[2]))) {
	userInput[0] = 3;
	spinningWheel = 0;
      }
      else if (spinningWheel && goodSpin && isRouletteWheel(userInput) == 2) {
	Mix_PlayChannel(-1, spinNoise, 0);
	last_spin = spinRouletteWheel(calculateDistance(startPress[0], startPress[1], userInput[1], userInput[2]), screen, last_spin);
	playerCash = playerCash + (isWinningBet(last_spin, betSelection) * padNumber);
	clearMoneyBar(screen);
	clearRouletteWheel(screen);
	displayDigits(playerCash, screen, 0);

	spinningWheel = 0;
      }
      if (!spinningWheel) {
	betSelection = displayBetTable(userInput, screen,betSelection);
				
	numSelection = numberPadDown(userInput, screen, numSelection, padNumber);
	padNumber = numberPadUp(userInput, screen, numSelection, padNumber);
	userInput[0] = 3;
      }

      if (getUserInput(userInput) == false) {
	running  = false;
      }
      if (running == false) {
	break;
      }
      if(delayTime > 0) {
	SDL_Delay((Uint32)delayTime);
      }
      frameStartTime = SDL_GetTicks();
    }

    playAgain = -1;

    if (playerCash <= 0) {
      displayPlayAgainSplash(screen);
      while (playAgain == -1) {
	delayTime = waitTime - (SDL_GetTicks() - frameStartTime);

	getUserInput(userInput);
	playAgain = playAgainYesNo(userInput[1],userInput[2]);
	
	if(delayTime > 0) {
	  SDL_Delay((Uint32)delayTime);
	}
	frameStartTime = SDL_GetTicks();
      }
    }

    if (playAgain < 1) {
      displayCloseSplash(screen);
    } 

  }

  Mix_FreeChunk(welcome);
  Mix_FreeChunk(spinNoise);

  SDL_Quit();

  return 0;
}
Beispiel #13
0
SoundPlayer::SoundPlayer(std::string soundPath)
	:sound{Mix_LoadWAV(soundPath.c_str())}
{
	sound = Mix_LoadWAV(soundPath.c_str());
	assert(sound != nullptr);
}
Beispiel #14
0
//the massive main function
int main(int argc, char* args[]) // Gets command line input
{
	bool quit = false, playing = true, falling = true, held = false, paused = false, cheating = false; // All our miscellaneous bools to keep track of game states.
	
	int level = 0, lines = 0, score = 0, choice = 0, cheatseq = 0;
	
	Scores scores("gfx"); // Opens the uber camoflaged gfx file for getting highscores. Tricksy, eh?
	
	Uint32 start = 0; // A REALLY big int for keeping track of time
	
	srand(SDL_GetTicks()); // seeding the random... seed
	
	if( init() == false ) // Initialize SDL
	{
		cout << "Init fail" << endl;
		return 1; //ERR !!!!
	}
	
	block = load_image( "blocks.png" ); // load blocks
	
	if(block == NULL) 
	{
		cout << "Error loading blocks.png" << endl;
		return 1; //ERR!
	}
	
	back = load_image( "back.png" ); // load background
	
	if(back == NULL)
	{
		cout << "Error loading back.png" << endl;
		return 1; //ERR!
	}
	
	smallblock = load_image( "smallblocks.png" ); // small blocks for next and hold
	
	if(smallblock == NULL)
	{
		cout << "Error loading smallblocks.png" << endl;
		return 1; //ERR!
	}
	
	title = load_image( "title.png" ); // title
	
	if(title == NULL)
	{
		cout << "Error loading title.png" << endl;
		return 1; //ERR!
	}
	
	cursor = load_image( "cursor.png" ); // cursor in menu
	
	if(cursor == NULL)
	{
		cout << "Error loading cursor.png" << endl;
		return 1; //ERR!
	}
	
	font = TTF_OpenFont("ProggyClean.ttf", FONTSIZE); // our font
	
	if(font == NULL)
	{
		cout << "Error loading ProggyClean.ttf" << endl;
		return 1; //Yup. Didn't load.
	}
	
	effect = Mix_LoadWAV( "pause.wav" ); // dee doo sound
	
	if(effect == NULL)
	{
		cout << "Mix_LoadWAV: " << Mix_GetError() << endl;
	}
	
	while(playing) // while the user hasn't quit
	{
		score = 0;
		quit = false;
		Mix_FadeOutMusic(100); // fades out the music (if playing) for menu.
		
		Mix_FreeMusic(music); // gets rid of any music we might have loaded
		
		if(XM == true) // load title music
		{
			music = Mix_LoadMUS("title.xm");
		}
		else
		{
			music = Mix_LoadMUS("title.mp3");
		}
		
		if(!music)
		{
	   		cout << "Mix_LoadMUS(\"title.mp3\"): %s\n" << Mix_GetError() << endl;
	   		// music didn't load...
		}
		
		Mix_PlayMusic(music, -1); // play it til the user can't stand it no mo'.

		for(int i = 600; i>=100; i--) // slowly bring up the title
		{
			while( SDL_PollEvent( &event ) ) // gets any recent events (mouse, keyboard, whatev)
			{
				if( event.type == SDL_QUIT ) // X button
				{
					i = 100;
					playing = false;
					quit = true;
				}
				else if( event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) //escape
				{
					i = 100; // brings the title screen instantly
				}
			}
			SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0x00, 0x00, 0x00 ) ); // fill screen black
			apply_surface( 200, i, title, screen ); // apply title
			if( SDL_Flip( screen ) == -1 ) // hand *screen to video card
			{
				return 1; //ERRRRRRR !!
			}
			SDL_Delay(2); // slows it down a wee bit.
		}
		
		apply_surface( 325, 402 + choice * 50, cursor, screen ); // display cursor
		
		numbers = TTF_RenderText_Blended(font, "START", fontColor); // start
		apply_surface( 350, 400, numbers, screen );
		
		numbers = TTF_RenderText_Blended(font, "HIGH SCORES", fontColor); // high scores
		apply_surface( 350, 450, numbers, screen );
		
		numbers = TTF_RenderText_Blended(font, "EXIT", fontColor); // exit
		apply_surface( 350, 500, numbers, screen );
		
		if( SDL_Flip( screen ) == -1 )
		{
			return 1; //ERRRRRRR !!
		}
		
		paused = true; //pause for menu
		while(paused && !quit)
		{
			while( SDL_PollEvent( &event ) ) // wait for events
			{
				if( event.type == SDL_QUIT )
				{
					paused = false;
					playing = false;
					quit = true;
				}
				else if( event.type == SDL_KEYDOWN )
				{
					switch(event.key.keysym.sym)
					{
						case SDLK_ESCAPE:
							paused = false;
							quit = true;
							playing = false;
							break;
						case SDLK_RETURN:
							switch(choice)
							{
								case 0:
									paused = false;
									break;
								case 1:
									scores.display();
									break;
								case 2:
									paused = false;
									quit = true;
									playing = false;
									break;
							}
							break;
						case SDLK_DOWN: // down, move cursor down
							Mix_PlayChannel(-1, effect, 0); // dee doo sound
							if(choice < 2)
							{
								choice++;
							}
							else
							{
								choice = 0;
							}
							break;
						case SDLK_UP: // up, move cursor up
							Mix_PlayChannel(-1, effect, 0); // see above
							if(choice > 0)
							{
								choice--;
							}
							else
							{
								choice = 2;
							}
							break;
					}
					SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0x00, 0x00, 0x00 ) );
					
					apply_surface( 200, 100, title, screen );
					apply_surface( 325, 402 + choice * 50, cursor, screen );
							
					numbers = TTF_RenderText_Blended(font, "START", fontColor);
					apply_surface( 350, 400, numbers, screen );
					
					numbers = TTF_RenderText_Blended(font, "HIGH SCORES", fontColor);
					apply_surface( 350, 450, numbers, screen );
		
					numbers = TTF_RenderText_Blended(font, "EXIT", fontColor);
					apply_surface( 350, 500, numbers, screen );
		
					if( SDL_Flip( screen ) == -1 )
					{
						return 1; //ERRRRRRR !!
					}
				}
			}
		}
		
		if(!quit) // if the user didn't quit
		{		
			Mix_FadeOutMusic(100); //fade out title music
			
			Mix_FreeMusic(music); //free it
			
			if(XM == true) // change to game music
			{
				music = Mix_LoadMUS("music.xm");
			}
			else
			{
				music = Mix_LoadMUS("music.mp3");
			}
		
			if(!music)
			{
	   			cout << "Mix_LoadMUS(\"music.mp3\"): %s\n" << Mix_GetError() << endl;
	   			// music didn't load...
			}
			
			Mix_PlayMusic(music, -1);
		
			SDL_Delay(1500); // wait for ba-ding! to finish
		}
		
		Tile *tile = NULL, *next = NULL, *next2 = NULL, *next3 = NULL, *hold = NULL, *blank = NULL; //current tile, next tiles 1 2 3, hold, and the tile used for switching hold
		
		setclips(); // set the clip boxes for tiles
		
		clearfield(); // initialize the field

		next = new Tile(); // inits new tiles
		next2 = new Tile();
		next3 = new Tile();
		
		while(!quit)
		{
			SDL_Delay(50); // wait a bit for the next block to drop
			tile = next; // next to current
			next = next2; // move nexts
			next2 = next3;
			next3 = new Tile(); // new next 3
			if(!tile->check(0, 0)) // if the tile is colliding from the get go
			{
				tile->show();
				if( SDL_Flip( screen ) == -1 )
				{
					return 1; //ERRRRRRR !!
				}
				gameOver(); // THEN YOU LOSE! HA!
				scores.checkScore(score); // Did you get a high score?
				scores.save(); // save the high score file
				scores.display(); // display the current high scores
				quit = true;
			}
			falling = true;
			
			while(falling && !quit) // the there a lot of !quits from now on so it goes straight back to the menu
			{
				apply_surface( 0, 0, back, screen ); // background
				tile->show(); // show the current tile
				if(hold != NULL)
				{
					hold->disp(27,78); // display hold
				}
				next->disp(390, 78); // display nexts
				next2->disp(390, 158);
				next3->disp(390, 238);
				start = SDL_GetTicks(); // start the timer
				while( falling && SDL_GetTicks() - start < (1/((static_cast<double>(level)/25) + 1))*(SPEED - MINSPEED)+MINSPEED) // spiffy formula I took way to long to make for speeding up
				{
					while( SDL_PollEvent( &event ) ) // get events
					{
						if( event.type == SDL_QUIT ) // quit immediatly
						{
							clean();
							exit(0);
							playing = false;
						}
						else if( event.type == SDL_KEYDOWN ) // was a key pressed?
						{
							switch( event.key.keysym.sym ) // what key was pressed?
							{
								case SDLK_LEFT: // move left
									tile->check(-1, 0);
									break;
								case SDLK_RIGHT: // move right
									tile->check(1, 0);
									break;
								case SDLK_z: // rotate CCW
									tile->rotate(CC);
									break;
								case SDLK_x: // rotate CW
									tile->rotate(CW);
									break;
								case SDLK_DOWN: // soft drop
									if(!tile->check(0,1)) // if it hits something as a result of dropping once
									{
	                                    falling = false; // apply the tile
	                                }
	                                start = SDL_GetTicks(); // reset the timer
									break;
								case SDLK_UP: // hard drop
									while(tile->check(0,1)) // move it down til it cant any more
									{
										score += 2 * (level + 1); // you get points for being so daring!
									}
									start -= 1000; //Lock that sucka!
									break;
								case SDLK_n: // this is the cheat key. But you have to be cheating to use it ;D
									if(cheating)
									{
										delete tile; // basically just gives you new tiles
										tile = new Tile();
									}
									break;
								case SDLK_ESCAPE: // back to main menu
									quit = true;
									break;
								case SDLK_k: //SUPER SECRET KYLE-MODE!
									block = load_image( "kyles.png" );
									back = load_image( "kyleback.png" );
									smallblock = load_image("smallkyles.png");
									Mix_HaltMusic();
									music = Mix_LoadMUS("rawk.mp3");
									Mix_PlayMusic(music, -1);
									break;
								case SDLK_o: // back to original
									block = load_image( "blocks.png" );
									back = load_image( "back.png" );
									smallblock = load_image("smallblocks.png");
									Mix_HaltMusic();
									music = Mix_LoadMUS("music.mp3");
									Mix_PlayMusic(music, -1);
									break;
								case SDLK_c: // hold
									if(hold && !held) // if there is something held and you haven't held yet this turn
									{
										blank = hold; // switch current and held
										hold = tile;
										tile = blank;
									}
									else if(!hold) // if you've never held
									{
										hold = tile; // hold current and make more tiles
										tile = next;
										next = next2;
										next2 = next3;
										next3 = new Tile();
									}
									hold->reset(); // reset the x and y values of the tile
									held = true;
									break;
								case SDLK_p: // pause
									paused = true;
									Mix_PauseMusic(); // pause music
									Mix_PlayChannel(-1, effect, 0); // play the dee doo
									apply_surface( 0, 0, back, screen ); // cover the tiles
									numbers = TTF_RenderText_Solid(font, intToStr(score).c_str(), fontColor); // but keep the scores
									apply_surface( 550, 50, numbers, screen );
									numbers = TTF_RenderText_Solid(font, intToStr(level).c_str(), fontColor);
									apply_surface( 550, 120, numbers, screen );
									if( SDL_Flip( screen ) == -1 ) // display screen
									{
										return 1; //ERRRRRRR !!
									}
									while(paused)
									{
										while(SDL_PollEvent( &event )) // get events
										{
											if( event.type == SDL_QUIT ) // quit immediatly
											{
												quit = true;
												paused = false;
												playing = false;
											}
											else if( event.type == SDL_KEYDOWN ) // key down?
											{
												switch( event.key.keysym.sym ) // what key?
												{
													case SDLK_ESCAPE: // unpause
													case SDLK_p: // unpause
														paused = false;
														break;
													case SDLK_UP: // CHEATING!! WOO!!! UP UP DOWN DOWN LEFT RIGHT LEFT RIGHT A B. <3 CONTRA.
														if(cheatseq == 0 || cheatseq == 1)
														{
															cheatseq++;
														}
														else
														{
															cheatseq = 0; // if you screwed up
														}
														break;
													case SDLK_DOWN:
														if(cheatseq == 2 || cheatseq == 3)
														{
															cheatseq++;
														}
														else
														{
															cheatseq = 0;
														}
														break;
													case SDLK_LEFT:
														if(cheatseq == 4 || cheatseq == 6)
														{
															cheatseq++;
														}
														else
														{
															cheatseq = 0;
														}
														break;
													case SDLK_RIGHT:
														if(cheatseq == 5 || cheatseq == 7)
														{
															cheatseq++;
														}
														else
														{
															cheatseq = 0;
														}
														break;
													case SDLK_z:
														if(cheatseq == 8)
														{
															cheatseq++;
														}
														else
														{
															cheatseq = 0;
														}
														break;
													case SDLK_x:
														if(cheatseq == 9)
														{
															Mix_PlayChannel(-1, effect, 0);
															cheating = true;
														}
														else
														{
															cheatseq = 0;
														}
														break;
													default:
														cheatseq = 0;
														break;
												}
											}
										}
									}
									cheatseq = 0; // If you screwed up the cheat sequence
									Mix_ResumeMusic(); // play that funky music
									break;
							}
							apply_surface( 0, 0, back, screen ); // put the background up
							screen << *tile; //There. Overloading. Huzzah.
							if(hold != NULL) // display hold
							{
								hold->disp(27,78);
							}
							next->disp(390, 78); // display all the nexts
							next2->disp(390, 158);
							next3->disp(390, 238);
							numbers = TTF_RenderText_Solid(font, intToStr(score).c_str(), fontColor); //display scores
							apply_surface( 550, 50, numbers, screen );
							numbers = TTF_RenderText_Solid(font, intToStr(level).c_str(), fontColor); //Pretty sweet you can use all the sweet string functions with a function that returns a string =D
							apply_surface( 550, 120, numbers, screen );
							if( SDL_Flip( screen ) == -1 ) // show screen
							{
								return 1; //ERRRRRRR !!
							}
						}
					}
					numbers = TTF_RenderText_Solid(font, intToStr(score).c_str(), fontColor); // display scores
					apply_surface( 550, 50, numbers, screen );
					numbers = TTF_RenderText_Solid(font, intToStr(level).c_str(), fontColor);
					apply_surface( 550, 120, numbers, screen );
					if( SDL_Flip( screen ) == -1 )
					{
						return 1; //ERRRRRRR !!
					}
					SDL_Delay(1);
				}
				if(tile->check(0, 1) == 0) // if it can't fall any more
				{
					falling = false; // stop falling
				}
			}
			tile->apply(); // apply it to the pile
			held = false; // you can hold again!
			score += (level+1)*checklines(lines); // check the lines and score accordingly
			level = lines/10; // level up?
			delete tile; // delete the current tile so we don't get yelled at
		}
		delete next; // delete all the other tiles if you lost
		delete next2;
		delete next3;
		delete hold;
	}
	clean(); // uninitialize SDL and everything
	return 0; // RETURN THAT ZERO, BABY.
} // Fin
Beispiel #15
0
// based on http://www.willusher.io/sdl2%20tutorials/2013/08/17/lesson-1-hello-world/
int main( int argc, char* args[] )
{
	if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
	{
		std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
		cleanExit(1);
	}
	std::cout << "SDL initialised OK!\n";

	// Initialise the audio mixer and also explained the variables.
	// 44100 - Common hertz level for these things
	// MIX_DEFAULT_FORMAT - Like the SDL_INIT_EVERYTHING, some init settings
	// 2 - Audio Channels for stereo play
	// 2048 - Sample size, can affect lag time for effect to play
	// != 0 - Same as other init stuff, not sure why, just needs it.
	if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) != 0)
	{
		std::cout << "SDL_Mixer init error: " << Mix_GetError() << std::endl;
		cleanExit(1);
	}
	std::cout << "SDP_Mixer Initialised OK!" << std::endl;
	//create window
	win = SDL_CreateWindow("SDL Hello World!", 100, 100, screenW, screenH, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);

	//error handling
	if (win == nullptr)	
	{
		std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
		cleanExit(1);
	}
	std::cout << "SDL CreatedWindow OK!\n";

	ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	if (ren == nullptr)
	{
		std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
		cleanExit(1);
	}

	player = new sprite("./assets/spritesheet.png", 50.0f, 520.0f, 24.0f, 32.0f, ren);
	player->srcRect.x = 0.0f;
	player->srcRect.y = 96.0f;
	player->srcRect.w = 24.0f;
	player->srcRect.h = 32.0f;
	player->playerScore = 0;
	player->bufferMax = 5;

#pragma region Hens
	hen1 = new enemy("./assets/spritesheet.png", 500, 100, 24, 40, ren);
	hens.push_back(hen1);
	hen1->state = enemy::moveRight;
	hen1->flipDirection = true;
	hen1->xTarget1 = 200.0f;
	hen1->xTarget2 = 250.0f;
	hen1->srcRect.x = 0.0f;
	hen1->srcRect.y = 0.0f;
	hen1->srcRect.w = 24.0f;
	hen1->srcRect.h = 40.0f;

	hen2 = new enemy("./assets/spritesheet.png", 700, 530, 24, 40, ren);
	hens.push_back(hen2);
	hen2->state = enemy::moveLeft;
	hen2->xTarget1 = 100.0f;
	hen2->xTarget2 = 750.0f;
	hen2->srcRect.x = 0.0f;
	hen2->srcRect.y = 0.0f;
	hen2->srcRect.w = 24.0f;
	hen2->srcRect.h = 40.0f;

	hen3 = new enemy("./assets/spritesheet.png", 600, 280, 24, 40, ren);
	hens.push_back(hen3);
	hen3->state = enemy::moveRight;
	hen3->xTarget1 = 100.0f;
	hen3->xTarget2 = 750.0f;
	hen3->srcRect.x = 0.0f;
	hen3->srcRect.y = 0.0f;
	hen3->srcRect.w = 24.0f;
	hen3->srcRect.h = 40.0f;
#pragma endregion

#pragma region Audio stuff
	// This is formatted in the same way to the default code from John as it makes sense and I want to stick to it.
	jumpEffect = Mix_LoadWAV("./assets/jump.wav");
	if (jumpEffect == nullptr)
	{
		std::cout << "Mix_LoadWAV Error: " << Mix_GetError() << std::endl;
		cleanExit(1);
	}

	pickup1 = Mix_LoadWAV("./assets/pickup1.wav");
	if (pickup1 == nullptr)
	{
		std::cout << "Mix_LoadWAV Error: " << Mix_GetError() << std::endl;
		cleanExit(1);
	}

	pickup2 = Mix_LoadWAV("./assets/pickup2.wav");
	if (pickup2 == nullptr)
	{
		std::cout << "Mix_LoadWAV Error: " << Mix_GetError() << std::endl;
		cleanExit(1);
	}

	background = Mix_LoadMUS("./assets/background_music.wav");
	if (background == nullptr)
	{
		std::cout << "Mix_LoadWAV Error: " << Mix_GetError() << std::endl;
		cleanExit(1);
	}
#pragma endregion


	if( TTF_Init() == -1 )
	{
		std::cout << "TTF_Init Failed: " << TTF_GetError() << std::endl;
		cleanExit(1);
	}

	TTF_Font* sans = TTF_OpenFont("./assets/Hack-Regular.ttf", 96);
	if (sans == nullptr)
	{
		std::cout << "TTF_OpenFont Error: " << TTF_GetError() << std::endl;
		cleanExit(1);
	}
	SDL_Color White = { 255, 255, 255 };
	SDL_Color Purple = { 165, 0, 220 };
	
	std::string lives = "Lives: " + std::to_string(player->playerLives);
	const char* lifeCounts = lives.c_str();

	loading = new text(ren, "Loading...", 200, 200, 400, 130, sans, White);
	Load();

	scoreCount = new text(ren, player->playerScore, 0, 0, 180, 60, sans, Purple);
	lifeCount = new text(ren, lifeCounts, 600, 0, 180, 60, sans, Purple);

	drawTileMap();

	loading->isShowing = false;
	Mix_PlayMusic(background, -1);

	while (!done) //loop until done flag is set)
	{
		handleInput(); // this should ONLY SET VARIABLES

		updateSimulation(); // this should ONLY SET VARIABLES according to simulation

		render(); // this should render the world state according to VARIABLES

		SDL_Delay(20); // unless vsync is on??
	}

	cleanExit(0);
	return 0;
}
Beispiel #16
0
Player::Player( Game* game, int currentTicks )
{
    mPosX = PLAYER_CAMERA_OFFSET;
    mPosY = SCREEN_HEIGHT / 2 - PLAYER_HEIGHT / 2;

    mVelY = 0.0;
    mVelX = CAMERA_VELOCITY;

    mLastMove = currentTicks;

    mLastFlap = currentTicks;

    mCollider.x = mPosX;
    mCollider.y = mPosY;
    mCollider.w = PLAYER_WIDTH;
    mCollider.h = PLAYER_HEIGHT;

    mGamePointer = game;

    if( !mSpriteSheet.loadFromFile( mGamePointer->getRenderer(), "assets/sprite_sheet.png" ) )
    {
        printf( "Could not load player sprite sheet!\n" );
    }

    mPlayerTextureClip.x = 6;
    mPlayerTextureClip.y = 982;
    mPlayerTextureClip.w = 34;
    mPlayerTextureClip.h = 24;

    mPlayerTextureStretchRect.x = mPosX;
    mPlayerTextureStretchRect.y = mPosY;
    mPlayerTextureStretchRect.w = BIRD_LENGTH;
    mPlayerTextureStretchRect.h = ( BIRD_LENGTH * 24 ) / 34;

    mRotationAngle = 0.0;

    mRotationSpeed = ROTATION_SPEED;

    mCurrentScore = 0;

    mAlive = true;

    mScoreTracker = new ScoreTracker( mGamePointer, this );

    mAnimationClips.reserve( FLAP_TOTAL );

    // Set animation neutral clip rect
    mAnimationClips[ FLAP_NEUTRAL ].x = 62;
    mAnimationClips[ FLAP_NEUTRAL ].y = 982;
    mAnimationClips[ FLAP_NEUTRAL ].w = 34;
    mAnimationClips[ FLAP_NEUTRAL ].h = 24;

    // Set animation flapping up clip rect
    mAnimationClips[ FLAP_UP ].x = 6;
    mAnimationClips[ FLAP_UP ].y = 982;
    mAnimationClips[ FLAP_UP ].w = 34;
    mAnimationClips[ FLAP_UP ].h = 24;

    // Set animation flapping down clip rect
    mAnimationClips[ FLAP_DOWN ].x = 118;
    mAnimationClips[ FLAP_DOWN ].y = 982;
    mAnimationClips[ FLAP_DOWN ].w = 34;
    mAnimationClips[ FLAP_DOWN ].h = 24;


    // Load sound effects
    mSoundEffects.reserve( SFX_TOTAL );

    mSoundEffects[ SFX_FLAP ] = Mix_LoadWAV( "assets/sounds/sfx_wing.ogg" );
    if( mSoundEffects[ SFX_FLAP ] == nullptr )
    {
        printf( "Could not load SFX_FLAP sound effect! Mix_Error: %s\n", Mix_GetError() );
    }

    mSoundEffects[ SFX_GET_POINT ] = Mix_LoadWAV( "assets/sounds/sfx_point.ogg" );
    if( mSoundEffects[ SFX_GET_POINT ] == nullptr )
    {
        printf( "Could not load SFX_GET_POINT sound effect! Mix_Error: %s\n", Mix_GetError() );
    }

    mSoundEffects[ SFX_HIT ] = Mix_LoadWAV( "assets/sounds/sfx_hit.ogg" );
    if( mSoundEffects[ SFX_HIT ] == nullptr )
    {
        printf( "Could not load SFX_HIT sound effect! Mix_Error: %s\n", Mix_GetError() );
    }

    mSoundEffects[ SFX_DIE ] = Mix_LoadWAV( "assets/sounds/sfx_die.ogg" );
    if( mSoundEffects[ SFX_DIE ] == nullptr )
    {
        printf( "Could not load SFX_DIE sound effect! Mix_Error: %s\n", Mix_GetError() );
    }
}
Beispiel #17
0
int main( int argc, char **argv )
{
    /* Flags to pass to SDL_SetVideoMode */
    int videoFlags;
    /* main loop variable */
    bool done = false;
    /* used to collect events */
    SDL_Event event;
    /* this holds some info about our display */
    const SDL_VideoInfo *videoInfo;
    /* whether or not the window is active */
    bool isActive = true;
   	int bpp;
   	/* Audio */
	int audio_rate      = 22050;
	Uint16 audio_format = AUDIO_S16;
	int audio_channels  = 2;
	int audio_buffers   = 4096;

    /* initialize SDL */
    if ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO ) < 0 )
	{
	    fprintf( stderr, "Video/Audio initialization failed: %s\n", SDL_GetError( ) );
	    Quit( 1 );
	}

	if(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers))
	{
	    fprintf( stderr, "Unable to open audio!\n" );
	    Quit( 1 );
	}

	/* We're going to pre-load the sound effects that we need right here */
	Shot = Mix_LoadWAV("Data/Shot.wav");
	if(!Shot)
	{
    	fprintf( stderr, "Mix_LoadWAV: %s\n", Mix_GetError( ) );
	    Quit( 1 );
	}
		
    /* Fetch the video info */
    videoInfo = SDL_GetVideoInfo( );

    if ( !videoInfo )
	{
	    fprintf( stderr, "Video query failed: %s\n", SDL_GetError( ) );
	    Quit( 1 );
	}

    /* the flags to pass to SDL_SetVideoMode */
    videoFlags  = SDL_OPENGL;          /* Enable OpenGL in SDL */
    videoFlags |= SDL_GL_DOUBLEBUFFER; /* Enable double buffering */
    videoFlags |= SDL_HWPALETTE;       /* Store the palette in hardware */
    videoFlags |= SDL_RESIZABLE;       /* Enable window resizing */

    /* This checks to see if surfaces can be stored in memory */
    if ( videoInfo->hw_available )
		videoFlags |= SDL_HWSURFACE;
    else
		videoFlags |= SDL_SWSURFACE;

    /* This checks if hardware blits can be done */
    if ( videoInfo->blit_hw )
		videoFlags |= SDL_HWACCEL;

    /* Sets up OpenGL double buffering */
    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

    /* get a SDL surface */
   	bpp = videoInfo->vfmt->BitsPerPixel;
    surface = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, bpp, videoFlags );

    /* Verify there is a surface */
    if ( !surface )
	{
	    fprintf( stderr,  "Video mode set failed: %s\n", SDL_GetError( ) );
	    Quit( 1 );
	}

    /* initialize OpenGL */
	if (!initGL())
	{
	    fprintf( stderr,  "OpenGL initialization failed!\n");
	    Quit( 1 );
	}

    /* resize the initial window */
    resizeWindow( SCREEN_WIDTH, SCREEN_HEIGHT );
	
    /* Hides the cursor */
    SDL_ShowCursor(0);

    /* wait for events */
    while ( !done )
	{
	    /* handle the events in the queue */
	    while ( SDL_PollEvent( &event ) )
		{
		    switch( event.type )
			{
			case SDL_ACTIVEEVENT:
			    /* Something's happend with our focus
			     * If we lost focus or we are iconified, we
			     * shouldn't draw the screen
			     */
			    if ( event.active.gain == 0 )
					isActive = false;
			    else
				{
					isActive = true;
					lastTickCount = SDL_GetTicks();	// Get The Tick Count
				}
			    break;			    
			case SDL_VIDEORESIZE:
			    /* handle resize event */
			    surface = SDL_SetVideoMode( event.resize.w, event.resize.h, 16, videoFlags );
			    if ( !surface )
				{
				    fprintf( stderr, "Could not get a surface after resize: %s\n", SDL_GetError( ) );
				    Quit( 1 );
				}
			    resizeWindow( event.resize.w, event.resize.h );
			    break;
			case SDL_KEYDOWN:
			    /* handle key presses */
			    handleKeyPress( &event.key.keysym );
			    break;
			case SDL_QUIT:
			    /* handle quit requests */
			    done = true;
			    break;
			case SDL_MOUSEBUTTONDOWN:
				/* handle left click */
				if (event.button.button == SDL_BUTTON_LEFT)
				{
	            	mouse_x = event.button.x;
					mouse_y = event.button.y;
					Selection();
				}
				break;
			case SDL_MOUSEMOTION:			
				/* handle mouse movements */
	            mouse_x = event.motion.x;
				mouse_y = event.motion.y;
				break;			
			default:
			    break;
			}
		}

	    /* draw the scene */
	    if ( isActive && !done)
			drawGLScene();
	}

    /* clean ourselves up and exit */
    Quit( 0 );

    /* Should never get here */
    return( 0 );
}
Beispiel #18
0
TextRoom::TextRoom(QWidget *parent, Qt::WFlags f)
		: QWidget(parent, f), sentenceTally(0)
{
	setupUi(this);
	setObjectName("textroom");

// Set the default values for variables.
	numChanges = 0;
	prevLength = 0;
	wordcount = 0;
	alarm = 0;
	parasold = 0;
	isHighlighted = false;

#ifdef Q_OS_MACX
	// Find the path for the app path 
	QDir tmpDir = QDir(QCoreApplication::applicationDirPath());
	// go into Resources folder
	tmpDir.cdUp();
	tmpDir.cd("Resources");
	// get the full path for the resources
	resourcesDir = tmpDir.path();
#endif

// Create the dialog windows.
	optionsDialog = new OptionsDialog(this);
	helpDialog = new HelpDialog(this);
	selectFont = new SelectFont(this);
	aboutDialog = new AboutDialog(this);
	scratchDialog = new ScratchDialog(this);
	miniFlo = new MiniFlo(this);
	getAWord = new GetAWord(this);
	musicRoom = new MusicRoom(this);
	googleDocsDialog = new GoogleDocsDialog(this);	

// Read settings saved by Options Dialog.
#ifdef Q_OS_WIN32
	settings = new QSettings(QSettings::IniFormat, QSettings::UserScope, QApplication::applicationName());
#else
	settings = new QSettings();
#endif
	readSettings();

// Sound adjustments.
	int audio_rate = 11025;
	Uint16 audio_format = AUDIO_S16SYS;
	int audio_channels = 2;
	int audio_buffers = 1024;
	
	if ( SDL_Init(SDL_INIT_AUDIO) < 0 ) {
		fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
		exit(1);
	}
	atexit(SDL_Quit);
	
	if(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) != 0) {
		printf("Unable to initialize audio: %s\n", Mix_GetError());
		exit(1);
	}

// Load sounds.
#ifdef Q_OS_WIN32
	soundenter = Mix_LoadWAV("keyenter.wav");
#elif defined(Q_OS_MACX)
	QString tmp = resourcesDir;
	tmp.append("/sounds/keyenter.wav");
	soundenter = Mix_LoadWAV(tmp.toAscii());
#else
	soundenter = Mix_LoadWAV("/usr/share/sounds/keyenter.wav");
#endif
	if(soundenter == NULL) {
		printf("Unable to load WAV file: %s\n", Mix_GetError());
	}

#ifdef Q_OS_WIN32
	soundany = Mix_LoadWAV("keyany.wav");
#elif defined(Q_OS_MACX)
	tmp = resourcesDir;
	tmp.append("/sounds/keyany.wav");
	soundany = Mix_LoadWAV(tmp.toAscii());
#else
	soundany = Mix_LoadWAV("/usr/share/sounds/keyany.wav");
#endif
	if(soundany == NULL) {
		printf("Unable to load WAV file: %s\n", Mix_GetError());
	}
		
// Create the keyboard shortcuts.
	new QShortcut ( QKeySequence(QKeySequence::New), this, SLOT( newFile() ) );
	new QShortcut ( QKeySequence(QKeySequence::Open), this, SLOT( open() ) );
	new QShortcut ( QKeySequence(QKeySequence::Save), this, SLOT( save() ) );
	new QShortcut ( QKeySequence(QKeySequence::HelpContents), this, SLOT( help() ) );
#ifdef Q_OS_MACX
	new QShortcut ( QKeySequence(tr("F1", "Help")), this, SLOT( help() ) );
#endif
	new QShortcut ( QKeySequence(tr("F2", "Options")), this, SLOT( options() ) );
	new QShortcut ( QKeySequence(tr("F3", "About")), this, SLOT( about() ) );
	new QShortcut ( QKeySequence(tr("F5", "Spell Check")), this, SLOT( spellCheck() ) );
	new QShortcut ( QKeySequence(tr("F6", "Scratch Pad")), this, SLOT( showScratchPad() ) );
	new QShortcut ( QKeySequence(tr("Ctrl+P", "Print")), this, SLOT( print() ) );
	new QShortcut ( QKeySequence(tr("Shift+Ctrl+S", "Save As")), this, SLOT( saveAs() ) );
	new QShortcut ( QKeySequence(tr("Ctrl+D", "Insert Date")), this, SLOT( insertDate() ) );
	new QShortcut ( QKeySequence(tr("Ctrl+T", "Insert Time")), this, SLOT( insertTime() ) );	
	new QShortcut ( QKeySequence(tr("Ctrl+Q", "Quit Application")) , this, SLOT( close() ) );
	new QShortcut ( QKeySequence(tr("Alt+F4", "Quit Application")) , this, SLOT( close() ) );
	new QShortcut ( QKeySequence(tr("Ctrl+F", "Find Text")) , this, SLOT( find() ) );
	new QShortcut ( QKeySequence(tr("F11", "Toggle Fullscreen")) , this, SLOT( toggleFullScreen() ) );
	new QShortcut ( QKeySequence(tr("Esc", "Toggle Fullscreen")) , this, SLOT( toggleEscape() ) );
	new QShortcut ( QKeySequence(tr("Ctrl+M", "Minimize TextRoom")) , this, SLOT( showMinimized() ) );
	new QShortcut ( QKeySequence(tr("F4", "Find Next")) , this, SLOT( find_next() ) );
	new QShortcut ( QKeySequence(tr("Ctrl+F4", "Find Previous")) , this, SLOT( find_previous() ) );
	new QShortcut ( QKeySequence(tr("Ctrl+B", "Bold")) , this, SLOT( textBold() ) );
	new QShortcut ( QKeySequence(tr("Ctrl+I", "Italic")) , this, SLOT( textItalic() ) );
	new QShortcut ( QKeySequence(tr("Ctrl+Up", "Increase Text Size")) , this, SLOT( textSizeUp() ) );
	new QShortcut ( QKeySequence(tr("Ctrl+Down", "Decrease Text Size")) , this, SLOT( textSizeDown() ) );	
	new QShortcut ( QKeySequence(tr("Ctrl+W", "Select Font")) , this, SLOT( changeFont() ) );	
        new QShortcut ( QKeySequence(tr("Ctrl+R", "Align Right")) , this, SLOT( alignRight() ) );
        new QShortcut ( QKeySequence(tr("Ctrl+L", "Align Left")) , this, SLOT( alignLeft() ) );
        new QShortcut ( QKeySequence(tr("Ctrl+J", "Align Justify")) , this, SLOT( alignJustify() ) );
        new QShortcut ( QKeySequence(tr("Ctrl+E", "Align Center")) , this, SLOT( alignCenter() ) );
        new QShortcut ( QKeySequence(tr("Ctrl+Alt+I", "Insert Image")) , this, SLOT( insertImage() ) );
        new QShortcut ( QKeySequence(tr("F7", "Show MiniFlo")) , this, SLOT( showMiniFlo() ) );
        new QShortcut ( QKeySequence(tr("F8", "Get A Word")) , this, SLOT( showGetAWord() ) );
        new QShortcut ( QKeySequence(tr("F9", "MusicRoom")) , this, SLOT( showMusicRoom() ) );
        new QShortcut ( QKeySequence(tr("F10", "Google Docs")) , this, SLOT( exportToGoogle() ) );
	// Service: show cursor
	new QShortcut ( QKeySequence(tr("Shift+F4", "Show Cursor")) , this, SLOT( sCursor() ) );

	//fw = new QFileSystemWatcher(this);
	//fw->addPath( settings->fileName() );

	// If file is changed, read the settings->
	//connect(fw, SIGNAL(fileChanged(const QString)),
	//		this, SLOT(readSettings()));
	// If the document is changed, do some stuff.
	connect(textEdit->document(), SIGNAL(contentsChanged()),
		this, SLOT(documentWasModified()));

	// If position is changed, scroll.
	connect(textEdit->verticalScrollBar(), SIGNAL(valueChanged(int)),
		this, SLOT(vPositionChanged()));
	// If horizontal scrollar is changed, scroll.
	connect(horizontalSlider, SIGNAL(valueChanged(int)),
		this, SLOT(hSliderPositionChanged()));
	connect(textEdit, SIGNAL(anchorClicked(QUrl)), this, SLOT(showScratchPad()));

	// check if we need to open some file at startup
	const QStringList args = QCoreApplication::arguments();
	if (args.count() == 2)
	{
		QFile file( args.at(1) );
		if ( file.exists() )
			curFile = args.at(1);
	}
	
	if (!curFile.isEmpty())
		loadFile(curFile);
	else
		newFile();


	// set cursor position
	if ( isSaveCursor )
	{
		textEdit->textCursor().setPosition(cPosition);
	}

	writeSettings();

// Refresh the file status every second.
	QTimer *timer = new QTimer(this);
	connect(timer, SIGNAL(timeout()), this, SLOT(getFileStatus()));
	timer->start(1000);
}
void Game::Start()
{
  // Seed the random number generator
  srand(time(NULL));

  GameEngine *pGE = GameEngine::GetEngine();
  SDL_Renderer *renderer = pGE->GetRenderer();

  // Create and load the bitmaps
  SDL_Color scTrans = {255, 0, 255, 255};
  _pOfficeBitmap = new Bitmap(renderer, "res/Office.bmp");
  _pTargetBitmap = new Bitmap(renderer, "res/Target.bmp", &scTrans);
  _pPowBitmap = new Bitmap(renderer, "res/Pow.bmp", &scTrans);
  _pGuyBitmaps[0] = new Bitmap(renderer, "res/Guy1.bmp", &scTrans);
  _pGuyBitmaps[1] = new Bitmap(renderer, "res/Guy2.bmp", &scTrans);
  _pGuyBitmaps[2] = new Bitmap(renderer, "res/Guy3.bmp", &scTrans);
  _pGuyBitmaps[3] = new Bitmap(renderer, "res/Guy4.bmp", &scTrans);
  _pGuyBitmaps[4] = new Bitmap(renderer, "res/Guy5.bmp", &scTrans);
  _pSmallGuyBitmap = new Bitmap(renderer, "res/SmallGuy.bmp", &scTrans);
  _pGameOverBitmap = new Bitmap(renderer, "res/GameOver.bmp", &scTrans);

  // Create the target, pow, and guy sprites
  SDL_Rect rcBounds = { 0, 0, 500, 400 };
  _pTargetSprite = new Sprite(_pTargetBitmap, rcBounds, BA_STOP);
  _pTargetSprite->SetZOrder(4);
  pGE->AddSprite(_pTargetSprite);
  _pPowSprite = new Sprite(_pPowBitmap, rcBounds, BA_STOP);
  _pPowSprite->SetZOrder(3);
  _pPowSprite->SetHidden(true);
  pGE->AddSprite(_pPowSprite);
  _pGuySprites[0] = new Sprite(_pGuyBitmaps[0], rcBounds);
  _pGuySprites[0]->SetPosition(92, 175);
  _pGuySprites[0]->SetZOrder(2);
  _pGuySprites[0]->SetHidden(true);
  pGE->AddSprite(_pGuySprites[0]);
  _pGuySprites[1] = new Sprite(_pGuyBitmaps[1], rcBounds);
  _pGuySprites[1]->SetPosition(301, 184);
  _pGuySprites[1]->SetZOrder(2);
  _pGuySprites[1]->SetHidden(true);
  pGE->AddSprite(_pGuySprites[1]);
  _pGuySprites[2] = new Sprite(_pGuyBitmaps[2], rcBounds);
  _pGuySprites[2]->SetPosition(394, 61);
  _pGuySprites[2]->SetZOrder(2);
  _pGuySprites[2]->SetHidden(true);
  pGE->AddSprite(_pGuySprites[2]);
  rcBounds.x = 340;
  _pGuySprites[3] = new Sprite(_pGuyBitmaps[3], rcBounds, BA_WRAP);
  _pGuySprites[3]->SetNumFrames(4);
  _pGuySprites[3]->SetPosition(500, 10);
  _pGuySprites[3]->SetVelocity(-3, 0);
  _pGuySprites[3]->SetZOrder(1);
  _pGuySprites[3]->SetHidden(true);
  pGE->AddSprite(_pGuySprites[3]);
  rcBounds.x = 385;
  _pGuySprites[4] = new Sprite(_pGuyBitmaps[4], rcBounds, BA_WRAP);
  _pGuySprites[4]->SetNumFrames(4);
  _pGuySprites[4]->SetFrameDelay(5);
  _pGuySprites[4]->SetPosition(260, 60);
  _pGuySprites[4]->SetVelocity(5, 0);
  _pGuySprites[4]->SetZOrder(1);
  _pGuySprites[4]->SetHidden(true);
  pGE->AddSprite(_pGuySprites[4]);

  // Initialize the remaining global variables
  _iGuyMasterDelay = 50;
  _iHits = 0;
  _iMisses = 0;
  _bGameOver = false;
  
  //Load the music
  _mmMusic = Mix_LoadMUS("res/Music.xm");
  if(_mmMusic==nullptr) cout << "Could not play music: " <<  Mix_GetError();

  //Load the sound effetcs
  _mcWhack = Mix_LoadWAV("res/Whack.wav");
  _mcTaunt = Mix_LoadWAV("res/Taunt.wav");
  _mcBoo = Mix_LoadWAV("res/Boo.wav");
  
  // Play the background music
  pGE->PlaySong(_mmMusic);
}
Beispiel #20
0
int main(int argc, char* argv[]) {
    //initialize and loading variables
    char *bgmm[11] = { "l1.mp3", "l2.mp3", "l3.mp3", "l4.mp3", "l5.mp3", "l6.mp3", "l7.mp3", "l8.mp3", "l9.mp3", "l10.mp3", "l11.mp3" };
    char *bv[11] = { "can we live together.wav",
        "can't you just relax do you even remember.wav",
        "chage is good for you.wav",
        "grace and integrity are what define us.wav",
        "how do thrive and grow under pressure.wav",
        "i don't want you to keep going.wav",
        "i know sometimes it feels like you have no controle",
        "i want to help you but you need to let me.wav",
        "is there another way.wav",
        "once an action is done it cannot be undone.wav",
        "push any further and yu will  break.wav" };
    SDL_Color color;
    const point center = { 220.0, 350.0 };
    int currenttick, score=0;
    short circleradius = 44,musicselect=0;
    boolean mainmenu = yes;
    double theta = 0.0,speed=0.09;
    //Uint8 alpha;
    SDL_Renderer *rendertarget = NULL;
    
    SDL_Rect rectangle1 = { 320, 0, 100, 20 }, rectangle2 = { 230, rectangle1.y-80, 100, 20 };
    SDL_Rect littlerectangle1 = { 310, rectangle1.y - 165, 50, 20 };
    SDL_Rect cube1 = { 300, rectangle1.y - 270, 40, 40 }, cube2 = { 310, cube1.y - 90, 40, 40 }, cube3 = { 305, cube2.y - 90, 40, 40 };
    
    SDL_Rect redballposition = { center.x + circleradius*sin(theta), center.y + circleradius*cos(theta), 25, 25 };
    SDL_Rect blueballposition = { center.x - circleradius*sin(theta), center.y - circleradius*cos(theta), 25, 25 };
    
    const Uint8 *keystate;
    SDL_Window *window = NULL;
    SDL_Texture *redball = NULL, *blueball = NULL, *box = NULL; //gametexture
    
    // Initialize SDL2
    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);
    Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 2560);
    Mix_Music *bgm = Mix_LoadMUS("l1.mp3");
    
    Mix_Chunk *voice = Mix_LoadWAV("trust your instincts.wav"), *hitsound = Mix_LoadWAV("Samples/3816133910831170.wav");
    Mix_PlayChannel(2,voice,0);
    Mix_PlayMusic(bgm, -1);
    
    
    
    // Create an application window with the following settings:
    window = SDL_CreateWindow("An SDL2 window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 440, 480, SDL_WINDOW_SHOWN  );
    
    rendertarget = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    box = loadTexture("box.png", rendertarget);
    
    redball = loadTexture("redball.png", rendertarget);
    blueball = loadTexture("bleuball.png", rendertarget);
    
    
    //SDL_SetRenderDrawColor(rendertarget, 0x23, 0x23, 0x23, 0x23);
    SDL_SetRenderDrawColor(rendertarget, 0x99, 0x99, 0xF8, 0x23);
    color.r = 0x99;
    color.g = 0x99;
    color.b = 0xF8;
    color.a = 0x23;
    option select = exitgame;
    //gameloop
    
    boolean gamerunning = yes, programruns = yes;
    SDL_Event e;
    
    while (programruns == yes){
        while (gamerunning == yes && select == startgame){
            
            
            while (SDL_PollEvent(&e)) {
                if (e.type == SDL_QUIT)
                    gamerunning = no;
            };
            srand(time(0));
            
            currenttick = SDL_GetTicks();
            if (e.key.keysym.scancode == SDL_SCANCODE_ESCAPE){
                SDL_RenderClear(rendertarget);
                SDL_RenderPresent(rendertarget);
                //SDL_RenderCopy(rendertarget, gameTitle, NULL, &Gametitleposition);
                //update(gameTitle, Gametitleposition);
                
                SDL_RenderPresent(rendertarget);
                mainmenu = yes;
                break;
                //code to stop game and get back to menu
            }
            keystate = SDL_GetKeyboardState(NULL);
            
            if (keystate[SDL_SCANCODE_LEFT]) {
                theta += speed;
                redballposition.x = center.x + circleradius*sin(theta);
                redballposition.y = center.y + circleradius*cos(theta);
                blueballposition.x = center.x - circleradius*sin(theta);
                blueballposition.y = center.y - circleradius*cos(theta);
            }
            else if (keystate[SDL_SCANCODE_RIGHT]){
                
                theta -= speed;
                redballposition.x = center.x + circleradius*sin(theta);
                redballposition.y = center.y + circleradius*cos(theta);
                blueballposition.x = center.x - circleradius*sin(theta);
                blueballposition.y = center.y - circleradius*cos(theta);
                
            }
            else if (keystate[SDL_SCANCODE_UP]){
                
                
                circleradius += 2;
                redballposition.x = center.x + circleradius*sin(theta);
                redballposition.y = center.y + circleradius*cos(theta);
                blueballposition.x = center.x - circleradius*sin(theta);
                blueballposition.y = center.y - circleradius*cos(theta);
            }
            else if (keystate[SDL_SCANCODE_DOWN]){
                
                circleradius -= 2;
                redballposition.x = center.x + circleradius*sin(theta);
                redballposition.y = center.y + circleradius*cos(theta);
                blueballposition.x = center.x - circleradius*sin(theta);
                blueballposition.y = center.y - circleradius*cos(theta);
            }
            movebox(rectangle1);
            srand(currenttick);
            movebox(rectangle2);
            
            srand(currenttick);
            movebox(littlerectangle1);
            srand(currenttick);
            movebox(cube1);
            srand(currenttick);
            movebox(cube2);
            srand(currenttick);
            movebox(cube3);
            SDL_RenderClear(rendertarget);
            update(redball, redballposition);
            update(blueball, blueballposition);
            update(box, rectangle1);
            update(box, rectangle2);
            update(box, littlerectangle1);
            update(box, cube1);
            update(box, cube2);
            update(box, cube3);
            
            SDL_RenderPresent(rendertarget);
            
            
            
            
            if (aBallhit(rectangle1) || aBallhit(rectangle2) || aBallhit(littlerectangle1) || aBallhit(cube1) || aBallhit(cube2) || aBallhit(cube3)){
                
                Mix_PlayChannel(1, hitsound, 0);
                //reinitialize Game
                
                //rectangle1 = { 220, 0, 100, 20 };
                rectangle1.x= 220;
                rectangle1.y= 0;
                rectangle1.w= 100;
                rectangle1.h= 20;
                //rectangle2 = { 130, rectangle1.y - 80, 100, 20 };
                rectangle2.x= 130;
                rectangle2.y= rectangle1.y - 80;
                rectangle2.w= 100;
                rectangle2.h= 20;
                //littlerectangle1 = { 210, rectangle1.y - 165, 50, 20 };
                littlerectangle1.x= 210;
                littlerectangle1.y= rectangle1.y - 165;
                littlerectangle1.w= 50;
                littlerectangle1.h= 20;
                //cube1 = { 200, rectangle1.y - 270, 40, 40 };
                cube1.x= 200;
                cube1.y= rectangle1.y - 270;
                cube1.w= 40;
                cube1.h= 40;
                //cube2 = { 210, cube1.y - 90, 40, 40 };
                cube2.x= 210;
                cube2.y= cube1.y - 90;
                cube2.w= 40;
                cube2.h= 40;
                //cube3 = { 205, cube2.y - 90, 40, 40 };
                cube3.x= 205;
                cube3.y= cube2.y - 90;
                cube3.w= 40;
                cube3.h= 40;
                
                
                //redballposition = { center.x + circleradius*sin(theta), center.y + circleradius*cos(theta), 25, 25 };
                redballposition.x= center.x + circleradius*sin(theta);
                redballposition.y= center.y + circleradius*cos(theta);
                redballposition.w= 25;
                redballposition.h= 25;
                //blueballposition = { center.x - circleradius*sin(theta), center.y - circleradius*cos(theta), 25, 25 };
                blueballposition.x=  center.x - circleradius*sin(theta);
                blueballposition.y= center.y - circleradius*cos(theta);
                blueballposition.w= 25;
                blueballposition.h= 25;
                
                circleradius = 44;
                gamerunning = yes;
                mainmenu = yes;
                printf("\n your score is: %d", score);
                score = 0;
                Mix_HaltMusic();
                Mix_FreeMusic(bgm);
                if (musicselect == 10)
                    musicselect = 0;
                else
                    musicselect += 1;
                
                bgm = Mix_LoadMUS(bgmm[musicselect]);
                voice = Mix_LoadWAV(bv[musicselect]);
                Mix_PlayMusic(bgm,-1);
                Mix_PlayChannel(2, voice, 0);
                srand(currenttick);
                
                color.b = rand(); srand(currenttick*100);
                color.a = rand(); srand(currenttick*1000);
                color.g = rand(); srand(currenttick*10000);
                color.r = rand();
                
                SDL_SetRenderDrawColor(rendertarget, color.r, color.g, color.b, color.a);
                
                break;
                
                //insert code when collision happens
                
            }
            if (musicselect == 6 ){
                color.b = rand(); srand(currenttick * 100);
                color.r = rand(); srand(currenttick * 1000);
                color.g = rand();
                SDL_SetTextureColorMod(box, color.r, color.g, color.b);
            }
            else if (musicselect == 7){
                //SDL_SetTextureColorMod(box, 0, 0, 0);
            }
            //if (rectangle1.y >= 200){
            //	alpha = 20;
            //	SDL_SetTextureAlphaMod(box,alpha);
            //}
            //else
            //	alpha=100;
            
            if( (notout(redballposition,blueballposition))&&(rectangle1.y == 400 || rectangle2.y == 400 || littlerectangle1.y == 400 || cube1.y == 400 || cube2.y == 400 || cube3.y == 400)){
                score += 1;
                //	printf("\n score = %d", score);
                
                
            }
            
            if (SDL_GetTicks() - currenttick<1000.0 / 60)/*60 FPS*/
            {
                SDL_Delay(1000 / 60 - SDL_GetTicks() + currenttick);
            }
        }
        runmenu(&programruns,&mainmenu,rendertarget,&select);
    }
    // Close and destroy the window
    SDL_DestroyWindow(window);
    
    // Clean up
    SDL_Quit();
    IMG_Quit();
    Mix_Quit();
    SDL_DestroyTexture(redball);
    SDL_DestroyTexture(blueball);
    SDL_DestroyTexture(box);
    
    SDL_DestroyRenderer(rendertarget);
    
    redball = NULL;
    blueball = NULL;
    box = NULL;
    rendertarget = NULL;
    return 0;
}
Beispiel #21
0
/// Load a drumkit
bool DrumKit::Load(const char* kitname, void (*progressCallback)(int, const char *))
{
	char scmd[200], stemp[200];
	FILE *pfile;
	FILE *plog;

	printf("Loading drumkit '%s'...\n", kitname);

	// Init progress display
	progressCallback(0, "Loading drumkit...");

	char kitcfgpath[200];
	strcpy(kitcfgpath, "kits/");
	strcat(kitcfgpath, kitname);
	strcat(kitcfgpath, "/kit.cfg");
	char logpath[200];
	strcpy(logpath, "loadkit.log");			// JH 11/4/2009 - always make dk load log in program folder (dk folder may not exist!)

	if (KIT_DEBUG)
		{
		printf("Drumkit path: %s...\n", kitcfgpath);
		printf("Log file path: %s...\n", logpath);

		plog = fopen(logpath, "w");
		fprintf(plog, "Opening kit config file: %s\n", kitcfgpath);
		fflush(plog);
		}

	pfile = fopen(kitcfgpath, "r");
	// check if file open failed
	if(NULL == pfile)
		{
		if (KIT_DEBUG)
			{
			fprintf(plog, "Failed to open kit config file!\n");
			fclose(plog);
			}
        return false;
		}

	// Reset track info
	Init();

	// Parse kit file
	int lineNumber = 0;
	int numTracksRead = 0;
	bool end = false;
	while(!end)
		{
		// reset valid flags to trap errors
		bool validCmd = false;
		bool validParam = false;

		lineNumber++;
		if (!fgets(scmd, 200, pfile))
			break;
			
		if (KIT_DEBUG)
			fprintf(plog, "Command is %s\n", scmd);
			
		if(scmd[0] == '!' || scmd[0] == '#')
			{
			validCmd = true;
			validParam = true;
			if (KIT_DEBUG)
				fprintf(plog, "Comment encountered. Scanning till eol.\n");
			// read till end of line (character 10)
			fscanf(pfile, "%c", &stemp[0]);
			while(stemp[0] != 10)
				fscanf(pfile, "%c", &stemp[0]);
			}
		
		// track def?
		if(strstr(scmd, "track") == scmd)
			{
			// get param value
			char *param = strchr(scmd, '=');
			if (param)
				{
				param++;
				// get track value (= drum number/index)
				// NB: drum is associated with a "track number", so that
				//     we can have a drumkit with eg 3 drums that load into tracks
				//     1, 4 and 5.
				int trackNum = 0;
				sscanf(scmd+5, "%d", &trackNum);
				if (KIT_DEBUG) printf("Track %d:\n", trackNum);
				if (trackNum >=1 && trackNum <= MAX_DRUMS_PER_KIT)
					{
					numTracksRead++;
					validCmd = true;
					// remove "\n" off end of params
					param[strlen(param)-1] = 0;
					// parse params
					char *sname = strtok(param, "|");
					if (KIT_DEBUG) printf("   Name: %s\n", sname);
					if (sname)
						{
						char *smix = strtok(NULL, "|");
						if (KIT_DEBUG) printf("   Mix: %s\n", smix);
						if (smix)
							{
							char *span = strtok(NULL, "|");
							if (KIT_DEBUG) printf("   Pan: %s\n", span);
							if (span)
								{
								char *sfile = strtok(NULL, "|");
								if (KIT_DEBUG) printf("   File: %s\n", sfile);
								if (sfile)
									{
									// validate params
									validParam = true;
									int mix = atoi(smix);
									if (mix < 0 || mix > 255)
										{
										printf("Bad mix value, line %d\n", lineNumber);
										mix = 200;
										}
									int pan = atoi(span);
									if (pan < 0 || pan > 255)
										{
										printf("Bad pan value, line %d\n", lineNumber);
										pan = 128;
										}
									// text sample path
									char samplePath[200];
									strcpy(samplePath, "kits/");
									strcat(samplePath, kitname);
									strcat(samplePath, "/");
									strcat(samplePath, sfile);
									if (KIT_DEBUG) printf("samplepath: %s\n", samplePath);
									/*
									FILE* pf = fopen(samplePath, "rb");
									if (pf)
										fclose(pf);
									else
										printf("Bad sample filename, line %d\n", lineNumber);
									*/
									// set trackinfo
									int i = trackNum - 1;
									drums[i].vol = mix;
									drums[i].pan = pan;
									// TODO : safe name copy
									strcpy_s(drums[i].name, sname);
									// Load sample
									if (drums[i].sampleData)
										Mix_FreeChunk(drums[i].sampleData);
									drums[i].sampleData = Mix_LoadWAV(samplePath);
									if (KIT_DEBUG) printf("sampledata: %X\n", (unsigned int)drums[i].sampleData);

									// update progress bar
									progressCallback(trackNum * 10, "Loading drumkit...");
									}
								}
							}
						}
					}
				else
					{
	        		if (KIT_DEBUG)
	        			fprintf(plog, "Error - bad track number on line %d\n", lineNumber);
					}
				}
			else
				{
				if (KIT_DEBUG)
					fprintf(plog, "Error - bad parameter on line %d\n", lineNumber);
				}
				
				
			}	// end if track def

		// drumkit name?
		if(strstr(scmd, "name") == scmd)
			{
			validCmd = true;
			// get param value
			char *param = strchr(scmd, '=');
			if (param)
				{
				param++;
				// remove "\n" off end of param
				param[strlen(param)-1] = 0;
				if (strlen(param) > 0)
					{
					validParam = true;
					if (strlen(param) > 31)
						param[DRUMKIT_NAME_LEN - 1] = 0;
					strcpy(this->name, param);
					}
				}
			}

		if (!validCmd)
			{
			printf("Bad command on line %d\n", lineNumber);
			if (KIT_DEBUG)
				fprintf(plog, "Bad command on line %d\n", lineNumber);
			}

		if (!validParam)
			{
			printf("Bad parameter on line %d\n", lineNumber);
			if (KIT_DEBUG)
				fprintf(plog, "Bad parameter on line %d\n", lineNumber);
			}

		// check if EOF before end
		if (feof(pfile))
			end = true;
		}

	fclose(pfile);

	if (KIT_DEBUG)
		fclose(plog);
	
	return true;
}
Beispiel #22
0
void load_sounds()
{
	drum_sounds[0] = Mix_LoadWAV("sounds/snarel.ogg");
	drum_sounds[1] = Mix_LoadWAV("sounds/snarer.ogg");
	drum_sounds[2] = Mix_LoadWAV("sounds/hihat.ogg");
	drum_sounds[3] = Mix_LoadWAV("sounds/hihatc.ogg");
	drum_sounds[4] = Mix_LoadWAV("sounds/hihatp.ogg");
	drum_sounds[5] = Mix_LoadWAV("sounds/bdrum.ogg");
	drum_sounds[6] = Mix_LoadWAV("sounds/crash.ogg");
	drum_sounds[7] = Mix_LoadWAV("sounds/chcrash.ogg");
	drum_sounds[8] = Mix_LoadWAV("sounds/splash.ogg");
	drum_sounds[9] = Mix_LoadWAV("sounds/ltom.ogg");
	drum_sounds[10] = Mix_LoadWAV("sounds/mtom.ogg");
	drum_sounds[11] = Mix_LoadWAV("sounds/htom.ogg");
	drum_sounds[12] = Mix_LoadWAV("sounds/ride.ogg");
	drum_sounds[13] = Mix_LoadWAV("sounds/stsnare.ogg");
}
Beispiel #23
0
void SoundInit(void)
{
#ifndef NOSOUND
		unsigned char  i;
		int  ret;
		char buf[128];
		 

#ifdef DREAMCAST
		SoundEnable = TRUE;
		snd_stream_init();
		sndoggvorbis_init();
		  
		for(i=0;i<9;i++)
		{
			snprintf(buf, sizeof(buf), "/rd/se0%d.wav", i);
			SEPool[i] = snd_sfx_load(buf); 
		}

		for(i=0;i<5;i++)
		{
			snprintf(buf, sizeof(buf), "/rd/bgm00%d.ogg", i);
			snprintf(BGMPool[i], sizeof(BGMPool[i]), "%s", buf);
		}
#else
		
		track = 0;

		SoundEnable = TRUE;
		ret = Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, AUDIO_S16, MIX_DEFAULT_CHANNELS, 1024);
		if (ret != 0) 
		{
			SoundEnable = FALSE;
			return;
		}
		
		for(i=0; i<8; i++) 
		{
			Mix_Volume(i, VOLUMEDEFAULT);
		}
		
		Mix_VolumeMusic(VOLUMEDEFAULT);

		for(i=0; i<BGMMAX; i++) 
		{
			BGMPool[i][0] = 0;
		}
		
		for(i=0; i<SEMAX; i++) 
		{
			SEPool[i] = 0;
		}
	  
	#ifdef NO_SNPRINTF
		for(i=0;i<5;i++)
		{
			sprintf(buf, "./data/bgm00%d.ogg", i);
			sprintf(BGMPool[i], "%s", buf);
		}
		  
		for(i=0;i<9;i++)
		{
			sprintf(buf, "./data/se0%d.wav", i);
			SEPool[i] = Mix_LoadWAV(buf);
		}
	#else
		for(i=0;i<5;i++)
		{
			snprintf(buf, sizeof(buf), "./data/bgm00%d.ogg", i);
			snprintf(BGMPool[i], sizeof(BGMPool[i]), "%s", buf);
		}
		  
		for(i=0;i<9;i++)
		{
			snprintf(buf, sizeof(buf), "./data/se0%d.wav", i);
			SEPool[i] = Mix_LoadWAV(buf);
		}
	#endif
	
#endif
		
#endif	//NOSOUND
}
Beispiel #24
0
int main(int argc, char *argv[])
{
	
	ShaderProgram program = setup();
	Mix_Music *music;
	music = Mix_LoadMUS("Dream Land.mp3");
	Mix_FadeInMusic(music, -1, 1000);
	Mix_Chunk *someSound;
	someSound = Mix_LoadWAV("Shell Hit 2.wav");
	Mix_Chunk *someSound2;
	someSound2 = Mix_LoadWAV("Bumper Hit.wav");
	Mix_Chunk *cheer;
	cheer = Mix_LoadWAV("Crowd Cheering.wav");
	Matrix paddle_left_matrix;
	Matrix paddle_right_matrix;
	Matrix ball_matrix;
	Matrix view_matrix;
	Matrix projection_matrix;

	GLuint chartreuse_texture_ID = load_texture_rgb("purple-suede.jpg");

	projection_matrix.setOrthoProjection(-3.55f, 3.55f, -2.0f, 2.0f, -1.0f, 1.0f);

	SDL_Event event;
	bool done = false;
	bool game_started = false;

	float lastFrameTicks = 0.0f;

	Paddle paddle_left(-3.5f, -3.4f, 0.5f, -0.5f);
	Paddle paddle_right(3.4f, 3.5f, 0.5f, -0.5f);
	Ball ball(0.0f, 0.0f, 0.05f, 0.0025f, (float)rand(), (float)rand());
	
	while (!done)
	{
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

		//Controls for the game
		while (SDL_PollEvent(&event))
		{
			if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE)
				done = true;
			if (event.type == SDL_KEYDOWN)
			{
				// left paddle
				if (event.key.keysym.scancode == SDL_SCANCODE_W)
				{
					if (paddle_left.top < 2.0f){
						paddle_left.top += 0.3f;
						paddle_left.bottom += 0.3f;
						paddle_left_matrix.Translate(0.0f, 0.3f, 0.0f);
					}
				}
				if (event.key.keysym.scancode == SDL_SCANCODE_S)
				{
					if (paddle_left.bottom > -2.0f){
						paddle_left.top -= 0.3f;
						paddle_left.bottom -= 0.3f;
						paddle_left_matrix.Translate(0.0f, -0.3f, 0.0f);
					}
				}

				// right paddle
				if (event.key.keysym.scancode == SDL_SCANCODE_UP)
				{
					if (paddle_right.top < 2.0f){
						paddle_right.top += 0.3f;
						paddle_right.bottom += 0.3f;
						paddle_right_matrix.Translate(0.0f, 0.3f, 0.0f);
					}
				}
				if (event.key.keysym.scancode == SDL_SCANCODE_DOWN)
				{
					if (paddle_right.bottom > -2.0f){
						paddle_right.top -= 0.3f;
						paddle_right.bottom -= 0.3f;
						paddle_right_matrix.Translate(0.0f, -0.3f, 0.0f);
					}
				}

				if (event.key.keysym.scancode == SDL_SCANCODE_SPACE || event.key.keysym.scancode == SDL_SCANCODE_RETURN)
				{
					if (!game_started)
						game_started = true;
				}
			}
		}
		float ticks = (float)SDL_GetTicks() / 1000.0f;
		float elapsed = ticks - lastFrameTicks;
		lastFrameTicks = ticks;
		glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT);

		program.setModelMatrix(paddle_left_matrix);
		program.setViewMatrix(view_matrix);
		program.setProjectionMatrix(projection_matrix);

		glUseProgram(program.programID);

		float texture_coords[] = { 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f }; // global texture coordinates

		// left paddle
		float paddle_left_coords[] = { -3.5f, -0.5f, -3.4f, -0.5f, -3.4f, 0.5f, -3.4f, 0.5f, -3.5f, 0.5f, -3.5f, -0.5f };
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, paddle_left_coords);
		glEnableVertexAttribArray(program.positionAttribute);
		glDrawArrays(GL_TRIANGLES, 0, 6);

		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texture_coords);
		glEnableVertexAttribArray(program.texCoordAttribute);
		glBindTexture(GL_TEXTURE_2D, chartreuse_texture_ID);

		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);

		// right paddle
		program.setModelMatrix(paddle_right_matrix);
		float paddle_right_coords[] = { 3.4f, -0.5f, 3.5f, -0.5f, 3.5f, 0.5f, 3.5f, 0.5f, 3.4f, 0.5f, 3.4f, -0.5f };
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, paddle_right_coords);
		glEnableVertexAttribArray(program.positionAttribute);
		glDrawArrays(GL_TRIANGLES, 0, 6);

		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texture_coords);
		glEnableVertexAttribArray(program.texCoordAttribute);
		glBindTexture(GL_TEXTURE_2D, chartreuse_texture_ID);

		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);

		// ball
		program.setModelMatrix(ball_matrix);
		float ball_coords[] = { -0.1f, -0.1f, 0.1f, -0.1f, 0.1f, 0.1f, 0.1f, 0.1f, -0.1f, 0.1f, -0.1f, -0.1f };
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, ball_coords);
		glEnableVertexAttribArray(program.positionAttribute);
		glDrawArrays(GL_TRIANGLES, 0, 6);

		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texture_coords);
		glEnableVertexAttribArray(program.texCoordAttribute);
		glBindTexture(GL_TEXTURE_2D, chartreuse_texture_ID);

		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);


		if (game_started)
		{
			//Mix_Chunk *start;
			//start = Mix_LoadWAV("Start.wav");
			//Mix_PlayChannel(-1, start, 0);
			

			// right wins
			if (ball.position_x - 0.1f <= paddle_left.left)
			{
				
				Mix_PlayChannel(-1, cheer, 0);
				
				game_started = false;
				ball_matrix.Translate(-ball.position_x, -ball.position_y, 0.0f);
				ball.position_x = 0.0f; // for some reason reset() doesn't work :-(
				ball.position_y = 0.0f;
				ball.direction_x = (float)rand() / (float)RAND_MAX;
				ball.direction_y = (float)rand() / (float)RAND_MAX;
				ball.speed = 0.0009f;
				std::cout << "Right player wins!\n"; 

			}

			// left wins
			else if (ball.position_x + 0.1f >= paddle_right.right)
			{


				
				game_started = false;
				ball_matrix.Translate(-ball.position_x, -ball.position_y, 0.0f);
				ball.position_x = 0.0f;
				ball.position_y = 0.0f;
				ball.direction_x = (float)rand() / (float)RAND_MAX;
				ball.direction_y = (float)rand() / (float)RAND_MAX;
				ball.speed = 0.0009f;
				if (ball.skip > 0)
				{
					Mix_PlayChannel(-1, cheer, 0);
					std::cout << "Left player wins!\n";
				}
				ball.skip++;
			}

			// hits top or bottom of screen
			else if (ball.position_y + 0.1f >= 2.0f || ball.position_y - 0.1f <= -2.0f)
			{
				
				Mix_PlayChannel(-1, someSound, 0);
				ball.direction_y *= -1;
				if (ball.speed < ball.max_speed)
				{
					ball.speed += ball.acceleration;
				}
				ball.move();
				ball_matrix.Translate(ball.speed * ball.direction_x, ball.speed * ball.direction_y, 0.0f);
			}

			// hits a paddle
			else if ((ball.position_x - 0.1f <= paddle_left.right && ball.position_y - 0.1f <= paddle_left.top && ball.position_y + 0.1f >= paddle_left.bottom) ||
				(ball.position_x + 0.1f >= paddle_right.left && ball.position_y - 0.1f <= paddle_right.top && ball.position_y + 0.1f >= paddle_right.bottom))
			{
				
				Mix_PlayChannel(-1, someSound2, 0);
				ball.direction_x *= -1;
				ball.speed += ball.acceleration;
				ball.move();
				ball_matrix.Translate((ball.speed * ball.direction_x), (ball.speed * ball.direction_y), 0.0f);
			}

			// general movement
			else
			{
				ball.move();
				ball_matrix.Translate((ball.speed * ball.direction_x), (ball.speed * ball.direction_y), 0.0f);
			}


		}
		
		
		SDL_GL_SwapWindow(displayWindow);
	}

	Mix_FreeChunk(someSound);
	Mix_FreeChunk(someSound2);
	Mix_FreeChunk(cheer);

	Mix_FreeMusic(music);
	SDL_Quit();
	return 0;
}
Beispiel #25
0
void SoundManager::loadExplosionSound(const char * filename)
{
	this->explosionSound = Mix_LoadWAV(filename);
}
Beispiel #26
0
//Does a countdown before the start of the race
void Application::loadingScreen(SDL_Renderer* gRenderer, LTexture& timeTexture, SDL_Color& textColor, Car &car)
{
    LTexture one, two, three;

    if (!one.loadFromFile("img/One.png", gRenderer))
    {
        printf("Failed to load one.png !\n");
    }
    if (!two.loadFromFile("img/Two.png", gRenderer))
    {
        printf("Failed to load two.png!\n");
    }
    if (!three.loadFromFile("img/Three.png", gRenderer))
    {
        printf("Failed to load three.png !\n");
    }

    Mix_HaltMusic();
    beep = Mix_LoadWAV("sounds/beep.wav");
    go = Mix_LoadWAV("sounds/go.wav");
    if (beep == NULL)
    {
        printf("Failed to load beep.wav !\n");
    }
    if (go == NULL)
    {
        printf("Failed to load go.wav !\n");
    }

    for (int i = 3; i > 0; i--)
    {
        //Clear screen
        SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
        SDL_RenderClear(gRenderer);

        gBackgroundTexture.render(*gRenderer, 0, 0);
        renderMusicButton();
        switch (i)
        {
        case 1:
            one.render(*gRenderer, 0, 0);
            break;
        case 2:
            two.render(*gRenderer, 0, 0);
            break;
        case 3:
            three.render(*gRenderer, 0, 0);
            break;
        }

        timeTexture.loadFromRenderedText(timer(gameData.getTime()), textColor, *gRenderer);
        car.render(gCarTexture, gSpeedMeter, gSpeedMeterClips, *gRenderer);
        timeTexture.render(*gRenderer, 620, 10);

        if (isMusicOn)
        {
            Mix_PlayChannel(-1, beep, 0);
        }
        SDL_RenderPresent(gRenderer);
        SDL_Delay(1000);
    }
    if (isMusicOn)
    {
        Mix_PlayChannel(-1, go, 0);
    }
}
Beispiel #27
0
void Audio::loadSounds() {
    sons = new Mix_Chunk*[44];

    sons[0] = Mix_LoadWAV("data/sound/text.ogg"); // lettres
    sons[1] = Mix_LoadWAV("data/sound/menu1.ogg"); // menu 1
    sons[2] = Mix_LoadWAV("data/sound/menu2.ogg"); // menu 2
    sons[3] = Mix_LoadWAV("data/sound/menu3.ogg"); // menu 3
    sons[4] = Mix_LoadWAV("data/sound/menu4.ogg"); // menu 4
    sons[5] = Mix_LoadWAV("data/sound/timewarp.ogg"); // time retour
    sons[6] = Mix_LoadWAV("data/sound/tombe.ogg"); // tombe (ennemi)
    sons[7] = Mix_LoadWAV("data/sound/hitenemy.ogg"); //shot 1
    sons[8] = Mix_LoadWAV("data/sound/killenemy.ogg"); // shot 2
    sons[9] = Mix_LoadWAV("data/sound/surprise.ogg"); // surprise
    sons[10] = Mix_LoadWAV("data/sound/monte.ogg"); // monte
    sons[11] = Mix_LoadWAV("data/sound/descend.ogg"); // descend
    sons[12] = Mix_LoadWAV("data/sound/chute.ogg"); // chute
    sons[13] = Mix_LoadWAV("data/sound/item.ogg"); // item
    sons[14] = Mix_LoadWAV("data/sound/rupee.ogg"); // rubis
    sons[15] = Mix_LoadWAV("data/sound/heart.ogg"); // coeur
    sons[16] = Mix_LoadWAV("data/sound/bomb.ogg"); // bombe
    sons[17] = Mix_LoadWAV("data/sound/textnext.ogg"); // suite texte
    sons[18] = Mix_LoadWAV("data/sound/textend.ogg"); // fin texte
    sons[19] = Mix_LoadWAV("data/sound/happy.ogg"); // trouve objet
    sons[20] = Mix_LoadWAV("data/sound/door.ogg"); // ouvre porte
    sons[21] = Mix_LoadWAV("data/sound/pics.ogg"); // pics contre mur
    sons[22] = Mix_LoadWAV("data/sound/sword.ogg"); // Epée
    sons[23] = Mix_LoadWAV("data/sound/SwordCharging.ogg"); // chargée
    sons[24] = Mix_LoadWAV("data/sound/Sword360.ogg"); // spin
    sons[25] = Mix_LoadWAV("data/sound/shoot.ogg"); // flèche
    sons[26] = Mix_LoadWAV("data/sound/hookshot.ogg"); // grappin
    sons[27] = Mix_LoadWAV("data/sound/stamp.ogg"); // pose bombe
    sons[28] = Mix_LoadWAV("data/sound/magic.ogg"); // magie
    sons[29] = Mix_LoadWAV("data/sound/burn.ogg"); // brËšle
    sons[30] = Mix_LoadWAV("data/sound/hammer.ogg"); // marteau
    sons[31] = Mix_LoadWAV("data/sound/plouf.ogg"); // plouf
    sons[32] = Mix_LoadWAV("data/sound/danger.ogg"); // danger
    sons[33] = Mix_LoadWAV("data/sound/hurt.ogg"); // link se blesse
    sons[34] = Mix_LoadWAV("data/sound/porte.ogg"); // porte objet
    sons[35] = Mix_LoadWAV("data/sound/lance.ogg"); // lance objet
    sons[36] = Mix_LoadWAV("data/sound/casse.ogg"); // casse objet
    sons[37] = Mix_LoadWAV("data/sound/charge.ogg"); // charge magie
    sons[38] = Mix_LoadWAV("data/sound/buisson.ogg"); // coupe buisson
    sons[39] = Mix_LoadWAV("data/sound/pousse.ogg"); // pousse caisse
	sons[40] = Mix_LoadWAV("data/sound/envol.ogg"); // chant envol
    sons[41] = Mix_LoadWAV("data/sound/inverse.ogg"); // hymne vide
    sons[42] = Mix_LoadWAV("data/sound/accelere.ogg"); // chant esprit
    sons[43] = Mix_LoadWAV("data/sound/splash.ogg"); // ...
}
Beispiel #28
0
void setup (void) {
	SDL_Surface * image;
	TTF_Font *temp1, *temp2;
	SDL_Color color;
	SDL_Rect rect, rect2;
	int g;
	char buffer_file[8192];
	char *systemdata_path = get_systemdata_path ();
	
	/* Inicializar el Video SDL */
	if (SDL_Init(SDL_INIT_VIDEO) < 0) {
		fprintf (stderr,
			_("Error: Can't initialize the video subsystem\n"
			"The error returned by SDL is:\n"
			"%s\n"), SDL_GetError());
		exit (1);
	}
	sprintf (buffer_file, "%simages/icon.png", systemdata_path);
	image = IMG_Load (buffer_file);
	if (image) {
		SDL_WM_SetIcon (image, NULL);
		SDL_FreeSurface (image);
	}
	SDL_WM_SetCaption (_("Paddle Puffle"), _("Paddle Puffle"));
	
	/* Crear la pantalla de dibujado */
	screen = set_video_mode (0);
	
	if (screen == NULL) {
		fprintf (stderr,
			_("Error: Can't setup 760x480 video mode.\n"
			"The error returned by SDL is:\n"
			"%s\n"), SDL_GetError());
		exit (1);
	}
	
	use_sound = 1;
	if (SDL_InitSubSystem (SDL_INIT_AUDIO) < 0) {
		fprintf (stdout,
			_("Warning: Can't initialize the audio subsystem\n"
			"Continuing...\n"));
		use_sound = 0;
	}
	
	if (use_sound) {
		/* Inicializar el sonido */
		if (Mix_OpenAudio (22050, AUDIO_S16, 2, 4096) < 0) {
			fprintf (stdout,
				_("Warning: Can't initialize the SDL Mixer library\n"));
			use_sound = 0;
		}
	}
	
	for (g = 0; g < NUM_IMAGES; g++) {
		sprintf (buffer_file, "%s%s", systemdata_path, images_names[g]);
		image = IMG_Load (buffer_file);
		
		if (image == NULL) {
			fprintf (stderr,
				_("Failed to load data file:\n"
				"%s\n"
				"The error returned by SDL is:\n"
				"%s\n"), buffer_file, SDL_GetError());
			SDL_Quit ();
			exit (1);
		}
		
		images[g] = image;
		/* TODO: Mostrar la carga de porcentaje */
	}
	
	/* Pre-Dibujar la pantalla gris */
	grey_screen = SDL_CreateRGBSurface (SDL_SWSURFACE | SDL_SRCALPHA, 760, 480, 32, 0, 0, 0, 0);
	SDL_FillRect (grey_screen, NULL,
	              SDL_MapRGB (grey_screen->format, 0, 0, 0)); /* Negro */
	SDL_SetAlpha (grey_screen, SDL_SRCALPHA, 128); /* Alpha al 50 % */
	
	if (use_sound) {
		for (g = 0; g < NUM_SOUNDS; g++) {
			sprintf (buffer_file, "%s%s", systemdata_path, sound_names[g]);
			sounds[g] = Mix_LoadWAV (buffer_file);
			
			if (sounds[g] == NULL) {
				fprintf (stderr,
					_("Failed to load data file:\n"
					"%s\n"
					"The error returned by SDL is:\n"
					"%s\n"), buffer_file, SDL_GetError ());
				SDL_Quit ();
				exit (1);
			}
			Mix_VolumeChunk (sounds[g], MIX_MAX_VOLUME / 2);
		}
		
		/* Cargar la música */
		sprintf (buffer_file, "%s%s", systemdata_path, MUS_CARNIE);
		mus_carnie = Mix_LoadMUS (buffer_file);
		
		if (mus_carnie == NULL) {
			fprintf (stderr,
				_("Failed to load data file:\n"
				"%s\n"
				"The error returned by SDL is:\n"
				"%s\n"), buffer_file, SDL_GetError ());
			SDL_Quit ();
			exit (1);
		}
		
	}
	
	if (TTF_Init () < 0) {
		fprintf (stderr,
			_("Error: Can't initialize the SDL TTF library\n"
			"%s\n"), TTF_GetError ());
		SDL_Quit ();
		exit (1);
	}
	
	/* Tipografias 10, 14, 16, 26 */
	sprintf (buffer_file, "%s%s", systemdata_path, "ccfacefront.ttf");
	ttf_facefront = SDL_RWFromFile (buffer_file, "rb");
	
	if (ttf_facefront == NULL) {
		fprintf (stderr,
			_("Failed to load font file 'CCFaceFront'\n"
			"The error returned by SDL is:\n"
			"%s\n"), TTF_GetError ());
		SDL_Quit ();
		exit (1);
	}
	
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	temp1 = TTF_OpenFontRW (ttf_facefront, 0, 10);
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf14_normal = TTF_OpenFontRW (ttf_facefront, 0, 14);
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf16_normal = TTF_OpenFontRW (ttf_facefront, 0, 16);
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf26_normal = TTF_OpenFontRW (ttf_facefront, 0, 26);
	
	if (!temp1 || !ttf14_normal || !ttf16_normal || !ttf26_normal) {
		SDL_Quit ();
		exit (1);
	}
	
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf20_normal = TTF_OpenFontRW (ttf_facefront, 0, 20);
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf20_outline = TTF_OpenFontRW (ttf_facefront, 0, 20);
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf16_outline = TTF_OpenFontRW (ttf_facefront, 1, 16);
	
	if (!ttf20_normal || !ttf20_outline || !ttf16_outline) {
		SDL_Quit ();
		exit (1);
	}
	
	TTF_SetFontStyle (temp1, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf14_normal, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf16_normal, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf26_normal, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf16_outline, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf20_outline, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf20_normal, TTF_STYLE_ITALIC);
	
	TTF_SetFontOutline (ttf16_outline, OUTLINE_TEXT);
	TTF_SetFontOutline (ttf20_outline, OUTLINE_TEXT);
	
	/* Generar textos */
	bind_textdomain_codeset (PACKAGE, "UTF-8");
	color.r = color.g = color.b = 0; /* Negro */
	
	for (g = 0; g < NUM_TEXTS; g++) {
		switch (text_info [g]) {
			case 10: temp2 = temp1; break;
			case 14: temp2 = ttf14_normal; break;
			case 16: temp2 = ttf16_normal; break;
			case 26: temp2 = ttf26_normal; break;
			default: temp2 = ttf16_normal;
		}
		
		texts[g] = draw_text (temp2, _(text_strings[g]), &color);
	}
	
	/* Copiar la palabra "Tickets" en el background */
	/* También copiar el nombre del juego al titulo y al fondo */
	rect.x = 607 + ((135 - texts[TEXT_TICKETS]->w) / 2); rect.y = 38;
	rect.w = texts[TEXT_TICKETS]->w; rect.h = texts[TEXT_TICKETS]->h;
	rect2.x = 191; rect2.y = 96;
	rect2.w = images[IMG_TITLE]->w; rect2.h = images[IMG_TITLE]->h;
	for (g = IMG_BACKGROUND_NORMAL; g <= IMG_BACKGROUND_FAIL_1; g++) {
		SDL_BlitSurface (texts[TEXT_TICKETS], NULL, images[g], &rect);
		SDL_BlitSurface (images[IMG_TITLE], NULL, images[g], &rect2);
	}
	
	/* X = 84.35, Y = 50.85 */
	rect2.x = 84; rect2.y = 51;
	SDL_BlitSurface (images[IMG_TITLE], NULL, images[IMG_TITLE_OPENING], &rect2);
	
	TTF_CloseFont (temp1);
	/* Generador de números aleatorios */
	srand ((unsigned int) getpid ());
}
Beispiel #29
0
Mix_Chunk *Utils::LoadSound(char *snd)
{
	char fn[256];
	sprintf(fn, "%s%s%s", oslink.soundDir, oslink.pathSep, snd);
	return Mix_LoadWAV(fn);
}
Beispiel #30
0
void OptionsMenu::initFonts()
{
	TextOptions normalOptions;
	normalOptions.fontPath = "Flappy.ttf";
	normalOptions.fontSize = 32;
	normalOptions.color =  Vector3::one;
	normalOptions.placement = CENTER;
	normalOptions.borderSize = 2;
	normalOptions.borderColor = Vector3::fromRGB(40, 100, 30);

	// volver
	normalOptions.text = "Volver";
	normalOptions.offsetX = 0;
	normalOptions.offsetY = 220;
	Text backTextNormal = Text(normalOptions);	
	// volver -- hover
	TextOptions hoverOptions = normalOptions;
	hoverOptions.fontSize = 36;
	hoverOptions.color =  Vector3::fromRGB(236, 218, 19);
	hoverOptions.text = "Volver";
	Text backTextHover = Text(hoverOptions);
	Mix_Chunk *menuTick = Mix_LoadWAV("MenuTick.wav");
	if(!menuTick) {
		Logger::logSDLError("Mix_LoadWAV");
	}
	backText = new TextHover(backTextNormal, backTextHover, menuTick);
	addObject(backText);

	// velocidad de juego
	normalOptions.offsetY = hoverOptions.offsetY = -60;
	gameSpeedText = new TextSwitchHover(
		normalOptions, hoverOptions, menuTick,
		"Velocidad de Juego: Media", "Velocidad de Juego: Alta", "Velocidad de Juego: Baja", NULL
		);
	addObject(gameSpeedText);

	// interpolado
	normalOptions.offsetY = hoverOptions.offsetY +=  40;
	interpolatedText = new TextSwitchHover(
		normalOptions, hoverOptions, menuTick,
		"Renderizado interpolado", "Renderizado liso",  NULL
		);
	addObject(interpolatedText);

	// texturas
	normalOptions.offsetY = hoverOptions.offsetY += 40;
	texturedText = new TextSwitchHover(
		normalOptions, hoverOptions, menuTick,
		"Texturas habilitadas", "Texturas deshabilitadas",  NULL
		);
	addObject(texturedText);

	// texturas
	normalOptions.offsetY = hoverOptions.offsetY += 40;
	useVSyncText = new TextSwitchHover(
		normalOptions, hoverOptions, menuTick,
		"VSync Activado", "VSync Desactivado",  NULL
		);
	addObject(useVSyncText);

	// wireframe
	normalOptions.offsetY = hoverOptions.offsetY += 40;
	wireframeText = new TextSwitchHover(
		normalOptions, hoverOptions, menuTick,
		"Modo alambre desactivado", "Modo alambre activado",  NULL
		);
	addObject(wireframeText);

	// color de luz
	normalOptions.offsetY = hoverOptions.offsetY += 40;
	lightColorText = new TextSwitchHover(
		normalOptions, hoverOptions, menuTick,
		"Luz blanca", "Luz roja", "Luz psicodelica", "Luz desactivada",  NULL
		);
	addObject(lightColorText);

	// posición de luz
	normalOptions.offsetY = hoverOptions.offsetY += 40;
	lightDirectionText = new TextSwitchHover(
		normalOptions, hoverOptions, menuTick,
		"Luz de frente", "Luz de arriba", "Luz de derecha", "Luz de atras",  NULL
		);
	addObject(lightDirectionText);

	addObject(mainMenu.getVersionText());
	//addObject(mainMenu.getCopyrightText());
}