.:: Bots United ::.  
filebase forums discord server github wiki web
cubebot epodbot fritzbot gravebot grogbot hpbbot ivpbot jkbotti joebot
meanmod podbotmm racc rcbot realbot sandbot shrikebot soulfathermaps yapb

Go Back   .:: Bots United ::. > YappA > Offtopic
Offtopic Just anything. You have time to waste ? Prove it !!!

Reply
 
Thread Tools
Show off your finest piece of code!
Old
  (#1)
stefanhendriks
RealBot Author
 
stefanhendriks's Avatar
 
Status: Offline
Posts: 3,088
Join Date: Nov 2003
Location: Netherlands
Default Show off your finest piece of code! - 29-12-2004

Just was thinking about this; did you ever had a function or a piece of code you tihnk it was uber leet? By its simplicity, or by its uniqueness, or its stupidness, or the way its written, etc. Post it here!

Also, if you find some cool comments in ur code, i would like to see them (including the code when possible)... i love it when i see:

Code:
// why does this work?
line of code
Lemme begin, in my RTS (which you can find info about @ Fundynamic (link in my sig))... its HUGE, but i have this main function, which i am fond off:

Code:
/*
Function: main()
Purpose : make sure the darn thing works.
  */
int main()
{

 // Initialize game first
 game.init();
 
 // Install everything
 if (install()) 
   game.run(); // run 

 Profile.dumpprint(0);

 // Destroy font of Allegro FONT library
 alfont_destroy_font(game_font);

 logbook("\n--------");
 logbook("SHUTDOWN");
 logbook("--------");

 // Exit the font library (must be first)
 alfont_exit();
 logbook("Allegro FONT library shut down.");

 // Now we are all neatly closed, we exit Allegro and return to OS hell.
 allegro_exit();
 logbook("Allegro shut down.");
 logbook("\nThanks for playing!");
 return 0;
}
END_OF_MAIN();
as you can see i like it to code like that, aka in the CS2D project (which died horribly) (does anyone wants the source to try it out?)

Code:
int main()
{
 if (install())
  game.run();
 
 alfont_exit();
 logbook("Allegro FONT library shut down.");
 
 // Now we are all neatly closed, we exit Allegro and return to OS hell.
 allegro_exit();
 logbook("Allegro shut down.");
 logbook("\nThanks for playing!");
 return 0;
}
END_OF_MAIN();
... funny pieces:

Code:
// Scale this
  fScale = fDistance / 4096;
  // 20/06/04 - stefan - and then i wondered, why would i limit fScale that much?
  // (fScale > 0.9)
(yeah i saw the light)

Code:
 // * so you are asking yourself why i do == true all the time huh?
	// * i just love the blue color in my MSVC :)
i just love this

Code:
// CHECK FOR STEAM;
  // As lazy as i am i use pierre's code which is in our modified metamod dll.
  // Omg, why use so many comments? Sory pierre for ripping some pieces out.
  // Pierre-Marie Baty -- STEAM/NOSTEAM auto-adaptative fix -- START
  // to check whether Steam is installed or not, I test Steam-specific files.
  // if you know a more orthodox way of doing this, please tell me.
  // test file, if found = STEAM Linux/Win32 dedicated server
  fp = fopen ("valve/steam.inf", "rb");
  if (fp != NULL)
rofl:

Code:
// set wait time (stand still, looks like bot is thinking hehe)
 pBot->f_wait_time = pBot->fWanderTime;
and:

Code:
/*
	 EMPTY - BANNED - UNUSED - MUHAHAHA
	 SINCE METAMOD ;) BUILD 2053


Author of RealBot, "Arrakis" and "Dune 2 - The Maker" | co-Founder of Bots-United | Fundynamic | Blog | E-Mail me
  
Reply With Quote
Re: Show off your finest piece of code!
Old
  (#2)
Leagle
Failed student
 
Leagle's Avatar
 
Status: Offline
Posts: 640
Join Date: Dec 2003
Location: Plymouth (No longer!)
Default Re: Show off your finest piece of code! - 29-12-2004

Code:
if (code) = yes ; (brain) SWITCH OFF

As you can see, there's a reason I dropped computing.9_9


RESISTANCE IS use-LESS!

Brother Boot Knife of Quiet Reflection

The following errors occurred when this message was submitted:
  1. The text that you have entered is too long (492645 characters). Please shorten it to 50000 characters long.

Last edited by Leagle; 29-12-2004 at 23:18..
  
Reply With Quote
Re: Show off your finest piece of code!
Old
  (#3)
sfx1999
Member
 
sfx1999's Avatar
 
Status: Offline
Posts: 534
Join Date: Jan 2004
Location: Pittsburgh, PA, USA
Default Re: Show off your finest piece of code! - 30-12-2004

I've seen some good ones in the HL SDK and in Quake/Quake 2.

Botman has them documented here -> http://www.planethalflife.com/botman/humor.shtml


sfx1999.postcount++
  
Reply With Quote
Re: Show off your finest piece of code!
Old
  (#4)
Rick
Council Member
 
Rick's Avatar
 
Status: Offline
Posts: 690
Join Date: Dec 2003
Location: Holland
Default Re: Show off your finest piece of code! - 30-12-2004

Cube bot, main think function:

Code:
     void CBot::Think()
     {
     	 if (intermission)
     		  return;
     			 
     	 // Bot is dead?
     	 if (m_pMyEnt->state == CS_DEAD)
     	 {
     		  if(lastmillis-m_pMyEnt->lastaction<1200)
     		  {
     			   m_pMyEnt->move = 0;
     			   moveplayer(m_pMyEnt, 1, false);
     		  }
     		  else if (!m_arena)
     			   Spawn();
     	 
     		  return;
     	 }
 							 
     	 CheckItems();
     	 CheckQuad(curtime);
     	 
     	 // Basic AI
     	 if (!BotManager.IdleBots())
     	 {			   
     		  // Default bots will run forward
     		  m_pMyEnt->move = 1;
     		
     		  // Default bots won't strafe
     		  m_pMyEnt->strafe = 0;
     		
     		  if (!BotManager.BotsShoot() && m_pMyEnt->enemy)
     			   m_pMyEnt->enemy = NULL;
     			 
     		  // Find enemy
     		  if (BotManager.BotsShoot() && FindEnemy())
     		  {
     			   // Shoot at enemy
     			   ShootEnemy();
     		  }
     
     		  // Navigate		
     		  HomeThroughMap();
     	 }
     	 else
     		  m_pMyEnt->move = 0;
     				  
     	 // Aim to ideal yaw and pitch
     	 AimToIdeal();
     	 
     	 // Store current location, to see if the bot is stuck
     	 m_vPrevOrigin = m_pMyEnt->o;
     		
     	 // Move the bot
     	 moveplayer(m_pMyEnt, 1, false);
     	 
     	 // Update bot info on all clients
     	 SendBotInfo();
     }
My favourite template (esf & cube bot)

Code:
    template <class C> class TMultiChoice 
    {
    	struct SMultiChoice
    	{
    		int MinVal;
    		int MaxVal;
    		C Choice;
    		SMultiChoice(void) : MinVal(0), MaxVal(0){};
    	};
    
    	int TotalVal;
    	TLinkedList<SMultiChoice*> *pChoiceList;
    
    public:
    	TMultiChoice(void) : TotalVal(0) // Constructor
    	{
    			 pChoiceList = new TLinkedList<SMultiChoice*>;
    	};
    	
    	~TMultiChoice(void) // Destructor
    	{
    		while(pChoiceList->Empty() == false)
    		{
    			SMultiChoice *pEntry = pChoiceList->Pop();
    			if (pEntry)
    				delete pEntry;
    			else
    				break;
    		}
    		delete pChoiceList;
    		pChoiceList = NULL;
    	}
    
    	void Insert(C Choice, short Percent = 50)
    	{
    		if (Percent == 0)
    			return;
    
    		SMultiChoice *pChoiceEntry = new SMultiChoice;
    		
    		pChoiceEntry->MinVal = TotalVal;
    		pChoiceEntry->MaxVal = TotalVal + Percent;
    		pChoiceEntry->Choice = Choice;
    
    		pChoiceList->AddNode(pChoiceEntry);
    
    		TotalVal += Percent;
    	};
    
    	bool FindSelection(SMultiChoice *MS, int Choice)
    	{
    		if ((Choice >= MS->MinVal) && (Choice < MS->MaxVal))
    		{
    			return true;
    		}
    		return false;
    	}
    
    	void ClearChoices(void)
    	{
    		TotalVal = 0;
    		while(pChoiceList->Empty() == false)
    			delete pChoiceList->Pop();
    	}
    
    	bool GetSelection(C &Var)
    	{
    		int Choice = RandomLong(0, (TotalVal - 1));
    		TLinkedList<SMultiChoice*>::node_s *pNode = pChoiceList->GetFirst();
    
    		while(pNode)
    		{
 			if ((Choice >= pNode->Entry->MinVal) && (Choice < pNode->Entry->MaxVal))
    			{
 				Var = pNode->Entry->Choice;
    				return true;
    			}
    			pNode = pNode->next;
    		}
    
    		return false;
    	}
    };
Used if there are things to select, like weapons, where each choice has a different score. For example:

Code:
   TMultiChoice WeaponChoices;
    
    WeaponChoices.Insert(GUN_FIST, 20);
    WeaponChoices.Insert(GUN_RIFLE, 50); // Higher chance for rifle

Here something new in the cube bot: used when bots have an enemy and still want an item(ammo etc). They will strafe to it but keep aiming(and shooting) at their enemy.

Code:
   			   vec v = { m_pTargetEnt->x, m_pTargetEnt->y,
 						 S(m_pTargetEnt->x, m_pTargetEnt->y)->floor+m_pMyEnt->eyeheight };
   			   vec v2, forward, right, up, cross;
   			   float flDot;
   
  			 AnglesToVectors(GetViewAngles(), forward, right, up);
   
   			   v2 = v;
   			   vsub(v2, m_pMyEnt->o);
   			   v2.z = 0.0f; // Make 2D
   			   v2 = Normalize(v2);
   			   forward.z = 0; // Make 2D
   		  
   			   flDot = dotprod(v2 , forward);
   			   cross = CrossProduct(v2, forward);
   			   
   			   bool IsLeft = (cross.z < -0.1f);
   			   bool IsRight = (cross.z > 0.1f);
   			   bool IsBehind = (flDot < 0.1f);
   			   bool IsInFront = (flDot > 0.1f);
   			   
   			   particle_trail(1, 500, m_pMyEnt->o, v);
   
   			   EDirection eMoveDir = FORWARD;
 											 
 			 if (IsInFront && !IsLeft && !IsRight) // ent is straight forward
   			   {
   				    eMoveDir = FORWARD;
 				 m_pMyEnt->move = m_iMoveDir = 1; // move forward
 				 m_pMyEnt->strafe = m_iStrafeDir = 0; // Don't strafe
 			 }												 
 			 else if (IsBehind && !IsLeft && !IsRight) // Ent is straight behind bot
   			   {
   				    eMoveDir = BACKWARD;
 				 m_pMyEnt->move = m_iMoveDir = -1; // Move backward
 				 m_pMyEnt->strafe = m_iStrafeDir = 0; // Don't strafe
   			   }
 			 else if (!IsBehind && !IsInFront && IsLeft) // Ent is straight left
   			   {
   				    eMoveDir = LEFT;
 				 m_pMyEnt->move = m_iMoveDir = 0; // don't move back or forward
 				 m_pMyEnt->strafe = m_iStrafeDir = -1; // Strafe left
   			   }
 			 else if (!IsBehind && !IsInFront && IsRight) // Ent is straight right
   			   {
   				    eMoveDir = RIGHT;
 				 m_pMyEnt->move = m_iMoveDir = 0; // don't move back or forward
 				 m_pMyEnt->strafe = m_iStrafeDir = 1; // Strafe right
 			 }			 
 			 else if (IsInFront && IsLeft) // Ent is forward-left
   			   {
   				    eMoveDir = FORWARD_LEFT;
 				 m_pMyEnt->move = m_iMoveDir = 1; // Move forward
 				 m_pMyEnt->strafe = m_iStrafeDir = -1; // Strafe left
   			   }
 			 else if (IsInFront && IsRight) // Ent is forward-right
   			   {
   				    eMoveDir = FORWARD_RIGHT;
 				 m_pMyEnt->move = m_iMoveDir = 1; // Move forward
 				 m_pMyEnt->strafe = m_iStrafeDir = 1; // Strafe right
 			 }			 
 			 else if (IsBehind && IsLeft) // ent is backward-left
   			   {
   				    eMoveDir = BACKWARD_LEFT;
 				 m_pMyEnt->move = m_iMoveDir = -1; // Move backward
 				 m_pMyEnt->strafe = m_iStrafeDir = -1; // Strafe left
   			   }
 			 else if (IsBehind && IsRight) // ent is backward-right
   			   {
   				    eMoveDir = BACKWARD_RIGHT;
 				 m_pMyEnt->move = m_iMoveDir = -1; // Move backward
 				 m_pMyEnt->strafe = m_iStrafeDir = 1; // Strafe right
   			   }
   			   
  			 m_iCombatNavTime = lastmillis + RandomLong(125, 250);
   			   
   			   // Check if bot needs to jump
   			   vec from = m_pMyEnt->o;
   			   from.z -= 1.0f;
   			   if (!IsVisible(from, eMoveDir, 3.0f, false))
  				 m_pMyEnt->jumpnext = true;

Aiming in cube bot(maths obviously not by me )
Code:
  void CBot::AimToVec(const vec &o)
  {
  	 m_pMyEnt->targetpitch = atan2(o.z-m_pMyEnt->o.z, GetDistance(o))*180/PI;
  	 m_pMyEnt->targetyaw = -(float)atan2(o.x - m_pMyEnt->o.x, o.y -
 										 m_pMyEnt->o.y)/PI*180+180;
  }
Handy for rocketlaunchers:

Code:
  // Prediction:
  // - pos: Current position
  // - vel: Current velocity
  // - Time: In seconds, predict how far it is after Time seconds
  vec PredictPos(vec pos, vec vel, float Time)
  {
  	 float flVelLength = sqrt(vel.x*vel.x + vel.y*vel.y + vel.z*vel.z);
  	
  	 if (flVelLength <= 1.0)
  		  return pos; // don't bother with low velocities...
  
  	 float speed = flVelLength * Time;
  	 float flTemp = 1/flVelLength;
  	 vec vecNormalize;
  	 
  	 vecNormalize.x = vel.x * flTemp;
  	 vecNormalize.y = vel.y * flTemp;
  	 vecNormalize.z = vel.z * flTemp;
  	 
  	 vec v_src = pos;
  	 vmul(vecNormalize, speed);
  	 vec v_end = v_src;
  	 vadd(v_end, vecNormalize);
  	 
  	 return v_end;
  }
A* Function, was pretty happy when it was done:
Code:
  // return true when done calculating
  bool CBot::AStar()
  {
  	 if (!m_pCurrentGoalWaypoint || !m_pCurrentWaypoint)
  	 {
  		  m_bCalculatingAStarPath = false;
  		  return true;
  	 }
  
  	 // Ideas by PMB :
  	 // * Make locals static to speed up a bit
  	 // * MaxCycles per frame and make it fps dependent
  
  	 static int iMaxCycles;
  	 static int iCurrentCycles;
  	 static float newg;
  	 static waypoint_s *n, *n2;
  	 static TLinkedList<waypoint_s *>::node_s *pPath = NULL;
  
  	 iMaxCycles = 10 * BotManager.m_iFrameTime;
  	 iCurrentCycles = 0;
  
  	 if (!m_bCalculatingAStarPath)
  	 {
  		  m_pCurrentWaypoint->g = 0.0f;
 		 m_pCurrentWaypoint->f = m_pCurrentWaypoint->g + GetDistance(m_pCurrentGoalWaypoint->v_origin);
  		  m_pCurrentWaypoint->pParent = NULL;
  		  m_AStarOpenList.Clear();
  		  m_AStarClosedList.DeleteAllNodes();
  		  m_AStarOpenList.AddEntry(m_pCurrentWaypoint, m_pCurrentWaypoint->f);
  		  
  		  m_AStarNodeList.DeleteAllNodes();
  	 }
  
  	 while(!m_AStarOpenList.Empty())
  	 {
  		  if (iCurrentCycles >= iMaxCycles)
  		  {
  			   m_bCalculatingAStarPath = true;
  			   return false;
  		  }
  
  		  n = m_AStarOpenList.Pop();
  
  		  // Done with calculating
  		  if (n == m_pCurrentGoalWaypoint)
  		  {
  			   while(n)
  			   {
 				 m_AStarNodeList.PushNode(n);
  				    n = n->pParent;
  			   }
  
  			   m_AStarOpenList.Clear();
  			   m_AStarClosedList.DeleteAllNodes();
  
  			   m_bCalculatingAStarPath = false;
  			   return true;
  		  }
  
  		  pPath = n->ConnectedWPs.GetFirst();
  		  while(pPath)
  		  {
  			   n2 = pPath->Entry;
  
  			   newg = AStarCost(n, n2);
  
  			   if ((n2->g <= newg) &&
 				 ((m_AStarClosedList.IsInList(n2) || m_AStarOpenList.IsInList(n2, n2->f))))
  			   {
  				    pPath = pPath->next;
 					continue;
  			   }
  			   
  			   n2->pParent = n;
  			   n2->g = newg;
 			 n2->f = n2->g + GetDistance(n2->v_origin, m_pCurrentGoalWaypoint->v_origin);
  
  			   m_AStarClosedList.DeleteEntry(n2);
  
  			   if (!m_AStarOpenList.IsInList(n2, n2->f))
  			   {
 				 m_AStarOpenList.AddEntry(n2, n2->f);
  			   }
  			   pPath = pPath->next;
  		  }
  		  
  		  m_AStarClosedList.PushNode(n);
  		  iCurrentCycles++;
  	 }
  
  	 // Failed making path
  	 conoutf("Path failed");
  	 m_AStarOpenList.Clear();
  	 m_AStarClosedList.DeleteAllNodes();	 
  	 m_bCalculatingAStarPath = false;
  	 return true;
  }
And I saw this from a n00b somewhere at a forum
Code:
  int blah=0;
  blah++;
  blah++;
  blah++;
  blah++;

As usual most code is inspired by PMB, he has some nice ideas *hugs*
  
Reply With Quote
Re: Show off your finest piece of code!
Old
  (#5)
sfx1999
Member
 
sfx1999's Avatar
 
Status: Offline
Posts: 534
Join Date: Jan 2004
Location: Pittsburgh, PA, USA
Default Re: Show off your finest piece of code! - 30-12-2004

Code:
#include <iostream>
   #include <stdlib.h>
   
   #define BIT0 1
   #define BIT1 2
   #define BIT2 4
   #define BIT3 8
   #define BIT4 16
   #define BIT5 32
   #define BIT6 64
   #define BIT7 128
   
   using namespace std;
   
   int main(void)
   {
     char AsciiStorageArray[256];
     cout << "Insert the phrase to be translated: ";
     cin.getline(AsciiStorageArray, 255);
     cout << endl << "Streaming: ";
     
     int i;
     for (i=0; i < 256; i++)
     {
   	if (AsciiStorageArray[i] == 0)
   	  break;
   	if (AsciiStorageArray[i] & BIT7)
   	  cout << 1;
   	else
   	  cout << 0;
   	if (AsciiStorageArray[i] & BIT6)
   	  cout << 1;
   	else
   	  cout << 0;
   	if (AsciiStorageArray[i] & BIT5)
   	  cout << 1;
   	else
   	  cout << 0;
   	if (AsciiStorageArray[i] & BIT4)
   	  cout << 1;
   	else
   	  cout << 0;
   	if (AsciiStorageArray[i] & BIT3)
   	  cout << 1;
   	else
   	  cout << 0;
   	if (AsciiStorageArray[i] & BIT2)
   	  cout << 1;
   	else
   	  cout << 0;
   	if (AsciiStorageArray[i] & BIT1)
   	  cout << 1;
   	else
   	  cout << 0;
   	if (AsciiStorageArray[i] & BIT0)
   	  cout << 1;
   	else
   	  cout << 0;
   	cout << " ";
     }
     
     cout << endl << "Thank you and have a very safe day" << endl;
     
     system("PAUSE");	
     return 0;


sfx1999.postcount++
  
Reply With Quote
Re: Show off your finest piece of code!
Old
  (#6)
@$3.1415rin
Council Member, Author of JoeBOT
 
@$3.1415rin's Avatar
 
Status: Offline
Posts: 1,381
Join Date: Nov 2003
Location: Germany
Default Re: Show off your finest piece of code! - 30-12-2004

@sfx : that code would be pretty small when using shift ops "<<"

to make some temporary conclusion : some people seem to like rows of if statements and other ppls best piece of code is that with very few comments

and ha, my AStar "Taskmanager" idea has found it's way over pierre to cube bot - nice !

some piece of nice code is attached ... my AStarMachine with a plugininterface for almost everything needed here, fast, reliable, never had to touch that code since optimizing

another nice thing is my n-dimensional vector class using SSE, that's a mess ... but well, not my finest piece of code

but percepting entities in joebot xp is :

Code:
void CPerceptionBot::perceptEntities(void){
PROFILE("CPerceptionBot::perceptEntities");
if(!m_pBot)
return;
if(m_fNextPerceptEntities > g_pGame->getTime() ){
return;
}
m_fNextPerceptEntities = g_pGame->getTime() + .18f;
CEntity Entity = 0;
list<CIEntity*>::iterator iter_entities,
begin_entities = g_pGame->m_LIEntities.begin(),
end_entities = g_pGame->m_LIEntities.end();
CPerceipt *pAllocPerc = /*new CPerceipt*/0; // an instance of a perceipt
Vector VOrigin = m_pBot->getOrigin();
while(Entity = UTIL_FindEntityInSphere(Entity,VOrigin,_ENT_PERC_RADIUS)){ // loop thru entities around here
iter_entities = begin_entities;
while(iter_entities != end_entities){
// check this entity
 
if( (*iter_entities)->compare(Entity) ){
	if(m_pBot->views((*iter_entities)->getOrigin(Entity))){
	 pAllocPerc = new CPerceipt; // create a new perceipt
	 (*iter_entities)->assign(Entity,pAllocPerc);
	 pAllocPerc->m_fDistance = (VOrigin-pAllocPerc->m_VOrigin).length(); // todo : more elegant
	 m_LNewPerceptions.push_back(pAllocPerc);
	 break; // there arent double classname IEntities !? am I right ?
	}
}
iter_entities ++;
}
}
}
€dit: where are all the empty lines gone to ?
Attached Files
File Type: h AStarMachine.h (4.8 KB, 317 views)


  
Reply With Quote
Re: Show off your finest piece of code!
Old
  (#7)
Rifleman
This user broke our rules and has been BANNED
 
Status: Offline
Posts: 128
Join Date: Sep 2004
Location: Mars
Default Re: Show off your finest piece of code! - 30-12-2004

Quote:
Originally Posted by stefanhendriks
as you can see i like it to code like that, aka in the CS2D project (which died horribly) (does anyone wants the source to try it out?)
I would love to
  
Reply With Quote
Re: Show off your finest piece of code!
Old
  (#8)
Rick
Council Member
 
Rick's Avatar
 
Status: Offline
Posts: 690
Join Date: Dec 2003
Location: Holland
Default Re: Show off your finest piece of code! - 30-12-2004

From a c++ book
Code:
   void send(int* to, int* from, int count)
   {
   	 int n = (count+7)/8;
   	 switch(count%8) {
   		   case 0: do {	 *to++ = *from++;
   		   case 7:		  *to++ = *from++;
   		   case 6:		  *to++ = *from++;
   		   case 5:		  *to++ = *from++;
   		   case 4:		  *to++ = *from++;
   		   case 3:		  *to++ = *from++;
   		   case 2:		  *to++ = *from++;
   		   case 1:		  *to++ = *from++;
 					 } while (--n>0);
   	 }
   }
@asp:
Didn't it know it came from you But 'taskmanager'? Its just time sliced
  
Reply With Quote
Re: Show off your finest piece of code!
Old
  (#9)
Cpl. Shrike
ShrikeBot Coder/Moderator
 
Cpl. Shrike's Avatar
 
Status: Offline
Posts: 550
Join Date: Mar 2004
Location: The Netherlands
Default Re: Show off your finest piece of code! - 30-12-2004

Well im proud of this cos i figured it out my self.
Not that it is some kind of rocket science.
But it just works so damn fast that lotsa time i forget i got debug logging on. Winding up enourmous megabitous log files with out lag.

Althoug the Win32 is not yet system logging. (but it is almost as fast as the linux method.)
It just compose the messages like linux sysloging is doing it. And it doesn't open close file after each log action.

Code:
   ///////////////////////////////////////////////////
   //
   //	sb_syslog.cpp
   //
   // linux sysloging and win32 file loggin 
   //
   //
   // TODO make it also win32 eventlog output.
   // 
   ///////////////////////////////////////////////////
   
   #include <extdll.h>
   #include "bot.h"
   #include "sb_syslog.h"
   
   #ifndef __linux__
   
   #include <time.h>
   static FILE *sb_log_file;
   char sb_log_msg[256];
   char * s_severity[] = {
   	"none",	// not used
   	"none",	// not used
   	"none",	// not used
   	"error",	// not used
   	"warn",	// not used
      "notice",
      "info",
      "debug"};
   
   #endif
   
   bool g_LogPrint_enabled = FALSE;
   
   // opens a Linux syslog entry or opens a windows file using date as file name
   void LogOpen()
   {
   	if (g_LogPrint_enabled)
   	{
   #ifndef __linux__
   		char dateStr [9];
   	  _strdate(dateStr);
   		int max = strlen(dateStr);
   		for (int x = 0; x <= max; x++)
   		{
   			if (dateStr[x] == '/')
   				dateStr[x] = '-';
   		}
   		strcpy(sb_log_msg, "log_");
   		strcat(sb_log_msg, dateStr);
   		strcat(sb_log_msg, ".txt");
   		sb_log_file=fopen(sb_log_msg, "a"); 
   #else	
   		openlog("shrikebot", LOG_DEBUG | LOG_INFO | LOG_NOTICE, LOG_USER);
   #endif
   	}
   }
   
   // write the log messages
   void LogPrint(int severity, char *message)
   {
   	if (g_LogPrint_enabled)
   	{
   #ifndef __linux__
   		char timeStr [9];
   		_strtime( timeStr );
   		if (sb_log_file != NULL)
   		{
   			if (severity != LOG_DEBUG)
   			{
   				strcpy(sb_log_msg, timeStr);
   				strcat(sb_log_msg, " - ");
 				strcat(sb_log_msg, s_severity[severity]);
   				strcat(sb_log_msg, ": ");
   				strcat(sb_log_msg, message);
   			}
   			else
   				strcpy(sb_log_msg, message);
   
   			strcat(sb_log_msg, "\n");
   			fprintf(sb_log_file, sb_log_msg);
   		} 
   #else
   		syslog(severity, message);
   #endif	
   	}
   }
   
   // close logging.  although this does not happen when it crashes.
 // but no dataloss because of not closed windows files so far.
   void LogClose()
   {
   	if (g_LogPrint_enabled)
   	{
   #ifndef __linux__
   		fclose(sb_log_file);
   #else
   		closelog();
   #endif
   	}
   }
Form the rest of the code i use LogPrint(LOG_LEVEL, msg);
In stead of the HPB_Bot log routines. Where LOG_LEVEL could be one of the levels defined by Linux syslog.h. But i derived it to sb_syslog.h to make it shorter LogPrint(); fuctions. and to make it work with Win32.

Last edited by Cpl. Shrike; 30-12-2004 at 17:24..
  
Reply With Quote
Re: Show off your finest piece of code!
Old
  (#10)
@$3.1415rin
Council Member, Author of JoeBOT
 
@$3.1415rin's Avatar
 
Status: Offline
Posts: 1,381
Join Date: Nov 2003
Location: Germany
Default Re: Show off your finest piece of code! - 30-12-2004

about the A* Taskmanager ... I extended this idea a bit and made it more comfortable to work with ... here are the definitions : ( the actual code is nothing special, just some assignments and a simple algorithm for managing which task to execute, such stuff can be looked up in every operating system book )

Code:
class AStarBase;
class CBaseBot;
class CBehaviour;
class CCallback_onPathCreation;
// these classes handle astar task, so that you don't have any lags when paths are created. Each process is 
// executed only for some time ( based on the iteration count of A* ) and then next frame calculation is
// continued based on priority and time of last execution
class AStarTask{
	friend class AStarTaskManager;
public:
AStarTask();
AStarTask(AStarBase *p,int iPriority,CBaseBot *pBot,CCallback_onPathCreation *pPC=0,long lTime=0)
:m_pAStar(p),m_iPriority(iPriority),m_pBot(pBot),m_pCB_onPathCreation(pPC),m_lExecution(lTime),m_lExecuted(0),m_lAdded(lTime){}
virtual ~AStarTask();
protected:
AStarBase *m_pAStar;
CCallback_onPathCreation *m_pCB_onPathCreation;
CBaseBot *m_pBot;
int m_iPriority; // priority of task - 0 is lowest, 5 is default
long m_lExecution; // last execution cycle
long m_lAdded;	// when was this task added ?
long m_lExecuted; // how many slices are already executed ?
};
class AStarTaskManager {
public:
AStarTaskManager();
virtual ~AStarTaskManager();
void addTask(AStarBase *,int,CBaseBot *,CCallback_onPathCreation *pPC=0);
void run(void);
int deleteTasksFrom(CCallback_onPathCreation*); // delete tasks with this callback
long getTotalTasks(void){return m_lCTasksTotal;}
unsigned long getCurrentTotalTasks(void){return (unsigned long)m_LTasks.size();}
int getSlicesCPFrame(void){return m_iSlicesNow;}
protected:
int m_iSlicespF;	// Slices per frame
long m_lCounter;	// couting up each iteration
long m_lCTasksTotal; // Total Tasks added since start of manager
int m_iSlicesNow;	// how many slices have been calculated ?
list <AStarTask> m_LTasks; // list of tasks
};



Last edited by @$3.1415rin; 30-12-2004 at 17:46..
  
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump



Powered by vBulletin® Version 3.8.2
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
vBulletin Skin developed by: vBStyles.com