Example #1
0
void CUIFrags2::Init(CUIXml& xml_doc, LPCSTR path, LPCSTR backgrnd_path){
	InitBackground(xml_doc, backgrnd_path);

	CUIWindow* pTeam1 = NULL;
	CUIWindow* pTeam2 = NULL;
	Fvector2 pos;

	pTeam1 = m_pStats->InitStats(xml_doc, path, 1);
	AttachChild(pTeam1);
	pTeam2 = m_pStats2->InitStats(xml_doc, path, 2);
	AttachChild(pTeam2);

    // team 2 list
	float x = xml_doc.ReadAttribFlt(path, 0, "x2");
	R_ASSERT(x);
	pos = m_pStats2->GetWndPos();
	pos.x = x;				// 
	pos.y += 3;	
	m_pStats2->SetWndPos(pos);
	// team2 statas
	pos = pTeam2->GetWndPos();
	pos.x += m_pStats2->GetWndPos().x;
	pTeam2->SetWndPos(pos);

    // team 1 list
	pos = m_pStats->GetWndPos();
	pos.y += 3;
	m_pStats->SetWndPos(pos);

	pos = pTeam1->GetWndPos();
	pos.x += m_pStats->GetWndPos().x;
	pTeam1->SetWndPos(pos);
	

}
Example #2
0
int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason,
                         void* lpReserved)
{
    switch( reason )
    {
    case DLL_PROCESS_ATTACH:
        InitBackground();
        break;
    case DLL_PROCESS_DETACH:
        FreeBMGImage( GetBackgroundImage() );
        break;
    }

    return 1;
}
Example #3
0
/** State - Start game */
void StateStartGame()
{
	game.page = 0;
	SetPage8(game.page);
	game.yOffset = 0;

	SetScreenColor(0, 0, BG_COLOR);
	ClearScreen8(BG_COLOR);

	game.bAnaglyph = TRUE;
	switch(game.anaglyphFx)
	{
		case 0:	game.bAnaglyph = FALSE; break;
		case 1:	game.power3d = 4; break;
		case 2: game.power3d = 8; break;
		case 3: game.power3d = 12; break;
	}
	switch(game.gameSpeed)
	{
		case 0: game.ballSpeed = 10; break;
		case 1: game.ballSpeed = 15; break;
		case 2: game.ballSpeed = 20; break;
	}

	game.page = 0;
	game.yOffset = 0;
	InitBackground();
	game.lineNum[0] = 0;
	game.lineNum[1] = 0;
	game.bestScore = 0;

	// Player 0
	game.players[0].score = 0;
	VEC_SET(game.players[0].position, F10_SET(50), F10_SET(50), F10_SET(0));
	game.players[0].angle = 0;

	// Player 1
	game.players[1].score = 0;
	VEC_SET(game.players[1].position, F10_SET(-50), F10_SET(-50), F10_SET(FIELD_DEPTH));
	game.players[1].angle = 0;

	// Ball
	VEC_SET(game.ballPos, 0, 0, F10_SET(128));
	VEC_SET(game.ballDir, 0, 0, F10_SET(game.ballSpeed));

	game.state = StateUpdateGame;
}
Example #4
0
void PrimeBackground() {
	// structure for playfields
	// FIXME: Avoid non-const global vars
	// TODO: We should simply merge this function with InitBackground
	//   in order to avoid the static var and the problems associate
	//   with it.
	static PLAYFIELD playfield[] = {
		{	// FIELD WORLD
			NULL,		// display list
			0,			// init field x
			0,			// init field y
			0,			// x vel
			0,			// y vel
			Common::Rect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT),	// clip rect
			false		// moved flag
		},
		{	// FIELD STATUS
			NULL,		// display list
			0,			// init field x
			0,			// init field y
			0,			// x vel
			0,			// y vel
			Common::Rect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT),	// clip rect
			false		// moved flag
		}
	};

	// structure for background
	static const BACKGND backgnd = {
		BLACK,			// sky colour
		Common::Point(0, 0),	// initial world pos
		Common::Rect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT),	// scroll limits
		0,				// no background update process
		NULL,			// no x scroll table
		NULL,			// no y scroll table
		2,				// 2 playfields
		playfield,		// playfield pointer
		false			// no auto-erase
	};

	InitBackground(&backgnd);
}
Example #5
0
void InitGame( char* ScreenName, int Width, int Height )
{
    LGame.Window = SDL_CreateWindow( ScreenName, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, Width, Height, SDL_WINDOW_SHOWN );
    if( LGame.Window )
    {
        LGame.Renderer =  SDL_CreateRenderer( LGame.Window, -1, SDL_RENDERER_ACCELERATED );
        if( LGame.Renderer )
        {
            LGame.Surface = SDL_GetWindowSurface( LGame.Window );
            if( LGame.Surface )
            {
                if( IMG_Init( IMG_INIT_PNG ) )
                {
                    LGame.ScreenWidth = Width;
                    LGame.ScreenHeight = Height;
                    InitBackground( );
                    InitPlayer( );
                    LGame.Gravity = 4.25f;
                    LGame.bRunning = true;
                    MainLoop( );   
                }
                else
                {
                    printf( "Failed to init IMG %s\n", IMG_GetError( ) );
                }
            }
            else
            {
                printf( "Failed to create surface %s\n", SDL_GetError( ) );
            }
        }
        else
        {
            printf( "Failed to create renderer %s\n", SDL_GetError( ) );
        }
    }
    else
    {
        printf( "Failed to Create window %s\n", SDL_GetError( ) );
    }
}
Example #6
0
/****** Initial ********************************************************
 *
 * Initialize LCD Screen (PMP + configuration + initial display).
 * Initialize Timer5 for a loop time of 10 ms.
 **********************************************************************/
