Skip to content

Commit

Permalink
RF: Rename rnd to rng and use instead of seed if applicable.
Browse files Browse the repository at this point in the history
  • Loading branch information
Debilski committed Oct 4, 2024
1 parent 7aa1985 commit b261dbe
Show file tree
Hide file tree
Showing 8 changed files with 43 additions and 43 deletions.
10 changes: 5 additions & 5 deletions pelita/game.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ def setup_game(team_specs, *, layout_dict, max_rounds=300, layout_name="", seed=
teams=[None] * 2,

#: Random number generator
rnd=Random(seed),
rng=Random(seed),

#: Timeout length, int, None
timeout_length=timeout_length,
Expand Down Expand Up @@ -534,7 +534,7 @@ def prepare_bot_state(game_state, idx=None):
# We assume that we are in get_initial phase
turn = idx
bot_turn = None
seed = game_state['rnd'].randint(0, sys.maxsize)
seed = game_state['rng'].randint(0, sys.maxsize)
elif bot_finalization:
# Called for remote players in _exit
turn = idx
Expand All @@ -555,7 +555,7 @@ def prepare_bot_state(game_state, idx=None):
enemy_positions=enemy_positions,
noise_radius=game_state['noise_radius'],
sight_distance=game_state['sight_distance'],
rnd=game_state['rnd'])
rng=game_state['rng'])


# Update noisy_positions in the game_state
Expand Down Expand Up @@ -669,7 +669,7 @@ def prepare_viewer_state(game_state):

# remove unserializable values
del viewer_state['teams']
del viewer_state['rnd']
del viewer_state['rng']
del viewer_state['viewers']
del viewer_state['controller']

Expand Down Expand Up @@ -855,7 +855,7 @@ def apply_move(gamestate, bot_position):
# There was an error for this round and turn
# but the game is not over.
# We execute a random move
bot_position = gamestate['rnd'].choice(legal_positions)
bot_position = gamestate['rng'].choice(legal_positions)
game_print(turn, f"Setting a legal position at random: {bot_position}")

# take step
Expand Down
18 changes: 9 additions & 9 deletions pelita/gamestate_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import random


def noiser(walls, shape, bot_position, enemy_positions, noise_radius=5, sight_distance=5, rnd=None):
def noiser(walls, shape, bot_position, enemy_positions, noise_radius=5, sight_distance=5, rng=None):
"""Function to make bot positions noisy in a game state.
Applies uniform noise in maze space. Noise will only be applied if the
Expand Down Expand Up @@ -38,7 +38,7 @@ def noiser(walls, shape, bot_position, enemy_positions, noise_radius=5, sight_di
the radius for the uniform noise
sight_distance : int, optional, default: 5
the distance at which noise is no longer applied.
rnd : Random, optional
rng : Random, optional
the game’s random number generator (or None for an independent one)
Returns
Expand All @@ -48,8 +48,8 @@ def noiser(walls, shape, bot_position, enemy_positions, noise_radius=5, sight_di
"""

# set the random state
if rnd is None:
rnd = random.Random()
if rng is None:
rng = random.Random()

