00001 /****************************************************************************** 00002 * Wormux is a convivial mass murder game. 00003 * Copyright (C) 2001-2004 Lawrence Azzoug. 00004 * 00005 * This program is free software; you can redistribute it and/or modify 00006 * it under the terms of the GNU General Public License as published by 00007 * the Free Software Foundation; either version 2 of the License, or 00008 * (at your option) any later version. 00009 * 00010 * This program is distributed in the hope that it will be useful, 00011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 00012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00013 * GNU General Public License for more details. 00014 * 00015 * You should have received a copy of the GNU General Public License 00016 * along with this program; if not, write to the Free Software 00017 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA 00018 ****************************************************************************** 00019 * Functions to generate random datas (number, boolean, etc.). 00020 *****************************************************************************/ 00021 00022 #include <time.h> 00023 #include <math.h> 00024 #include <stdlib.h> 00025 #include <assert.h> 00026 #include "random.h" 00027 00028 Random randomObj; 00029 00030 Random::Random(){ 00031 srand( time(NULL) ); 00032 } 00033 00034 bool Random::GetBool(){ 00035 int moitie = RAND_MAX/2; 00036 return (rand() <= moitie); 00037 } 00038 00042 long Random::GetLong(long min, long max){ 00043 return min + (long)GetDouble(max - min + 1); 00044 /* double r = rand(); 00045 00046 r *= (max - min); 00047 r /= RAND_MAX; 00048 if( r >= 0 ) 00049 r = floor(r + 0.5); 00050 else 00051 r = ceil(r - 0.5); 00052 00053 return min + (long)r; */ 00054 } 00055 00056 double Random::GetDouble(double min, double max){ 00057 return min + GetDouble(max - min); 00058 } 00059 00060 double Random::GetDouble(double max){ 00061 return max * GetDouble(); 00062 } 00063 00069 double Random::GetDouble(){ 00070 return 1.0*rand()/(RAND_MAX + 1.0); 00071 } 00072 00079 Point2i Random::GetPoint(const Rectanglei &rect){ 00080 Point2i topPoint = rect.GetPosition(); 00081 Point2i bottomPoint = rect.GetBottomRightPoint(); 00082 00083 return Point2i( GetLong(topPoint.x, bottomPoint.x), 00084 GetLong(topPoint.y, bottomPoint.y) ); 00085 } 00086 00087 Point2i Random::GetPoint(const Point2i &pt){ 00088 return Point2i( GetLong(0, pt.x - 1), GetLong(0, pt.y - 1) ); 00089 }