changeset 5299:db18dfecfb7c draft

(svn r7452) -Fix: GetRandom(Industry|Town) must return a valid industry/town and should not need to loop over the pool for a second time.
author rubidium <rubidium@openttd.org>
date Sat, 09 Dec 2006 14:18:08 +0000
parents f032b319aa52
children 4ef0b8358d6e
files industry.h town.h
diffstat 2 files changed, 26 insertions(+), 17 deletions(-) [+]
line wrap: on
line diff
--- a/industry.h
+++ b/industry.h
@@ -90,6 +90,11 @@
 	return industry->xy != 0;
 }
 
+static inline bool IsValidIndustryID(IndustryID index)
+{
+	return index < GetIndustryPoolSize() && IsValidIndustry(GetIndustry(index));
+}
+
 VARDEF int _total_industries;
 
 static inline IndustryID GetMaxIndustryIndex(void)
@@ -108,23 +113,23 @@
 }
 
 /**
- * Return a random valid town.
+ * Return a random valid industry.
  */
 static inline Industry *GetRandomIndustry(void)
 {
-	uint num = RandomRange(GetNumIndustries());
-	uint index = 0;
+	int num = RandomRange(GetNumIndustries());
+	IndustryID index = INVALID_INDUSTRY;
 
 	if (GetNumIndustries() == 0) return NULL;
 
-	while (num > 0) {
+	while (num >= 0) {
 		num--;
-
 		index++;
+
 		/* Make sure we have a valid industry */
-		while (GetIndustry(index) == NULL) {
+		while (!IsValidIndustryID(index)) {
 			index++;
-			if (index > GetMaxIndustryIndex()) index = 0;
+			assert(index <= GetMaxIndustryIndex());
 		}
 	}
 
--- a/town.h
+++ b/town.h
@@ -6,6 +6,10 @@
 #include "oldpool.h"
 #include "player.h"
 
+enum {
+	INVALID_TOWN = 0xFFFF,
+};
+
 struct Town {
 	TileIndex xy;
 
@@ -162,6 +166,11 @@
 	return town->xy != 0;
 }
 
+static inline bool IsValidTownID(TownID index)
+{
+	return index < GetTownPoolSize() && IsValidTown(GetTown(index));
+}
+
 VARDEF uint _total_towns;
 
 static inline TownID GetMaxTownIndex(void)
@@ -184,28 +193,23 @@
  */
 static inline Town *GetRandomTown(void)
 {
-	uint num = RandomRange(GetNumTowns());
-	uint index = 0;
+	int num = RandomRange(GetNumTowns());
+	TownID index = INVALID_TOWN;
 
-	while (num > 0) {
+	while (num >= 0) {
 		num--;
 
 		index++;
 		/* Make sure we have a valid industry */
-		while (GetTown(index) == NULL) {
+		while (!IsValidTownID(index)) {
 			index++;
-			if (index > GetMaxTownIndex()) index = 0;
+			assert(index <= GetMaxTownIndex());
 		}
 	}
 
 	return GetTown(index);
 }
 
-static inline bool IsValidTownID(uint index)
-{
-	return index < GetTownPoolSize() && IsValidTown(GetTown(index));
-}
-
 void DestroyTown(Town *t);
 
 static inline void DeleteTown(Town *t)