# store the noised positions
noised_positions = [None] * len(enemy_positions)
Expand All @@ -64,7 +64,7 @@ def noiser(walls, shape, bot_position, enemy_positions, noise_radius=5, sight_di

if cur_distance is None or cur_distance > sight_distance:
# If so then alter the position of the enemy
new_pos, noisy_flag = alter_pos(b, noise_radius, rnd, walls, shape)
new_pos, noisy_flag = alter_pos(b, noise_radius, rng, walls, shape)
noised_positions[count] = new_pos
is_noisy[count] = noisy_flag
else:
Expand All @@ -74,7 +74,7 @@ def noiser(walls, shape, bot_position, enemy_positions, noise_radius=5, sight_di
return { "enemy_positions": noised_positions, "is_noisy": is_noisy }


def alter_pos(bot_pos, noise_radius, rnd, walls, shape):
def alter_pos(bot_pos, noise_radius, rng, walls, shape):
""" alter the position """

# get a list of possible positions
Expand Down Expand Up @@ -110,7 +110,7 @@ def alter_pos(bot_pos, noise_radius, rnd, walls, shape):
noisy = False
else:
# select a random position
final_pos = rnd.choice(possible_positions)
final_pos = rng.choice(possible_positions)
noisy = True

# return the final_pos and a flag if it is noisy or not
Expand Down Expand Up @@ -153,7 +153,7 @@ def relocate_expired_food(game_state, team, radius, max_food_age=None):
food_age = [dict(team_food_age) for team_food_age in game_state['food_age']]
width, height = game_state['shape']
walls = game_state['walls']
rnd = game_state['rnd']
rng = game_state['rng']
if max_food_age is None:
max_food_age = game_state['max_food_age']

Expand Down Expand Up @@ -186,7 +186,7 @@ def relocate_expired_food(game_state, team, radius, max_food_age=None):
# relocated at the next round
continue
# choose a new position at random
new_pos = rnd.choice(targets)
new_pos = rng.choice(targets)

# remove the new pellet position from the list of possible targets for new pellets
targets.remove(new_pos)
Expand Down
15 changes: 8 additions & 7 deletions pelita/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@
BOT_I2N = {0: 'a', 2: 'b', 1: 'x', 3: 'y'}


RNG = random.Random()

def get_random_layout(size='normal', seed=None, dead_ends=0):
def get_random_layout(size='normal', rng=None, dead_ends=0):
""" Return a random layout string from the available ones.
Parameters
Expand All @@ -34,13 +32,16 @@ def get_random_layout(size='normal', seed=None, dead_ends=0):
the name of the layout, a random layout string
"""
if seed is not None:
RNG.seed(seed)
if dead_ends and RNG.random() < dead_ends:

# set the random state
if rng is None:
rng = random.Random()

if dead_ends and rng.random() < dead_ends:
layouts_names = get_available_layouts(size=size, dead_ends=True)
else:
layouts_names = get_available_layouts(size=size, dead_ends=False)
layout_choice = RNG.choice(layouts_names)
layout_choice = rng.choice(layouts_names)
return layout_choice, get_layout_by_name(layout_choice)

def get_available_layouts(size='normal', dead_ends=False):
Expand Down
4 changes: 2 additions & 2 deletions pelita/scripts/pelita_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,7 @@ def main():
else:
seed = args.seed

random.seed(seed)
rng = random.Random(seed)

if args.layout:
# first check if the given layout is a file
Expand All @@ -449,7 +449,7 @@ def main():
layout_name = args.layout
layout_string = pelita.layout.get_layout_by_name(args.layout)
else:
layout_name, layout_string = pelita.layout.get_random_layout(args.size, seed=seed, dead_ends=DEAD_ENDS)
layout_name, layout_string = pelita.layout.get_random_layout(args.size, rng=rng, dead_ends=DEAD_ENDS)

print("Using layout '%s'" % layout_name)

Expand Down
14 changes: 7 additions & 7 deletions pelita/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,12 @@
# older clients!
from .team import walls_to_graph

RNG = random.Random()


def _parse_layout_arg(*, layout=None, food=None, bots=None, seed=None):
def _parse_layout_arg(*, layout=None, food=None, bots=None, rng=None):

# prepare layout argument to be passed to pelita.game.run_game
if layout is None:
layout_name, layout_str = get_random_layout(size='normal', seed=seed, dead_ends=DEAD_ENDS)
layout_name, layout_str = get_random_layout(size='normal', rng=rng, dead_ends=DEAD_ENDS)
layout_dict = parse_layout(layout_str)
elif layout in get_available_layouts(size='all'):
# check if this is a built-in layout
Expand Down Expand Up @@ -118,10 +116,12 @@ def run_background_game(*, blue_move, red_move, layout=None, max_rounds=300, see

# if the seed is not set explicitly, set it here
if seed is None:
seed = RNG.randint(1, 2**31)
RNG.seed(seed)
rng = random.Random()
seed = rng.randint(1, 2**31)
else:
rng = random.Random(seed)

layout_dict, layout_name = _parse_layout_arg(layout=layout, seed=seed)
layout_dict, layout_name = _parse_layout_arg(layout=layout, rng=rng)

game_state = run_game((blue_move, red_move), layout_dict=layout_dict,
layout_name=layout_name, max_rounds=max_rounds, seed=seed,
Expand Down
8 changes: 4 additions & 4 deletions test/test_filter_gamestates.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def test_noiser_no_negative_coordinates(bot_id):
enemy_group = 1 - (bot_id // 2)
enemy_positions = gamestate['bots'][enemy_group::2]
noised = gf.noiser(walls, shape=shape, bot_position=bot_position, enemy_positions=enemy_positions,
noise_radius=5, sight_distance=5, rnd=None)
noise_radius=5, sight_distance=5, rng=None)
new_bots = noised["enemy_positions"]
test_1 = all(item[0] > 0 for item in new_bots)
test_2 = all(item[1] > 0 for item in new_bots)
Expand Down Expand Up @@ -296,7 +296,7 @@ def test_noiser_noising_at_noise_radius_extreme(ii):
shape=gamestate["shape"],
bot_position=gamestate["bots"][gamestate["turn"]],
enemy_positions=enemy_bots,
noise_radius=50, sight_distance=5, rnd=None)
noise_radius=50, sight_distance=5, rng=None)

assert all(noised["is_noisy"])

Expand Down Expand Up @@ -694,7 +694,7 @@ def test_relocate_expired_food(dummy):
parsed.update({
"food": food,
"food_age": food_age,
"rnd" : random.Random(),
"rng" : random.Random(),
})

radius = 2
Expand Down Expand Up @@ -747,7 +747,7 @@ def test_relocate_expired_food_nospaceleft():
parsed.update({
"food": food,
"food_age": food_age,
"rnd" : random.Random(),
"rng" : random.Random(),
})

radius = 2
Expand Down
2 changes: 1 addition & 1 deletion test/test_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -803,7 +803,7 @@ def test_play_turn_move():
"bot_was_killed": [False]*4,
"errors": [[], []],
"fatal_errors": [{}, {}],
"rnd": random.Random()
"rng": random.Random()
}
legal_positions = get_legal_positions(game_state["walls"], game_state["shape"], game_state["bots"][turn])
game_state_new = apply_move(game_state, legal_positions[0])
Expand Down
15 changes: 7 additions & 8 deletions test/test_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,22 +67,21 @@ def test_get_random_layout_returns_correct_layout():
layout2 = get_layout_by_name(name)
assert layout == layout2

def test_get_random_layout_random_seed():
name, layout = get_random_layout(size='small', seed=1)
def test_get_random_layout_random_rng():
rng = random.Random(1)
name, layout = get_random_layout(size='small', rng=rng)
assert name == 'small_017'

def test_get_random_layout_proportion_dead_ends():
N = 1000
prop = 0.25
expected = int(prop*N)
# get a fix sequence of seeds, so that the test is reproducible
RNG = random.Random()
RNG.seed(176399)
seeds = [RNG.random() for i in range(N)]
# get a fixed rng, so that the test is reproducible
rng = random.Random(176399)
# check that we don't get any layout with dead ends if we don't ask for it
assert not any('dead_ends' in get_random_layout(seed=s)[0] for s in seeds)
assert not any('dead_ends' in get_random_layout(rng=rng)[0] for _ in range(N))
# check that we get more or less the right proportion of layouts with dead ends
dead_ends = sum('dead_ends' in get_random_layout(seed=s, dead_ends=prop)[0] for s in seeds)
dead_ends = sum('dead_ends' in get_random_layout(rng=rng, dead_ends=prop)[0] for _ in range(N))
assert math.isclose(dead_ends, expected, rel_tol=0.1)


Expand Down

0 comments on commit b261dbe

Please sign in to comment.