🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Useful code snippets

Started by
5 comments, last by Russell 20 years, 10 months ago
I thought it might be nice to have a thread to share helpful functions or code snippets. So post your little helper functions here. I got really tired of doing sprintf and Taunt all over the place, so I wrote a Say() function. It works just like printf(). Be sure to #include <cstdarg> void Say (const char * format, ...) { char buffer[1024]; va_list args; va_start(args, format); vsprintf(buffer, format, args); g_pCore->Taunt(buffer); } You can use it like this: // Bot will spin around and tell you how many things it sees void BotName::Update() { Say("I see %d things", g_pCore->GetNumObjectsInSight()); g_pCore->TurnLeft(TURN_SLOW); } BTW Kevin, when I ran this code, the bot sees zero things when it looks into a corner, but that''s for the bug thread.
Advertisement
The buffer in your function only needs to be 35 chars long as thats the max length of taunts in Debug more, or 20 in normal..

Good idea about code snippets, so i'm putting in my timer class. I use it alot, its not very accurate, only using GetTickCount(), but its a start and can be modified and done alot better. Here it is:
header file:

#include <windows.h>class CTimer  {public:	CTimer();	virtual ~CTimer();	int GetTime();	void Reset();	int Stop();	void Start();	bool IsTiming()	{	return IsTiming;	}	int Time;private:	int EndTick;	int StartTick;	bool Timing;};