void Initial()
{
   AD1PCFGL = 0xFFFF;            // Make all ADC pins default to digital pins
   PMP_Init();                   // Configure PMP module for LCD
   LCD_Init();                   // Configure LCD controller
   InitBackground();
   _TRISA3 = 0;                  // Make RA3 an output (pin 50 of Mikro board)
   TMR5 = 0;                     // Clear Timer5
   PR5 = 19999;                  // Set period of Timer5 to 10 ms
   T5CON = 0x8010;               // Clock Timer5 with Fcy/8 = 2 MHz
   _TRISD0 = 0; 
   
	_CN2PUE = 1;
	_CN4PUE = 1;
	_CN5PUE = 1;

   //color box center locations
   white_x = 48+25;
   lr_x = white_x+51;
   lg_x = lr_x+51;
   lb_x = lg_x+51;
   yellow_x = lb_x+51;

   DrawRectangle(white_x-14, box_y-14, white_x+15, box_y+15, BLACK);
   DrawRectangle(white_x-12, box_y-12, white_x+13, box_y+13, WHITE);
   DrawRectangle(lr_x-14, box_y-14, lr_x+15, box_y+15, BLACK);
   DrawRectangle(lr_x-12, box_y-12, lr_x+13, box_y+13, LIGHT_RED);
   DrawRectangle(lg_x-14, box_y-14, lg_x+15, box_y+15, BLACK);
   DrawRectangle(lg_x-12, box_y-12, lg_x+13, box_y+13, LIGHT_GREEN);
   DrawRectangle(lb_x-14, box_y-14, lb_x+15, box_y+15, BLACK);
   DrawRectangle(lb_x-12, box_y-12, lb_x+13, box_y+13, LIGHT_BLUE);
   DrawRectangle(yellow_x-14, box_y-14, yellow_x+15, box_y+15, BLACK);
   DrawRectangle(yellow_x-12, box_y-12, yellow_x+13, box_y+13, YELLOW);
	Display(BKGD, (char *) HandleStr);
	
	DrawRectangle(currentBar_x, bargraph_top, currentBar_x+3, bargraph_bottom, WHITE);
   InitRPG();
}
Example #7
0
BOOL CGameDlg::OnInitDialog()
{
	//mainBGM();
	CDialogEx::OnInitDialog();
	InitBackground();
	InitElement();
	InitMask();
	InitComboMask();
	InitComboInit();
	Pause();
	UpdateWindow();
	Score = 0;
	ShowScore();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	return TRUE;// return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE

}
Example #8
0
void CRenderWorld::LoadImages(){ //load images
  InitBackground();
  LoadBackground(); 
  LoadSplash();

  //Numbers
  Load(N_0, "0");
  Load(N_1, "1");
  Load(N_2, "2");
  Load(N_3, "3");
  Load(N_4, "4");
  Load(N_5, "5");
  Load(N_6, "6");
  Load(N_7, "7");
  Load(N_8, "8");
  Load(N_9, "9");
  Load(N_10, "10");
  
  //Load sprites
  Load(CURSOR, "cursor");
  Load(CURSOR_HAND, "cursor_hand");
  Load(START, "start");
  Load(START_HOVER, "hoverStart");
  Load(ENDTURN, "endTurn");
  Load(ENDTURNHOVER, "endTurnHover");
  Load(ATTACKACTIVE, "attackActive");
  Load(ATTACK, "attack");
  Load(ATTACKHOVER, "attackHover");
  Load(WAIT, "wait");
  Load(WAITHOVER, "waitHover");
  Load(WAITACTIVE, "waitActive");
  Load(CAPTURE, "capture");
  Load(CAPTUREHOVER, "capHover");
  Load(CAPTUREACTIVE, "capActive");
  Load(INFO, "info");
  Load(INFOHOVER, "infoHover");
  Load(SIDE1, "side1");
  Load(SIDE2, "side2");
  Load(WIN1, "win1");
  Load(WIN2, "win2");
  Load(CROSSHAIR, "crosshair");

  //attack animation
  Load(ATTACK0, "attack0");
  Load(ATTACK1, "attack1");
  Load(ATTACK2, "attack2");
  Load(ATTACK3, "attack3");

  //Blood Crystle
  Load(BLOODCRYSTLE0, "bCrystle0");
  Load(BLOODCRYSTLE1, "bCrystle1");
  Load(BLOODCRYSTLE2, "bCrystle2");
  Load(BLOODCRYSTLE3, "bCrystle3");
  Load(BLOODCRYSTLE4, "bCrystle4");
  
  //infoPane
  Load(INFOPANE, "infoPane");
  Load(HEALTH_ICON, "health");
  Load(DEFENSE_ICON, "defense");
  Load(MOVE_ICON, "move");
  Load(ATTACK_ICON, "attack");

  Load(TITLE_NAME, "title");
  Load(BLOOD, "blood");

  //Arrow
  Load(DOWNA, "downA");
  Load(DOWNBUTT, "downButt");
  Load(HORZ, "horz");
  Load(LEFTA, "leftA");
  Load(LEFTBUTT, "leftButt");
  Load(LEFTUP, "leftUp");
  Load(RIGHTA, "rightA");
  Load(RIGHTBUTT, "rightButt");
  Load(RIGHTDOWN, "rightDown");
  Load(RIGHTUP, "rightUp");
  Load(UPA, "upA");
  Load(UPBUTT, "upButt");
  Load(VERT, "vert");

  //blue soldier
  Load(BSIDLE0, "BSidle0");
  Load(BSIDLE1, "BSidle1");
  Load(BSIDLE2, "BSidle2");
  Load(BSIDLE3, "BSidle3");

  Load(BSRIGHT0, "BSright0");
  Load(BSRIGHT1, "BSright1");
  Load(BSRIGHT2, "BSright2");
  Load(BSRIGHT3, "BSright3");

  Load(BSLEFT0, "BSleft0");
  Load(BSLEFT1, "BSleft1");
  Load(BSLEFT2, "BSleft2");
  Load(BSLEFT3, "BSleft3");

  Load(BSUP0, "BSup0");
  Load(BSUP1, "BSup1");
  Load(BSUP2, "BSup2");
  Load(BSUP3, "BSup3");

  Load(BSDOWN0, "BSdown0");
  Load(BSDOWN1, "BSdown1");
  Load(BSDOWN2, "BSdown2");
  Load(BSDOWN3, "BSdown3");

  Load(BSMOVED0, "BSmoved0");
  Load(BSMOVED1, "BSmoved1");
  Load(BSMOVED2, "BSmoved2");
  Load(BSMOVED3, "BSmoved3");

  //blue heavy soldier
  Load(BHIDLE0, "BHidle0");
  Load(BHIDLE1, "BHidle1");
  Load(BHIDLE2, "BHidle0");
  Load(BHIDLE3, "BHidle1");

  Load(BHRIGHT0, "BHright0");
  Load(BHRIGHT1, "BHright1");
  Load(BHRIGHT2, "BHright2");
  Load(BHRIGHT3, "BHright3");

  Load(BHLEFT0, "BHleft0");
  Load(BHLEFT1, "BHleft1");
  Load(BHLEFT2, "BHleft2");
  Load(BHLEFT3, "BHleft3");

  Load(BHUP0, "BHup0");
  Load(BHUP1, "BHup1");
  Load(BHUP2, "BHup2");
  Load(BHUP3, "BHup3");

  Load(BHDOWN0, "BHdown0");
  Load(BHDOWN1, "BHdown1");
  Load(BHDOWN2, "BHdown2");
  Load(BHDOWN3, "BHdown3");

  Load(BHMOVED0, "BHmoved0");
  Load(BHMOVED1, "BHmoved1");
  Load(BHMOVED2, "BHmoved0");
  Load(BHMOVED3, "BHmoved1");

  //blue tank
  Load(BTIDLE0, "BTidle0");
  Load(BTIDLE1, "BTidle1");
  Load(BTIDLE2, "BTidle2");
  Load(BTIDLE3, "BTidle1");

  Load(BTRIGHT0, "BTright0");
  Load(BTRIGHT1, "BTright1");
  Load(BTRIGHT2, "BTright2");
  Load(BTRIGHT3, "BTright1");

  Load(BTLEFT0, "BTleft0");
  Load(BTLEFT1, "BTleft1");
  Load(BTLEFT2, "BTleft2");
  Load(BTLEFT3, "BTleft1");

  Load(BTUP0, "BTup0");
  Load(BTUP1, "BTup1");
  Load(BTUP2, "BTup2");
  Load(BTUP3, "BTup1");

  Load(BTDOWN0, "BTdown0");
  Load(BTDOWN1, "BTdown1");
  Load(BTDOWN2, "BTdown2");
  Load(BTDOWN3, "BTdown1");

  Load(BTMOVED0, "BTmoved0");
  Load(BTMOVED1, "BTmoved1");
  Load(BTMOVED2, "BTmoved2");
  Load(BTMOVED3, "BTmoved1");
  
  //red soldier
  Load(RSIDLE0, "RSidle0");
  Load(RSIDLE1, "RSidle1");
  Load(RSIDLE2, "RSidle2");
  Load(RSIDLE3, "RSidle3");

  Load(RSRIGHT0, "RSright0");
  Load(RSRIGHT1, "RSright1");
  Load(RSRIGHT2, "RSright2");
  Load(RSRIGHT3, "RSright3");

  Load(RSLEFT0, "RSleft0");
  Load(RSLEFT1, "RSleft1");
  Load(RSLEFT2, "RSleft2");
  Load(RSLEFT3, "RSleft3");

  Load(RSUP0, "RSup0");
  Load(RSUP1, "RSup1");
  Load(RSUP2, "RSup2");
  Load(RSUP3, "RSup3");

  Load(RSDOWN0, "RSdown0");
  Load(RSDOWN1, "RSdown1");
  Load(RSDOWN2, "RSdown2");
  Load(RSDOWN3, "RSdown3");

  Load(RSMOVED0, "RSmoved0");
  Load(RSMOVED1, "RSmoved1");
  Load(RSMOVED2, "RSmoved2");
  Load(RSMOVED3, "RSmoved3");

  //red heavy soldier
  Load(RHIDLE0, "RHidle0");
  Load(RHIDLE1, "RHidle1");
  Load(RHIDLE2, "RHidle0");
  Load(RHIDLE3, "RHidle1");

  Load(RHRIGHT0, "RHright0");
  Load(RHRIGHT1, "RHright1");
  Load(RHRIGHT2, "RHright2");
  Load(RHRIGHT3, "RHright3");

  Load(RHLEFT0, "RHleft0");
  Load(RHLEFT1, "RHleft1");
  Load(RHLEFT2, "RHleft2");
  Load(RHLEFT3, "RHleft3");

  Load(RHUP0, "RHup0");
  Load(RHUP1, "RHup1");
  Load(RHUP2, "RHup2");
  Load(RHUP3, "RHup3");

  Load(RHDOWN0, "RHdown0");
  Load(RHDOWN1, "RHdown1");
  Load(RHDOWN2, "RHdown2");
  Load(RHDOWN3, "RHdown3");

  Load(RHMOVED0, "RHmoved0");
  Load(RHMOVED1, "RHmoved1");
  Load(RHMOVED2, "RHmoved0");
  Load(RHMOVED3, "RHmoved1");

  //red tank
  Load(RTIDLE0, "RTidle0");
  Load(RTIDLE1, "RTidle1");
  Load(RTIDLE2, "RTidle2");
  Load(RTIDLE3, "RTidle1");

  Load(RTRIGHT0, "RTright0");
  Load(RTRIGHT1, "RTright1");
  Load(RTRIGHT2, "RTright2");
  Load(RTRIGHT3, "RTright1");

  Load(RTLEFT0, "RTleft0");
  Load(RTLEFT1, "RTleft1");
  Load(RTLEFT2, "RTleft2");
  Load(RTLEFT3, "RTleft1");

  Load(RTUP0, "RTup0");
  Load(RTUP1, "RTup1");
  Load(RTUP2, "RTup2");
  Load(RTUP3, "RTup1");

  Load(RTDOWN0, "RTdown0");
  Load(RTDOWN1, "RTdown1");
  Load(RTDOWN2, "RTdown2");
  Load(RTDOWN3, "RTdown1");

  Load(RTMOVED0, "RTmoved0");
  Load(RTMOVED1, "RTmoved1");
  Load(RTMOVED2, "RTmoved2");
  Load(RTMOVED3, "RTmoved1");

  //map tiles
  Load(RED_BASE, "redBase"); 
  Load(BLUE_BASE, "blueBase");
  Load(GRASS0, "grass0"); 
  Load(GRASS1, "grass1");
  Load(MOUNTAIN0, "mountain0");
  Load(MOUNTAIN1, "mountain1");
  Load(MOUNTAIN2, "mountain2");
  Load(MOUNTAIN3, "mountain3");
  Load(MOUNTAIN4, "mountain4");
  Load(MOUNTAIN5, "mountain5");
  Load(RIVER0, "river0");
  Load(RIVER1, "river1");
  Load(RIVER2, "river2");
  Load(ROAD0, "road0");
  Load(ROAD1, "road1");
  Load(ROAD2, "road2");
  Load(ROAD3, "road3");
  Load(ROAD4, "road4");
  Load(ROAD5, "road5");
  Load(ROAD6, "road6");
  Load(ROAD7, "road7");
  Load(ROAD8, "road8");
  Load(ROAD9, "road9");
  Load(ROAD10, "road10");
  Load(TREE0, "tree0");
  Load(TREE1, "tree1");
  Load(WALLPAPER, "greyWallpaper");
  //RED MAP TILES
  Load(RED_BASE_R, "redBase_r");
  Load(BLUE_BASE_R, "blueBase_r");
  Load(GRASS0_R, "grass0_r");
  Load(GRASS1_R, "grass1_r");
  Load(MOUNTAIN0_R, "mountain0_r");
  Load(MOUNTAIN1_R, "mountain1_r");
  Load(MOUNTAIN2_R, "mountain2_r");
  Load(MOUNTAIN3_R, "mountain3_r");
  Load(MOUNTAIN4_R, "mountain4_r");
  Load(MOUNTAIN5_R, "mountain5_r");
  Load(ROAD0_R, "road0_r");
  Load(ROAD1_R, "road1_r");
  Load(ROAD2_R, "road2_r");
  Load(ROAD3_R, "road3_r");
  Load(ROAD4_R, "road4_r");
  Load(ROAD5_R, "road5_r");
  Load(ROAD6_R, "road6_r");
  Load(ROAD7_R, "road7_r");
  Load(ROAD8_R, "road8_r");
  Load(ROAD9_R, "road9_r");
  Load(ROAD10_R, "road10_r");
  Load(TREE0_R, "tree0_r");
  Load(TREE1_R, "tree1_r");
  Load(WALLPAPER_R, "redWallpaper");
  //BLUE MAP TILES
  Load(RED_BASE_B, "redBase_b");
  Load(BLUE_BASE_B, "blueBase_b");
  Load(GRASS0_B, "grass0_b");
  Load(GRASS1_B, "grass1_b");
  Load(MOUNTAIN0_B, "mountain0_b");
  Load(MOUNTAIN1_B, "mountain1_b");
  Load(MOUNTAIN2_B, "mountain2_b");
  Load(MOUNTAIN3_B, "mountain3_b");
  Load(MOUNTAIN4_B, "mountain4_b");
  Load(MOUNTAIN5_B, "mountain5_b");
  Load(ROAD0_B, "road0_b");
  Load(ROAD1_B, "road1_b");
  Load(ROAD2_B, "road2_b");
  Load(ROAD3_B, "road3_b");
  Load(ROAD4_B, "road4_b");
  Load(ROAD5_B, "road5_b");
  Load(ROAD6_B, "road6_b");
  Load(ROAD7_B, "road7_b");
  Load(ROAD8_B, "road8_b");
  Load(ROAD9_B, "road9_b");
  Load(ROAD10_B, "road10_b");
  Load(TREE0_B, "tree0_b");
  Load(TREE1_B, "tree1_b");
  Load(WALLPAPER_B, "blueWallpaper");
  
  Load(EX0, "ex0");
  Load(EX1, "ex1");
  Load(EX2, "ex2");
  Load(EX3, "ex3");
  Load(EX4, "ex4");
  Load(EX5, "ex5");
  Load(EX6, "ex6");
  Load(EX7, "ex7");
  Load(EX8, "ex8");
  Load(EX9, "ex9");
  Load(EX10, "ex10");
  Load(EX11, "ex11");
  Load(EX12, "ex12");
  Load(EX13, "ex13");
  Load(EX14, "ex14");
  Load(EX15, "ex15");
  Load(EX16, "ex16");
  Load(EX17, "ex17");
  Load(EX18, "ex18");
  Load(EX19, "ex19");
  Load(EX20, "ex20");
  Load(EX21, "ex21");
  Load(EX22, "ex22");
  Load(EX23, "ex23");
} //LoadImages
Example #9
0
int main(int argc, char *argv[])
{
    enum { GAME_COMPUTER, GAME_NETWORK, GAME_UNKNOWN } game_type = GAME_UNKNOWN;
    char *remote_address = NULL;
    int remote_port;
    int i;
	
    if (argc < 2) {
	printf("Penguin Warrior\n");
	printf("Usage: pw [ mode ] [ option ... ]\n");
	printf("  Game modes (choose one):\n");
	printf("    --computer\n");
	printf("    --client <remote ip address>\n");
	printf("    --server <port number>\n");
	printf("  Display options, for tweaking and experimenting:\n");
	printf("    --fullscreen\n");
	printf("    --hwsurface  (use an SDL hardware surface if possible)\n");
	printf("    --doublebuf  (use SDL double buffering if possible)\n");
	printf("  The display options default to a windowed, software buffer.\n");
	exit(EXIT_FAILURE);
    }

    /* Process command line arguments. There are plenty of libraries for command
       line processing, but our needs are simple in this case. */
    for (i = 0; i < argc; i++) {

	/* Networked or scripted opponent? */
	if (!strcmp(argv[i], "--computer")) {
	    game_type = GAME_COMPUTER;
	    continue;
	} else if (!strcmp(argv[i], "--client")) {
	    game_type = GAME_NETWORK;
	    if (i + 2 >= argc) {
		printf("You must supply an IP address "\
		       "and port number for network games.\n");
		exit(EXIT_FAILURE);
	    }
	    remote_address = argv[i+1];
	    remote_port = atoi(argv[i+2]);
	    i++;
	    continue;

	} else if (!strcmp(argv[i], "--server")) {
	    game_type = GAME_NETWORK;
	    if (++i >= argc) {
		printf("You must supply a port number "\
		       "for --server.\n");
		exit(EXIT_FAILURE);
	    }
	    remote_port = atoi(argv[i]);
	    continue;
			
	    /* Display-related options */
	} else if (!strcmp(argv[i], "--hwsurface")) {
	    hwsurface = 1;
	} else if (!strcmp(argv[i], "--doublebuf")) {
	    doublebuf = 1;
	} else if (!strcmp(argv[i], "--fullscreen")) {
	    fullscreen = 1;
	}
    }

    /* If this is a network game, make a connection. */
    if (game_type == GAME_NETWORK) {

	/* If there's no remote address, the user selected
	   server mode. */
	if (remote_address == NULL) {
	    if (WaitNetgameConnection(remote_port,
				      &netlink) != 0) {
		printf("Unable to receive connection.\n");
		exit(EXIT_FAILURE);
	    }
	} else {
	    if (ConnectToNetgame(remote_address, remote_port,
				 &netlink) != 0) {
		printf("Unable to connect.\n");
		exit(EXIT_FAILURE);
	    }
	}

	opponent_type = OPP_NETWORK;
	printf("Playing in network game against %s.\n", netlink.dotted_ip);

    } else if (game_type == GAME_COMPUTER) {

	opponent_type = OPP_COMPUTER;
	printf("Playing against the computer.\n");

    } else {

	printf("No game type selected.\n");
	exit(EXIT_FAILURE);

    }
	
    /* Initialize our random number generator. */
    initrandom();

    /* Create a mutex to protect the player data. */
    player_mutex = SDL_CreateMutex();
    if (player_mutex == NULL) {
	fprintf(stderr, "Unable to create mutex: %s\n",
		SDL_GetError());
    }

    /* Start our scripting engine. */
    InitScripting();
    if (LoadGameScript("pw.tcl") != 0) {
	fprintf(stderr, "Exiting due to script error.\n");
	exit(EXIT_FAILURE);
    }

    /* Fire up SDL. */
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
	printf("Unable to initialize SDL: %s\n", SDL_GetError());
	exit(EXIT_FAILURE);
    }
    atexit(SDL_Quit);
	
    /* Set an appropriate 16-bit video mode. */
    if (SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 16,
			 (hwsurface ? SDL_HWSURFACE : SDL_SWSURFACE) |
			 (doublebuf ? SDL_DOUBLEBUF : 0) |
			 (fullscreen ? SDL_FULLSCREEN : 0)) == NULL) {
	printf("Unable to set video mode: %s\n", SDL_GetError());
	exit(EXIT_FAILURE);
    }
	
    /* Save the screen pointer for later use. */
    screen = SDL_GetVideoSurface();
	
    /* Set the window caption to the name of the game. */
    SDL_WM_SetCaption("Penguin Warrior", "Penguin Warrior");
	
    /* Hide the mouse pointer. */
    SDL_ShowCursor(0);

    /* Initialize the status display. */
    if (InitStatusDisplay() < 0) {
	printf("Unable to initialize status display.\n");
	exit(EXIT_FAILURE);
    }
		
    /* Start the OpenAL-based audio system. */
    InitAudio();

    /* Initialize music and give the music system a file. */
    InitMusic();
    if (LoadMusic("reflux.ogg") < 0) {
	/* If that failed, don't worry about it. */
	printf("Unable to load reflux.ogg.\n");
    }

    /* Load the game's data into globals. */
    LoadGameData();

    /* Initialize the background starfield. */
    InitBackground();

    /* Start the network thread. */
    if (game_type == GAME_NETWORK) {
	network_thread = SDL_CreateThread(NetworkThread, NULL);
	if (network_thread == NULL) {
	    printf("Unable to start network thread: %s\n",
		   SDL_GetError());
	    exit(EXIT_FAILURE);
	}
    }
	
    /* Play! */
    InitPlayer(&player);
    InitPlayer(&opponent);
    PlayGame();

    /* Kill the network thread. */
    if (game_type == GAME_NETWORK) {
	SDL_KillThread(network_thread);
    }

    /* Close the network connection. */
    if (game_type == GAME_NETWORK)
	CloseNetgameLink(&netlink);

    /* Unhide the mouse pointer. */
    SDL_ShowCursor(1);
	
    /* Clean up the status display. */
    CleanupStatusDisplay();

    /* Unload data. */
    UnloadGameData();
	
    /* Shut down our scripting engine. */
    CleanupScripting();

    /* Get rid of the mutex. */
    SDL_DestroyMutex(player_mutex);

    /* Shut down audio. */
    CleanupMusic();
    CleanupAudio();

    return 0;
}
Example #10
0
File: main.c Project: Clasr/Game-C
//main
int main()
{
    int letra;
    OpcaoBackground(letra);
    //primitive variables
    int NUM_ENEMYRED = 10; //quantidade de inimigos vermelhos
    int NUM_ENEMYBLUE = 10; //quantidade de inimigos azuis
    int NUM_BOSS = 5;
    int text_color = 255; //variavel para cor (animacao inicial de jogo - efeito relampago)
    int text_boss = 255; //variavel para cor de texto boss
    int FPS = 60; //frames per second
    bool done = false;
    bool redraw = true;
    enum KEYS {UP, DOWN, LEFT, RIGHT, Q, W, E, R};
    bool keys[8] = {false, false, false, false, false, false, false, false};

    //object variables
    struct Player player;
    struct Enemy_red enemyred[NUM_ENEMYRED];
    struct Enemy_blue enemyblue[NUM_ENEMYBLUE];
    struct Boss boss[NUM_BOSS];
    struct Shoot shootQ;
    struct Shoot shootW;
    struct Shoot shootE;
    struct Obstacle obstacle;
    struct SpriteScientist scientist;
    struct Sprite background;
    struct Sprite background1;
    struct Sprite background2;
    struct Sprite background3;
    struct Sprite background4;
    struct Sprite background5;
    struct Sprite background6;
    struct Sprite enemyred_sprite;

    //allegro variables
    ALLEGRO_DISPLAY *display;
    ALLEGRO_EVENT_QUEUE *event_queue = NULL;
    ALLEGRO_TIMER *timer = NULL;

    ALLEGRO_FONT *title_font = NULL;
    ALLEGRO_FONT *medium_font = NULL;

////////////////////////////////////////////////////////////////////////

    //verificacoes de erro
    if(!al_init())
        return -1; //caso de erro ao inicializar allegro

    display = al_create_display(WIDTH,HEIGHT); //criar display

    if(!display)
        return -1; //se der merda

    //Allegro Module Init
    al_init_primitives_addon();
    al_init_font_addon();
    if (!al_init_ttf_addon())
    {
        printf("Falha ao inicializar addon allegro_ttf.\n");
        return -1;
    }
    al_install_keyboard();

    if(!al_init_image_addon())
    {
        printf("Falha ao inicializar image addon");
        return -1;
    }




    event_queue = al_create_event_queue();
    timer = al_create_timer(1.0 / FPS);
    medium_font = al_load_font("fonts/EHSMB.TTF", 50, 0);
    if (!medium_font)
    {
        al_destroy_display(display);
        printf("Falha ao carregar fonte.\n");
        return -1;
    }
    title_font = al_load_font("fonts/French Electric Techno.ttf", 200, 0);
    if (!title_font)
    {
        al_destroy_display(display);
        printf("Falha ao carregar fonte.\n");
        return -1;
    }

    int b;

    //Inicializacao de objetos
    InitPlayer(player, &text_color); //funcao que "inicia" player
    InitScientist(scientist);
    if (!scientist.bitmap)
    {
        al_destroy_display(display);
        printf("Falha ao carregar sprite scientist.\n");
        return -1;
    }
    InitEnemyRed(enemyred, &NUM_ENEMYRED); //funcao que inicia enemyred
    InitEnemyBlue(enemyblue, &NUM_ENEMYBLUE); //funcao que inicia enemyblue
    InitShootQ(shootQ); //funcao que inicializa disparo 1 (capacitor)
    if(!shootQ.bitmap)
    {
        al_destroy_display(display);
        printf("Falha ao carregar sprite shootQ.\n");
        return -1;
    }
    InitShootW(shootW); //funcao que inicializa disparo 2 (indutor)
    if(!shootW.bitmap)
    {
        al_destroy_display(display);
        printf("Falha ao carregar sprite shootW.\n");
        return -1;
    }
    InitShootE(shootE); //funcao que inicializa habilidade de escudo (shield / resistor)
    if(!shootE.bitmap)
    {
        al_destroy_display(display);
        printf("Falha ao carregar sprite shield.\n");
        return -1;
    }
    InitObstacle(obstacle); //funcao que inicializa obstaculos
    InitBoss(boss, &NUM_BOSS); //funcao que inicializa chefes (bosses)
    InitBackground(background, letra); //funcao que inicializa sprite de background
    InitBackground1(background1, letra); //funcao que inicializa sprite de background1 alternativo
    InitBackground2(background2, letra); //funcao que inicializa sprite de background2 alternativo
    InitBackground3(background3, letra); //funcao que inicializa sprite de background3 alternativo
    InitBackground4(background4, letra); //funcao que inicializa sprite de background4 alternativo
    InitBackground5(background5, letra); //funcao que inicializa sprite de background4 alternativo
    InitBackground6(background6, letra); //funcao que inicializa sprite de background4 alternativo
    InitEnemyredSprite(enemyred_sprite); // funcao que inicializa sprite de inimigo vermelho

    al_register_event_source(event_queue, al_get_keyboard_event_source());
    al_register_event_source(event_queue, al_get_display_event_source(display));
    al_register_event_source(event_queue, al_get_timer_event_source(timer));
    al_start_timer(timer);

    while (!done)
    {
        ALLEGRO_EVENT ev;
        al_wait_for_event(event_queue, &ev);

        //se clicar para fechar a janela
        if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
        {
            done = true;
        }
        //evento do timer (vai entrar nesse else if sempre, a nao ser que feche a janela)
        else if(ev.type == ALLEGRO_EVENT_TIMER)
        {
            redraw = true;
            if(keys[RIGHT] && !player.moving)
            {
                player.velx = player.speed;
                player.moving = true;
            }
            if(keys[LEFT] && !player.moving)
            {
                player.velx = player.speed;
                player.moving = true;
            }

            ChangeColor(&text_color, player, boss, &NUM_BOSS, &text_boss);
            PlayerJump(player, &keys[UP]);
            PlayerRight(player, &keys[RIGHT], scientist);
            PlayerLeft(player, &keys[LEFT]);
            //updates
            UpdateShootQ(shootQ, player);
            UpdateShootW(shootW, player);
            UpdateShootE(shootE, player);
            UpdateEnemyRed(enemyred, &NUM_ENEMYRED, player, shootQ);
            UpdateEnemyBlue(enemyblue, &NUM_ENEMYBLUE, player, shootW);
            UpdateObstacle(obstacle, medium_font, player);
            UpdateBoss(boss, &NUM_BOSS, &text_boss, player, enemyred, &NUM_ENEMYRED, enemyblue, &NUM_ENEMYBLUE);
            //colisoes
            ShootQColisionEnemyRed(shootQ,enemyred, &NUM_ENEMYRED, player);
            ShootWColisionEnemyBlue(shootW, enemyblue, &NUM_ENEMYBLUE, player);
            ShootColisionBoss(shootW, shootQ, boss, &NUM_BOSS, player);
            PlayerColisionEnemyBlue(player, enemyblue, &NUM_ENEMYBLUE);
            PlayerColisionEnemyRed(player, enemyred, &NUM_ENEMYRED);
            PlayerColisionObstacle(player,obstacle);
            PlayerColisionBoss(player, boss, &NUM_BOSS);

            ResetPlayer(player, enemyred, &NUM_ENEMYRED, enemyblue, &NUM_ENEMYBLUE, obstacle, boss, &NUM_BOSS, &text_color);
        }

        else if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
        {
            switch(ev.keyboard.keycode)
            {
            case ALLEGRO_KEY_ESCAPE:
                done = true;
                break;
            case ALLEGRO_KEY_UP:
                keys[UP] = true;
                break;
            case ALLEGRO_KEY_RIGHT:
                keys[RIGHT] = true;
                break;
            case ALLEGRO_KEY_LEFT:
                keys[LEFT] = true;
                break;
            case ALLEGRO_KEY_Q:
                keys[Q] = true;
                FireShootQ(shootQ, player);
                break;
            case ALLEGRO_KEY_W:
                keys[W] = true;
                FireShootW(shootW, player);
                break;
            case ALLEGRO_KEY_E:
                keys[E] = true;
                FireShootE(shootE, player);
                break;
            case ALLEGRO_KEY_R:
                keys[R] = true;
                break;
            }
        }

        else if(ev.type == ALLEGRO_EVENT_KEY_UP)
        {
            switch(ev.keyboard.keycode)
            {
            case ALLEGRO_KEY_UP:
                keys[UP] = false;
                break;
            case ALLEGRO_KEY_RIGHT:
                keys[RIGHT] = false;
                player.moving = false;
                break;
            case ALLEGRO_KEY_LEFT:
                keys[LEFT] = false;
                player.moving = false;
                break;
            case ALLEGRO_KEY_Q:
                keys[Q] = false;
                break;
            case ALLEGRO_KEY_W:
                keys[W] = false;
                break;
            case ALLEGRO_KEY_E:
                keys[E] = false;
                break;
            case ALLEGRO_KEY_R:
                keys[R] = false;
                break;
            }
        }

        if(redraw && al_is_event_queue_empty(event_queue))
        {
            redraw = false;

            //desenhar objetos
            DrawBackground(background, letra);
            DrawBackground1(background1, letra);
            DrawBackground2(background2, letra);
            DrawBackground3(background3, letra);
            DrawBackground4(background4, letra);
            DrawBackground5(background5, letra);
            DrawBackground6(background6, letra);
            DrawText(title_font, medium_font, player, boss, &NUM_BOSS, &text_color, &text_boss);
            DrawShootQ(shootQ);
            DrawShootW(shootW);
            DrawShootE(shootE, player);
            DrawEnemyRed(enemyred, &NUM_ENEMYRED, player, enemyred_sprite);
            DrawEnemyBlue(enemyblue, &NUM_ENEMYBLUE, player);
            DrawBoss(boss, &NUM_BOSS, player);
            DrawObstacle(obstacle);
            DrawScientist(player, scientist, &keys[LEFT], &keys[RIGHT]);

            al_flip_display();
        }
    }

    al_destroy_event_queue(event_queue);
    al_destroy_timer(timer);
    al_destroy_font(title_font);
    al_destroy_font(medium_font);
    al_destroy_display(display);
    al_destroy_bitmap(scientist.bitmap);
    al_destroy_bitmap(shootE.bitmap);
    for(b=0; b<background.frame_max; b++)
    {
        al_destroy_bitmap(background.image[b]);
    }
    for(b=0; b<background1.frame_max; b++)
    {
        al_destroy_bitmap(background1.image[b]);
    }
    for(b=0; b<background2.frame_max; b++)
    {
        al_destroy_bitmap(background2.image[b]);
    }
    for(b=0; b<background3.frame_max; b++)
    {
        al_destroy_bitmap(background3.image[b]);
    }
    for(b=0; b<background4.frame_max; b++)
    {
        al_destroy_bitmap(background4.image[b]);
    }
    for(b=0; b<background5.frame_max; b++)
    {
        al_destroy_bitmap(background5.image[b]);
    }
    for(b=0; b<background6.frame_max; b++)
    {
        al_destroy_bitmap(background6.image[b]);
    }

    return 0;
}//final da MAIN!!
Example #11
0
void CUIFrags::Init(CUIXml& xml_doc, LPCSTR path, LPCSTR backgrnd_path){
	m_pStats->Init(xml_doc, path, 0);
	InitBackground(xml_doc, backgrnd_path);	
}
/**
* Update cycle
*
* Checks for keypresses:
*   - Esc - Quits the game
*   - Left - Rotates ship left
*   - Right - Rotates ship right
*   - Up - Accelerates the ship
*   - Down - Deccelerates the ship
*
* Also calls Update() on all the ships in the universe
*/
bool Application::Update()
{
	float timedelta = hge_->Timer_GetDelta();
	if (bulletShootTimer < S_BULLET_SHOOT_INTERVAL)
	{
		bulletShootTimer += timedelta;
	}
	if (missileShootTimer < S_MISSILE_SHOOT_INTERVAL)
	{
		missileShootTimer += timedelta;
	}

	ships_.at(0)->SetAngularVelocity(0.0f);

	// Lab 13 Task 4 : Add a key to shoot missiles
	/*if (hge_->Input_GetKeyState(HGEK_ENTER))
	{
		if (!keydown_enter)
		{
			CreateMissile(ships_.at(0)->GetX(), ships_.at(0)->GetY(), ships_.at(0)->GetW(), ships_.at(0)->GetID());
			keydown_enter = true;
		}
	}
	else
	{
		if (keydown_enter)
		{
			keydown_enter = false;
		}
	}*/

	static const float MAX_ENTER_TIMER = 0.5f;
	static float enterTimer;

	if (enterTimer < MAX_ENTER_TIMER)
	{
		enterTimer += timedelta;
	}

	// Chat
	if (chatMode)
	{
		char input = hge_->Input_GetKey();

		if (input == HGEK_ESCAPE)
		{
			chatMode = false;
			typingMsg = "";
		}
		else if (input == HGEK_ENTER && enterTimer >= MAX_ENTER_TIMER)
		{
			// Send
			if (typingMsg != "")
			{
				RakNet::BitStream chatBS;
				chatBS.Write((unsigned char)ID_CHAT_SEND);
				chatBS.Write(typingMsg.c_str());
				rakpeer_->Send(&chatBS, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
				chatList.push_back(typingMsg);
			}

			// Reset
			chatMode = false;
			typingMsg = "";
			enterTimer = 0.f;
			chatShowTimer = 5.f;
		}
		else if (input >= 32 && input <= 126)
		{
			typingMsg += input;
		}
	}
	else
	{
		if (chatShowTimer > 0.f)
		{
			chatShowTimer -= timedelta;
		}

		if (hge_->Input_GetKeyState(HGEK_ENTER) && enterTimer >= MAX_ENTER_TIMER)
		{
			chatMode = true;
			enterTimer = 0.f;
		}

		// Ship controls
		if (hge_->Input_GetKeyState(HGEK_LEFT))
		{
			ships_.at(0)->SetAngularVelocity(ships_.at(0)->GetAngularVelocity() - DEFAULT_ANGULAR_VELOCITY);
		}

		if (hge_->Input_GetKeyState(HGEK_RIGHT))
		{
			ships_.at(0)->SetAngularVelocity(ships_.at(0)->GetAngularVelocity() + DEFAULT_ANGULAR_VELOCITY);
		}

		if (hge_->Input_GetKeyState(HGEK_UP))
		{
			ships_.at(0)->Accelerate(DEFAULT_ACCELERATION, timedelta);
		}

		if (hge_->Input_GetKeyState(HGEK_DOWN))
		{
			ships_.at(0)->Accelerate(-DEFAULT_ACCELERATION, timedelta);
		}

		// Shooting
		if (hge_->Input_GetKeyState(HGEK_1))
		{
			if (missileShootTimer >= S_MISSILE_SHOOT_INTERVAL)
			{
				Shoot(Projectile::PROJ_SEEKING_MISSLE);
			}
		}
		if (hge_->Input_GetKeyState(HGEK_2))
		{
			if (bulletShootTimer >= S_BULLET_SHOOT_INTERVAL)
			{
				Shoot(Projectile::PROJ_BULLET);
			}
		}

		if (hge_->Input_GetKeyState(HGEK_ESCAPE))
		{
			return true;
		}
	}

	// Update all ships
	for (ShipList::iterator ship = ships_.begin();
	ship != ships_.end(); ship++)
	{
		(*ship)->Update(timedelta);

		//collisions
		/*if ((*ship) == ships_.at(0))
			checkCollisions((*ship));*/
	}

	// Lab 13 Task 5 : Updating the missile
	/*if (mymissile)
	{
		if (mymissile->Update(ships_, timedelta))
		{
			//havecollision
			delete mymissile;
			mymissile = 0;
		}
	}*/

	// Lab 13 Task 13 : Update network missiles
	/*for (MissileList::iterator missile = missiles_.begin(); missile != missiles_.end(); missile++)
	{
		if ((*missile)->Update(ships_, timedelta))
		{
			//havecollision
			delete*missile;
			missiles_.erase(missile);
			break;
		}
	}*/

	// Update enemies
	/*for (vector<Enemy*>::iterator it = enemyList.begin(); it != enemyList.end(); ++it)
	{
		Enemy* e = *it;
		if (e->GetActive())
		{
			bool reset = e->Update(timedelta);
			if (reset)
			{
				RakNet::BitStream bs;
				bs.Write((unsigned char)ID_DESTROY_ENEMY);
				bs.Write(e->GetID());
				rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
			}
		}
	}*/

	// Update projectile
	for (vector<Projectile*>::iterator it = projectileList.begin(); it != projectileList.end(); ++it)
	{
		Projectile* p = *it;
		if (/*p->GetOwner() == ships_.at(0) && */p->GetActive()) // Only update your own projectile
		{
			bool reset = p->Update(timedelta);
			RakNet::BitStream bs;
			if (reset)
			{
				DestroyProjectile(p);
				bs.Write((unsigned char)ID_DESTROY_PROJECTILE);
				bs.Write(p->GetID());
				rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
			}
			else
			{
				for (vector<Enemy*>::iterator it2 = enemyList.begin(); it2 != enemyList.end(); ++it2)
				{
					Enemy* e = *it2;
					if (e->GetActive())
					{
						bool collision = p->CollideWith(e);
						if (collision)
						{
							int newHP = e->Injure(p->GetDamage());
							if (newHP <= 0)
							{
								RakNet::BitStream bs;
								// Add score to player
								p->GetOwner()->AddScore(100);

								bs.Write((unsigned char)ID_UPDATE_SCORE);
								bs.Write(p->GetOwner()->GetID());
								bs.Write(p->GetOwner()->GetScore());
								rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);

								// Destroy enemy
								DestroyEnemy(e);

								// Send to server to destroy enemy
								bs.ResetWritePointer();
								bs.Write((unsigned char)ID_DESTROY_ENEMY);
								bs.Write(e->GetID());
								rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
							}
							else
							{
								// Send to server to injure enemy
								RakNet::BitStream bs;
								bs.ResetWritePointer();
								bs.Write((unsigned char)ID_INJURE_ENEMY);
								bs.Write(e->GetID());
								bs.Write(e->GetHP());
								rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
							}

							// Reset projectile
							DestroyProjectile(p);
							bs.ResetWritePointer();
							bs.Write((unsigned char)ID_DESTROY_PROJECTILE);
							bs.Write(p->GetID());
							rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
						}
					}
				}
				/*int max = projectileUpdateList.size();
				int count = 0;
				for (vector<Projectile*>::iterator it2 = projectileUpdateList.begin(); it2 != projectileUpdateList.end(); ++it2)
				{
					Projectile* p2 = *it2;
					if (p == p2)
					{
						break;
					}
					else
					{
						++count;
					}
				}
				if (count == max)
				{
					projectileUpdateList.push_back(p);
				}*/
				/*bs.Write((unsigned char)ID_UPDATE_PROJECTILE);
				bs.Write(p->GetID());
				bs.Write(p->GetActive());
				bs.Write(p->GetType());
				bs.Write(p->GetX());
				bs.Write(p->GetY());
				bs.Write(p->GetVelocityX());
				bs.Write(p->GetVelocityY());
				bs.Write(p->GetSpeed());
				bs.Write(p->GetDamage());
				bs.Write(p->GetOwner()->GetID());
				// Send target id if available
				if (p->GetTarget())
				{
					bs.Write(p->GetTarget()->GetID());
				}
				else
				{
					bs.Write(-1);
				}
				rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);*/
			}
		}
	}

	// Update explosions
	for (vector<Explosion*>::iterator it = explosionList.begin(); it != explosionList.end(); ++it)
	{
		Explosion* e = *it;
		if ( e->isActive())
		{
			e->Update(timedelta);
		}
	}

	// Update boom
	for (vector<Boom*>::iterator it = boomList.begin(); it != boomList.end(); ++it)
	{
		Boom* b = *it;
		if (b->isActive())
		{
			b->Update(timedelta);
		}
	}

	// Packet receive
	if (Packet* packet = rakpeer_->Receive())
	{
		RakNet::BitStream bs(packet->data, packet->length, false);
		
		unsigned char msgid = 0;
		RakNetTime timestamp = 0;

		bs.Read(msgid);

		if (msgid == ID_TIMESTAMP)
		{
			bs.Read(timestamp);
			bs.Read(msgid);
		}

		switch(msgid)
		{
		case ID_CONNECTION_REQUEST_ACCEPTED:
			{
				std::cout << "Connected to Server" << std::endl;
				SendScreenSize();
				InitEnemyList();
				InitExplosionList();
				InitBoomList();
				InitProjectileList();
				InitBackground();
				InitBase();
				InitScore();
				chatMsg = new hgeFont("font1.fnt");
				chatMsg->SetScale(1);
				
			}
			break;

		case ID_NO_FREE_INCOMING_CONNECTIONS:
		case ID_CONNECTION_LOST:
		case ID_DISCONNECTION_NOTIFICATION:
			std::cout << "Lost Connection to Server" << std::endl;
			rakpeer_->DeallocatePacket(packet);
			return true;

		case ID_WELCOME:
			{
				unsigned int shipcount, id;
				float x_, y_;
				int type_;
				std::string temp;
				char chartemp[5];

				bs.Read(id);
				ships_.at(0)->setID( id );
				bs.Read(shipcount);

				for (unsigned int i = 0; i < shipcount; ++ i)
				{
					bs.Read(id);
					bs.Read(x_);
					bs.Read(y_);
					bs.Read(type_);
					std::cout << "New Ship pos" << x_ << " " << y_ << std::endl;
					Ship* ship = new Ship(type_, x_, y_ ); 
					temp = "Ship ";
					temp += _itoa(id, chartemp, 10);
					ship->SetName(temp.c_str());
					ship->setID( id );
					ships_.push_back(ship);
				}

				for (vector<Enemy*>::iterator it = enemyList.begin(); it != enemyList.end(); ++it)
				{
					int id, hp;
					bool active;
					Enemy::ENEMY_TYPE type;
					float x, y, vel_x, vel_y, speed;
					bs.Read(id);
					bs.Read(active);
					bs.Read(type);
					bs.Read(x);
					bs.Read(y);
					bs.Read(vel_x);
					bs.Read(vel_y);
					bs.Read(speed);
					bs.Read(hp);
					Enemy* e = FindEnemyByID(id);
					if (e)
					{
						float w = CalcW(Vector2(vel_x, vel_y));
						/*if (speed != 0)
						{
							w = acosf(vel_x / speed);
						}
						else
						{
							w = 0.f;
						}*/
						e->Init(type, x, y, w, active);
						e->SetVelocityX(vel_x);
						e->SetVelocityY(vel_y);
						e->SetSpeed(speed);
						e->SetHP(hp);
					}
				}
				
				// Base hp
				bs.Read(base_hp);

				SendInitialPosition();
			}
			break;
		case ID_REJECT_PLAYER:
			{
				std::cout << "Rejected player" << std::endl;
				return true;
			}
			break;

		case ID_NEWSHIP:
			{
				unsigned int id;
				bs.Read(id);

				if( id == ships_.at(0)->GetID() )
				{
					// if it is me
					break;
				}
				else
				{
					float x_, y_;
					int type_;
					std::string temp;
					char chartemp[5];

					bs.Read( x_ );
					bs.Read( y_ );
					bs.Read( type_ );
					std::cout << "New Ship pos" << x_ << " " << y_ << std::endl;
					Ship* ship = new Ship(type_, x_, y_);
					temp = "Ship "; 
					temp += _itoa(id, chartemp, 10);
					ship->SetName(temp.c_str());
					ship->setID( id );
					ships_.push_back(ship);
				}

			}
			break;

		case ID_LOSTSHIP:
			{
				unsigned int shipid;
				bs.Read(shipid);
				for (ShipList::iterator itr = ships_.begin(); itr != ships_.end(); ++itr)
				{
					if ((*itr)->GetID() == shipid)
					{
						delete *itr;
						ships_.erase(itr);
						break;
					}
				}
			}
			break;

		case ID_INITIALPOS:
			break;

		case ID_MOVEMENT:
			{
				unsigned int shipid;
				float temp;
				float x,y,w;
				bs.Read(shipid);
				for (ShipList::iterator itr = ships_.begin(); itr != ships_.end(); ++itr)
				{
					if ((*itr)->GetID() == shipid)
					{
						// this portion needs to be changed for it to work
#ifdef INTERPOLATEMOVEMENT
						bs.Read(x);
						bs.Read(y);
						bs.Read(w);

						(*itr)->SetServerLocation( x, y, w ); 

						bs.Read(temp);
						(*itr)->SetServerVelocityX( temp );
						bs.Read(temp);
						(*itr)->SetServerVelocityY( temp );
						bs.Read(temp);
						(*itr)->SetAngularVelocity( temp );

						(*itr)->DoInterpolateUpdate();
#else
						bs.Read(x);
						bs.Read(y);
						bs.Read(w);
						(*itr)->setLocation( x, y, w ); 

						// Lab 7 Task 1 : Read Extrapolation Data velocity x, velocity y & angular velocity
						bs.Read(temp);
						(*itr)->SetVelocityX( temp );
						bs.Read(temp);
						(*itr)->SetVelocityY( temp );
						bs.Read(temp);
						(*itr)->SetAngularVelocity( temp );
#endif

						break;
					}
				}
			}
			break;

		case ID_COLLIDE:
			{
				unsigned int shipid;
				float x, y;
				bs.Read(shipid);
				
				if( shipid == ships_.at(0)->GetID() )
				{
					std::cout << "collided with someone!" << std::endl;
					bs.Read(x);
					bs.Read(y);
					ships_.at(0)->SetX( x );
					ships_.at(0)->SetY( y );
					bs.Read(x);
					bs.Read(y);
					ships_.at(0)->SetVelocityX( x );
					ships_.at(0)->SetVelocityY( y );
#ifdef INTERPOLATEMOVEMENT
					bs.Read(x);
					bs.Read(y);
					ships_.at(0)->SetServerVelocityX( x );
					ships_.at(0)->SetServerVelocityY( y );
#endif	
				}
			}
			break;


		// Lab 13 Task 10 : new cases to handle missile on application side
		case ID_NEWMISSILE:
			{
				float x, y, w;
				int id;
				bs.Read(id);
				bs.Read(x);
				bs.Read(y);
				bs.Read(w);
				missiles_.push_back(new Missile("missile.png", x, y, w, id));
			}
			break;
		case ID_UPDATEMISSILE:
			{
				float x, y, w;
				int id;
				char deleted;
				bs.Read(id);
				bs.Read(deleted);
				for (MissileList::iterator itr = missiles_.begin(); itr !=
					missiles_.end(); ++itr)
				{
					if ((*itr)->GetOwnerID() == id)
					{
						if (deleted == 1)
						{
							delete*itr;
							missiles_.erase(itr);
						}
						else
						{
							bs.Read(x);
							bs.Read(y);
							bs.Read(w);
							(*itr)->UpdateLoc(x, y, w);
							bs.Read(x);
							(*itr)->SetVelocityX(x);
							bs.Read(y);
							(*itr)->SetVelocityY(y);
						}
						break;
					}
				}
			}
			break;
		case ID_NEW_ENEMY:
			{
				int id, hp;
				Enemy::ENEMY_TYPE type;
				float x, y, vel_x, vel_y, speed;
				bs.Read(id);
				bs.Read(type);
				bs.Read(x);
				bs.Read(y);
				bs.Read(vel_x);
				bs.Read(vel_y);
				bs.Read(speed);
				bs.Read(hp);
				Enemy* e = FindEnemyByID(id);
				if (e)
				{
					float w = CalcW(Vector2(vel_x, vel_y));
					e->Init(type, x, y, w);
					e->SetVelocityX(vel_x);
					e->SetVelocityY(vel_y);
					e->SetSpeed(speed);
					e->SetHP(hp);
				}
			}
			break;
		case ID_UPDATE_ENEMY:
			{
				int id;
				bs.Read(id);
				Enemy* e = FindEnemyByID(id);
				if (e)
				{
					float x, y;
					bs.Read(x);
					bs.Read(y);
					e->SetX(x);
					e->SetY(y);
				}
			}
			break;
		case ID_INJURE_ENEMY:
			{
				int id, hp;
				bs.Read(id);
				Enemy* e = FindEnemyByID(id);
				if (e && e->GetActive())
				{
					bs.Read(hp);
					e->SetHP(hp);
				}
			}
			break;
		case ID_DESTROY_ENEMY:
			{
				int id;
				bs.Read(id);
				Enemy* e = FindEnemyByID(id);

				DestroyEnemy(e);
			}
			break;
		case ID_SHOOT:
			{
				int id, damage, owner, target;
				Projectile::PROJECTILE_TYPE type;
				float x, y, w, vel_x, vel_y, speed;
				bs.Read(id);

				Projectile* p = FindProjectileByID(id);
				if (p)
				{
					bs.Read(type);
					bs.Read(x);
					bs.Read(y);
					bs.Read(w);
					bs.Read(vel_x);
					bs.Read(vel_y);
					bs.Read(speed);
					bs.Read(damage);
					bs.Read(owner);
					bs.Read(target);
					
					Ship* sOwner = FindShipByID(owner);
					if (sOwner)
					{
						p->Init(sOwner, type, x, y, w);
						p->SetVelocityX(vel_x);
						p->SetVelocityY(vel_y);
						p->SetSpeed(speed);
						p->SetDamage(damage);
						if (target != -1)
						{
							Enemy* sTarget = FindEnemyByID(target);
							if (sTarget)
							{
								p->SetTarget(sTarget);
							}
						}
					}
				}
			}
			break;
		case ID_UPDATE_PROJECTILE:
			{
				int id, damage, owner, target;
				Projectile::PROJECTILE_TYPE type;
				float x, y, vel_x, vel_y, speed;
				bool active;
				bs.Read(id);

				Projectile* p = FindProjectileByID(id);
				if (p)
				{
					bs.Read(active);
					bs.Read(type);
					bs.Read(x);
					bs.Read(y);
					bs.Read(vel_x);
					bs.Read(vel_y);
					bs.Read(speed);
					bs.Read(damage);
					bs.Read(owner);
					bs.Read(target);

					Ship* sOwner = FindShipByID(owner);
					if (sOwner)
					{
						p->SetOwner(sOwner);
						p->SetType(type);
						p->SetX(x);
						p->SetY(y);
						p->SetActive(active);
						p->SetVelocityX(vel_x);
						p->SetVelocityY(vel_y);
						p->SetSpeed(speed);
						p->SetDamage(damage);
						if (target != -1)
						{
							Enemy* sTarget = FindEnemyByID(target);
							if (sTarget)
							{
								p->SetTarget(sTarget);
							}
						}
					}
				}
			}
			break;
		case ID_DESTROY_PROJECTILE:
			{
				int id;
				bs.Read(id);
				Projectile* p = FindProjectileByID(id);
				if (p && p->GetActive())
				{
					// Reset projectile
					//DestroyProjectile(p);
					p->Reset();
				}
			}
			break;
		case ID_UPDATE_BASE:
			{
				bs.Read(base_hp);
			}
			break;
		case ID_UPDATE_SCORE:
			{
				int id, score;
				bs.Read(id);
				Ship* s = FindShipByID(id);
				if (s)
				{
					bs.Read(score);
					s->SetScore(score);
				}
			}
			break;
		case ID_CHAT_SEND:
			{
				char cMsg[256];
				bs.Read(cMsg);
				chatList.push_back(cMsg);
				chatShowTimer = 5.f;
			}
			break;

		default:
			std::cout << "Unhandled Message Identifier: " << (int)msgid << std::endl;

		}
		rakpeer_->DeallocatePacket(packet);
	}

	if (base_hp <= 0)
	{
		return true;
	}

	// Send projectile updates
	/*static const int SYNCS_PER_SEC = 24;
	static const float TIME_PER_SYNC = 1 / SYNCS_PER_SEC;
	static float projSendTimer = TIME_PER_SYNC;
	if (projSendTimer < TIME_PER_SYNC)
	{
		projSendTimer += timedelta;
	}
	else
	{
		for (vector<Projectile*>::iterator it = projectileList.begin(); it != projectileList.end(); ++it)
		{
			Projectile* p = *it;
			if (p->GetActive() && p->GetOwner() == ships_.at(0))
			{
				RakNet::BitStream sendProj;
				sendProj.Write((unsigned char)ID_UPDATE_PROJECTILE);
				sendProj.Write(p->GetID());
				sendProj.Write(p->GetActive());
				sendProj.Write(p->GetType());
				sendProj.Write(p->GetX());
				sendProj.Write(p->GetY());
				sendProj.Write(p->GetVelocityX());
				sendProj.Write(p->GetVelocityY());
				sendProj.Write(p->GetSpeed());
				sendProj.Write(p->GetDamage());
				sendProj.Write(p->GetOwner()->GetID());
				// Send target id if available
				if (p->GetTarget())
				{
					sendProj.Write(p->GetTarget()->GetID());
				}
				else
				{
					sendProj.Write(-1);
				}
				rakpeer_->Send(&sendProj, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
				std::cout << p->GetX() << " | " << p->GetY() << std::endl;
			}
		}
		projSendTimer = 0.f;
	}*/

	// Send data
	float timeToSync = 1000 / 24; // Sync 24 times in a second (Millisecond)
	if (RakNet::GetTime() - timer_ > timeToSync)
	{
		timer_ = RakNet::GetTime(); // Store previous time
		RakNet::BitStream bs2;
		unsigned char msgid = ID_MOVEMENT;
		bs2.Write(msgid);

#ifdef INTERPOLATEMOVEMENT
		bs2.Write(ships_.at(0)->GetID());
		bs2.Write(ships_.at(0)->GetServerX());
		bs2.Write(ships_.at(0)->GetServerY());
		bs2.Write(ships_.at(0)->GetServerW());
		bs2.Write(ships_.at(0)->GetServerVelocityX());
		bs2.Write(ships_.at(0)->GetServerVelocityY());
		bs2.Write(ships_.at(0)->GetAngularVelocity());

#else
		bs2.Write(ships_.at(0)->GetID());
		bs2.Write(ships_.at(0)->GetX());
		bs2.Write(ships_.at(0)->GetY());
		bs2.Write(ships_.at(0)->GetW());
		// Lab 7 Task 1 : Add Extrapolation Data velocity x, velocity y & angular velocity
		bs2.Write(ships_.at(0)->GetVelocityX());
		bs2.Write(ships_.at(0)->GetVelocityY());
		bs2.Write(ships_.at(0)->GetAngularVelocity());
#endif

		rakpeer_->Send(&bs2, HIGH_PRIORITY, RELIABLE, 0, UNASSIGNED_SYSTEM_ADDRESS, true);


		// Lab 13 Task 11 : send missile update 
		/*if (mymissile)
		{
			RakNet::BitStream bs3;
			unsigned char msgid2 = ID_UPDATEMISSILE;
			unsigned char deleted = 0;
			bs3.Write(msgid2);
			bs3.Write(mymissile->GetOwnerID());
			bs3.Write(deleted);
			bs3.Write(mymissile->GetX());
			bs3.Write(mymissile->GetY());
			bs3.Write(mymissile->GetW());
			bs3.Write(mymissile->GetVelocityX());
			bs3.Write(mymissile->GetVelocityY());
			rakpeer_->Send(&bs3, HIGH_PRIORITY, UNRELIABLE_SEQUENCED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
		}*/

		// Send update projectile
		/*for (int i = 0; i < projectileUpdateList.size(); ++i)
		{
			Projectile* p = projectileList[i];
			if (p && p->GetActive())
			{
				RakNet::BitStream sendProj;
				sendProj.Write((unsigned char)ID_UPDATE_PROJECTILE);
				sendProj.Write(p->GetID());
				sendProj.Write(p->GetActive());
				sendProj.Write(p->GetType());
				sendProj.Write(p->GetX());
				sendProj.Write(p->GetY());
				sendProj.Write(p->GetVelocityX());
				sendProj.Write(p->GetVelocityY());
				sendProj.Write(p->GetSpeed());
				sendProj.Write(p->GetDamage());
				sendProj.Write(p->GetOwner()->GetID());
				// Send target id if available
				if (p->GetTarget())
				{
					sendProj.Write(p->GetTarget()->GetID());
				}
				else
				{
					sendProj.Write(-1);
				}
				rakpeer_->Send(&sendProj, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
			}
		}
		projectileUpdateList.clear();*/
	}

	return false;
}
Example #13
0
int main(int argc, char *argv[])
{
    enum { GAME_COMPUTER, GAME_NETWORK, GAME_UNKNOWN } game_type = GAME_UNKNOWN;
    char *remote_address;
    int i;
	
    if (argc < 2) {
	printf("Penguin Warrior\n");
	printf("Usage: pw [ mode ] [ option ... ]\n");
	printf("  Game modes (choose one):\n");
	printf("    --computer\n");
	printf("    --net <remote ip address>\n");
	printf("  Display options, for tweaking and experimenting:\n");
	printf("    --fullscreen\n");
	printf("    --hwsurface  (use an SDL hardware surface if possible)\n");
	printf("    --doublebuf  (use SDL double buffering if possible)\n");
	printf("  The display options default to a windowed, software buffer.\n");
	exit(EXIT_FAILURE);
    }

    /* Process command line arguments. There are plenty of libraries for command
       line processing, but our needs are simple in this case. */
    for (i = 0; i < argc; i++) {

	/* Networked or scripted opponent? */
	if (!strcmp(argv[i], "--computer")) {
	    game_type = GAME_COMPUTER;
	    continue;
	} else if (!strcmp(argv[i], "--net")) {
	    game_type = GAME_NETWORK;
	    if (++i >= argc) {
		printf("You must supply an IP address for --net.\n");
		exit(EXIT_FAILURE);
	    }
	    remote_address = argv[i];
	    continue;

	    /* Display-related options */
	} else if (!strcmp(argv[i], "--hwsurface")) {
	    hwsurface = 1;
	} else if (!strcmp(argv[i], "--doublebuf")) {
	    doublebuf = 1;
	} else if (!strcmp(argv[i], "--fullscreen")) {
	    fullscreen = 1;
	}
    }

    switch (game_type) {
    case GAME_COMPUTER:
	opponent_type = OPP_COMPUTER;
	printf("Playing against the computer.\n");
	break; 
			
    case GAME_NETWORK:
	printf("Sorry, network play is not implemented... yet!\n");
	exit(EXIT_FAILURE);
			
    default:
	printf("You must select a game type.\n");
	exit(EXIT_FAILURE);
    }
	
    /* Initialize our random number generator. */
    initrandom();

    /* Fire up SDL. */
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
	printf("Unable to initialize SDL: %s\n", SDL_GetError());
	exit(EXIT_FAILURE);
    }
    atexit(SDL_Quit);
	
    /* Set an appropriate 16-bit double buffered video mode. */
    if (SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 16,
			 (hwsurface ? SDL_HWSURFACE : SDL_SWSURFACE) |
			 (doublebuf ? SDL_DOUBLEBUF : 0) |
			 (fullscreen ? SDL_FULLSCREEN : 0)) == NULL) {
	printf("Unable to set video mode: %s\n", SDL_GetError());
	exit(EXIT_FAILURE);
    }
	
    /* Save the screen pointer for later use. */
    screen = SDL_GetVideoSurface();
	
    /* Set the window caption to the name of the game. */
    SDL_WM_SetCaption("Penguin Warrior", "Penguin Warrior");
	
    /* Hide the mouse pointer. */
    SDL_ShowCursor(0);

    /* Start the OpenAL-based audio system. */
    InitAudio();

    /* Initialize music and give the music system a file. */
    InitMusic();
    if (LoadMusic("reflux.ogg") != 0) {
	/* If that failed, don't worry about it. */
	printf("Unable to load reflux.ogg.\n");
    }
		
    /* Load the game's data into globals. We can only do this after the
       video and audio subsystems are ready for action, since the loading
       routines interact with SDL and OpenAL. */
    LoadGameData();

    /* Initialize the background starfield. */
    InitBackground();
	
    /* Play! */
    InitPlayer();
    InitOpponent();
    PlayGame();

    /* Unhide the mouse pointer. */
    SDL_ShowCursor(1);
	
    /* Unload data. */
    UnloadGameData();

    /* Shut down audio. */
    CleanupMusic();
    CleanupAudio();

    return 0;
}
Example #14
0
void Stage01::OnStart()
{
	Stage::OnStart();

	InitBackground();
}