and cpp file:

   CTimer::CTimer(){	Reset();				//Reset to 0.	Timing = false;}CTimer::~CTimer(){}void CTimer::Start(){	StartTick = GetTickCount();		//Store current Tick Count in StartTick.	Timing = true;}int CTimer::Stop(){	if(StartTick == 0)	{		return 0;	}	EndTick = GetTickCount();		//Store TickCount in EndTick.	Timing = false;	Time+=(EndTick - StartTick);	return EndTick - StartTick;				//Return Time.}void CTimer::Reset(){	if(Timing)		//If the timer is still active, stop timing	{		Stop();	}		StartTick = 0;					//Reset values to 0.	EndTick = 0;	Time = 0;}int CTimer::GetTime(){	if(StartTick == 0)	{		return 0;	}		int tmpTick = GetTickCount();	return tmpTick - StartTick;}


Like I say it could probably be done better, but my little contribution..

Heres a comment/documentation paragraph i wrote, so i'm not sure if it makes sence, i can read it..

To time, user must call the Start() function. When user wishes to stop timing call the Stop() function.Stop will return the time interval counted, however, the user can access this at a later time throughthe public variable Time. Reset() resets the timing values (including Time) to 0. If the user should start timing again without calling Reset(), then the time will be added to the last time interval.Use the GetTime() function to get the time without interupting timing. Use this to display live datafrom the timer with out stopping it.  


EDIT: Changed code so it would work with modification i made before I posted.

-J

[edited by - jason2jason on August 4, 2003 5:27:07 PM]
I think this code works, but it's a pain to look at. Maybe somebody can find this useful. It just does rotations.

PS: No, i normally don't code like this .

//-------------------------------------------------------------------------------------//// CONSTANTS                                                                           ////-------------------------------------------------------------------------------------////Constant speed values for movementconst float SPEED_TURN_SLOW = 2.0f;const float SPEED_TURN_FAST = 4.0f;const float SPEED_MOVE_NORMAL = 0.4444f;const float SPEED_MOVE_HIGH = 0.8888f;const float SPEED_MOVE_REVERSE = 0.5555f;const float SPEED_STRAFE = 0.3333f;//-------------------------------------------------------------------------------------//// CLASSES AND STRUCTURE                                                               ////-------------------------------------------------------------------------------------////Manages the bot and world in the dllclass botSystem{public:   //////////////////////////////////////////////////////////////////////////////////////   //Call this every frame   void update()   {      //Rotate      if(m_state==1)      {         //Check if we're going left or right         if(m_value<0)         {            //Going left            if(-m_value>SPEED_TURN_FAST)            {               m_pCore->TurnLeft(TURN_FAST);               m_value+=SPEED_TURN_FAST;            }            else if(-m_value>SPEED_TURN_SLOW)            {               m_pCore->TurnLeft(TURN_SLOW);               m_value+=SPEED_TURN_SLOW;            }            else            {               m_state=0;               m_value=0;            }         }         else if(m_value>0)         {            //Going right            if(m_value>SPEED_TURN_FAST)            {               m_pCore->TurnRight(TURN_FAST);               m_value-=SPEED_TURN_FAST;            }            else if(m_value>SPEED_TURN_SLOW)            {               m_pCore->TurnRight(TURN_SLOW);               m_value-=SPEED_TURN_SLOW;            }            else            {               m_state=0;               m_value=0;            }         }         else         {            //No rotation necessary            m_value=0;            m_state=0;         }      }      else if(m_state==2)      {         m_state=0;         m_pCore->TurnRight(TURN_SLOW);         m_value=0;      }   }   //////////////////////////////////////////////////////////////////////////////////////   float objRealObjRotation(int objID) // because of the angle problem, finds the true angle   {      //First get the object direction      int tt;      float t,dir,dir2;      m_pCore->GetObjectsInSight(objID,tt,dir,t,t);      //Rotate a little bit and see which way it changes      m_pCore->TurnLeft(TURN_SLOW);      m_pCore->GetObjectsInSight(objID,tt,dir2,t,t);      t=dir-dir2;      if(t>0)         dir2=dir;      else         dir2=-dir;      m_value=dir2;      m_state=2;      return(dir2);   }   //////////////////////////////////////////////////////////////////////////////////////   void rotate(int deg) //+ right, - left   {      m_state=1;      m_value=deg;   }   //////////////////////////////////////////////////////////////////////////////////////   //Set the core   void coreSet(ICore* pc)   {      m_pCore=pc;   }   //////////////////////////////////////////////////////////////////////////////////////private:   ICore* m_pCore;   //0 = none   //1 = rotate   //2 = real object position find (returns in update)   int m_state;   float m_value;};


---
Brent Gunning | My Site

[edited by - RapidStunna on August 4, 2003 5:27:16 PM]
quote: The buffer in your function only needs to be 35 chars long as thats the max length of taunts in Debug more, or 20 in normal..

Well, that isn''t entirely true. Sure, I don''t need 1024 chars, but since it works like printf, it will expand things. A couple of expanded floats can make a big difference. I think it''s better to let Say() handle a string that is too long rather than hope the user always plays by the rules and never enters a string that expands past 20 or 35 chars. You know, Murphy''s laws and all of that.
Perhaps it would be better to use vsnprintf to save a little memory and not have to worry about buffer overflows.
Chess is played by three people. Two people play the game; the third provides moral support for the pawns. The object of the game is to kill your opponent by flinging captured pieces at his head. Since the only piece that can be killed is a pawn, the two armies agree to meet in a pawn-infested area (or even a pawn shop) and kill as many pawns as possible in the crossfire. If the game goes on for an hour, one player may legally attempt to gouge out the other player's eyes with his King.
Why not simply use a std::basic_stringstream?

 #include <sstream>....std::stringstream buffer;buffer << "This works just as well as sprintf!";;buffer << "And it scales up to any size!";buffer << "Numbers work as well!" << 2 << 5.0f;g_pCore->Taunt(buffer.str().c_str());


VirtuallyOnline.RecommendedBooks().GameDevChatStats().Forums()
That's even better. Maybe something like this:
#include <stdexcept>#include <sstream>std::stringstream say;class se {} endsay;std::ostream & operator << (std::ostream &ss, se &ref) {  std::stringstream *ptr = dynamic_cast<std::stringstream *>(&ss);  if(!ptr)   throw std::invalid_argument("endsay should only be used with stringstream objects.");  else if(!g_pCore)   throw std::runtime_error("g_pCore is null.");  g_pCore->Taunt(ptr->str().data());  ptr->str("");  return ss; }...say << "I see " << g_pCore->GetNumObjectsInSight() << " things." << endsay;


[edited by - smart_idiot on August 8, 2003 1:43:25 AM]
Chess is played by three people. Two people play the game; the third provides moral support for the pawns. The object of the game is to kill your opponent by flinging captured pieces at his head. Since the only piece that can be killed is a pawn, the two armies agree to meet in a pawn-infested area (or even a pawn shop) and kill as many pawns as possible in the crossfire. If the game goes on for an hour, one player may legally attempt to gouge out the other player's eyes with his King.

This topic is closed to new replies.

Advertisement