Skip to content

Commit

Permalink
RF: Remove blank import random to avoid accidentally calling it
Browse files Browse the repository at this point in the history
  • Loading branch information
Debilski committed Oct 7, 2024
1 parent c4d2ea3 commit bd349cd
Show file tree
Hide file tree
Showing 18 changed files with 65 additions and 60 deletions.
7 changes: 4 additions & 3 deletions contrib/ci_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@
import itertools
import json
import logging
import random
import sqlite3
import subprocess
import sys
from random import Random

import click
from rich.console import Console
Expand Down Expand Up @@ -184,6 +184,7 @@ def start(self, n):
"""
loop = itertools.repeat(None) if n == 0 else itertools.repeat(None, n)
rng = Random()

for _ in loop:
# choose the player with the least number of played game,
Expand All @@ -193,9 +194,9 @@ def start(self, n):
game_count = [(self.dbwrapper.get_game_count(p['name']), idx) for idx, p in enumerate(self.players)]
players_sorted = [idx for count, idx in sorted(game_count) if not idx in broken_players]
a, rest = players_sorted[0], players_sorted[1:]
b = random.choice(rest)
b = rng.choice(rest)
players = [a, b]
random.shuffle(players)
rng.shuffle(players)

self.run_game(players[0], players[1])
self.pretty_print_results(highlight=[self.players[players[0]]['name'], self.players[players[1]]['name']])
Expand Down
6 changes: 3 additions & 3 deletions pelita/game.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

import logging
import os
import random
import subprocess
import sys
import time
import math
from random import Random
from warnings import warn

from . import layout
Expand Down Expand Up @@ -313,8 +313,8 @@ def setup_game(team_specs, *, layout_dict, max_rounds=300, layout_name="", rng=N

viewer_state = setup_viewers(viewers, options=viewer_options, print_result=print_result)

if not isinstance(rng, random.Random):
rng = random.Random(rng)
if not isinstance(rng, Random):
rng = Random(rng)

# Initialize the game state.

Expand Down
6 changes: 3 additions & 3 deletions pelita/gamestate_filters.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
""" collecting the game state filter functions """
import random
from random import Random


def noiser(walls, shape, bot_position, enemy_positions, noise_radius=5, sight_distance=5, rng=None):
Expand Down Expand Up @@ -48,8 +48,8 @@ def noiser(walls, shape, bot_position, enemy_positions, noise_radius=5, sight_di
"""

# set the random state
if not isinstance(rng, random.Random):
rng = random.Random(rng)
if not isinstance(rng, Random):
rng = Random(rng)

# store the noised positions
noised_positions = [None] * len(enemy_positions)
Expand Down
9 changes: 5 additions & 4 deletions pelita/layout.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import importlib.resources as importlib_resources

import io
import os
import random
import importlib.resources as importlib_resources
from random import Random

# bot to index conversion
BOT_N2I = {'a': 0, 'b': 2, 'x': 1, 'y': 3}
Expand Down Expand Up @@ -34,8 +35,8 @@ def get_random_layout(size='normal', dead_ends=0, rng=None):
"""

# set the random state
if not isinstance(rng, random.Random):
rng = random.Random(rng)
if not isinstance(rng, Random):
rng = Random(rng)

if dead_ends and rng.random() < dead_ends:
layouts_names = get_available_layouts(size=size, dead_ends=True)
Expand Down
18 changes: 9 additions & 9 deletions pelita/maze_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@
Completely rewritten by Pietro Berkes
Rewritten again (but not completely) by Tiziano Zito
"""
import random

import numpy as np
import networkx as nx
from random import Random


north = (0, -1)
Expand Down Expand Up @@ -97,8 +97,8 @@ def create_half_maze(maze, ngaps_center, rng=None):
The second half can be created by mirroring the left part using
the 'complete_maze' function.
"""
if not isinstance(rng, random.Random):
rng = random.Random(rng)
if not isinstance(rng, Random):
rng = Random(rng)

# first, we need a wall in the middle

Expand Down Expand Up @@ -321,8 +321,8 @@ def get_neighboring_walls(maze, locs):
return walls

def remove_all_chambers(maze, rng=None):
if not isinstance(rng, random.Random):
rng = random.Random(rng)
if not isinstance(rng, Random):
rng = Random(rng)

maze_graph = walls_to_graph(maze)
# this will find one of the chambers, if there is any
Expand All @@ -349,8 +349,8 @@ def add_food(maze, max_food, rng=None):
We exclude the pacmen's starting positions and the central dividing border
"""
if not isinstance(rng, random.Random):
rng = random.Random(rng)
if not isinstance(rng, Random):
rng = Random(rng)

if max_food == 0:
# no food needs to be added, return here
Expand Down Expand Up @@ -409,8 +409,8 @@ def get_new_maze(height, width, nfood, dead_ends=False, rng=None):
if width%2 != 0:
raise ValueError(f'Width must be even ({width} given)')

if not isinstance(rng, random.Random):
rng = random.Random(rng)
if not isinstance(rng, Random):
rng = Random(rng)

maze = empty_maze(height, width)
create_half_maze(maze, height // 2, rng=rng)
Expand Down
2 changes: 1 addition & 1 deletion pelita/scripts/pelita_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import argparse
import json
import logging
from pathlib import Path
import random
import sys
from pathlib import Path
from urllib.parse import urlparse

from rich.console import Console
Expand Down
11 changes: 7 additions & 4 deletions pelita/scripts/pelita_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,18 @@
from dataclasses import dataclass
import json
import logging
import random

import queue
import shlex
import signal
import subprocess
import sys
import time
from typing import Optional, Dict, List
import urllib
from urllib.parse import urlparse
import urllib.parse
from typing import Optional, Dict, List
from urllib.parse import urlparse
from random import Random
from weakref import WeakValueDictionary

import click
Expand Down Expand Up @@ -560,7 +561,9 @@ def remote_server(address, port, teams, advertise, max_connections):
# - name: def
# spec: path/to/module

session_key = "".join(str(random.randint(0, 9)) for _ in range(12))
rng = Random()

session_key = "".join(str(rng.randint(0, 9)) for _ in range(12))
pprint(f"Use --session-key {session_key} to for the admin API.")

team_infos = []
Expand Down
6 changes: 3 additions & 3 deletions pelita/scripts/pelita_tournament.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
import argparse
import datetime
import itertools
from pathlib import Path
import random
import re
import shlex
import sys
from pathlib import Path
from random import Random

import shutil
import yaml
Expand Down Expand Up @@ -266,7 +266,7 @@ def escape(s):
if args.rounds:
config.rounds = args.rounds

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

if Path(args.state).is_file():
if not args.load_state:
Expand Down
4 changes: 2 additions & 2 deletions pelita/team.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@

import logging
import os
import random
import subprocess
import sys
import traceback
from io import StringIO
from pathlib import Path
from random import Random
from urllib.parse import urlparse

import zmq
Expand Down Expand Up @@ -138,7 +138,7 @@ def set_initial(self, team_id, game_state):

# Initialize the random number generator
# with the seed that we received from game
self._rng = random.Random(game_state['seed'])
self._rng = Random(game_state['seed'])

# Reset the bot tracks
self._bot_track = [[], []]
Expand Down
8 changes: 4 additions & 4 deletions pelita/utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import random
from random import Random

import networkx as nx

Expand Down Expand Up @@ -116,10 +116,10 @@ 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:
rng = random.Random()
rng = Random()
seed = rng.randint(1, 2**31)
else:
rng = random.Random(seed)
rng = Random(seed)

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

Expand Down Expand Up @@ -237,7 +237,7 @@ def setup_test_game(*, layout, is_blue=True, round=None, score=None, seed=None,
enemy_positions = [layout['bots'][0], layout['bots'][2]]
is_noisy_enemy = [is_noisy["a"], is_noisy["b"]]

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

team = {
'bot_positions': bot_positions,
Expand Down
10 changes: 6 additions & 4 deletions test/test_filter_gamestates.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import pytest

import collections
import random
from random import Random

from pelita import gamestate_filters as gf
from pelita.game import setup_game, play_turn, prepare_bot_state, split_food
Expand All @@ -11,6 +11,8 @@
import pelita.utils
import pelita.game

RNG = Random()

def make_gamestate():
def dummy_team(bot, state):
return bot.position, state
Expand Down Expand Up @@ -287,7 +289,7 @@ def test_noiser_noising_at_noise_radius_extreme(ii):
still noise within confines of maze, despite extreme radius """

gamestate = make_gamestate()
gamestate["turn"] = random.randint(0, 3)
gamestate["turn"] = RNG.randint(0, 3)
team_id = gamestate["turn"] % 2
old_bots = gamestate["bots"]
team_bots = old_bots[team_id::2]
Expand Down Expand Up @@ -694,7 +696,7 @@ def test_relocate_expired_food(dummy):
parsed.update({
"food": food,
"food_age": food_age,
"rng" : random.Random(),
"rng" : Random(),
})

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

radius = 2
Expand Down
10 changes: 5 additions & 5 deletions test/test_game.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
"""Tests for Pelita game module"""
import pytest

from contextlib import contextmanager

import inspect
import itertools
import os
from pathlib import Path
import random
from textwrap import dedent
import sys
from contextlib import contextmanager
from pathlib import Path
from random import Random

from pelita import game, layout
from pelita.exceptions import NoFoodWarning
Expand Down Expand Up @@ -803,7 +803,7 @@ def test_play_turn_move():
"bot_was_killed": [False]*4,
"errors": [[], []],
"fatal_errors": [{}, {}],
"rng": random.Random()
"rng": 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
7 changes: 3 additions & 4 deletions test/test_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@

import itertools
import math
import random
from pathlib import Path
from random import Random
from textwrap import dedent

from pelita.layout import *
Expand Down Expand Up @@ -68,7 +67,7 @@ def test_get_random_layout_returns_correct_layout():
assert layout == layout2

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

Expand All @@ -77,7 +76,7 @@ def test_get_random_layout_proportion_dead_ends():
prop = 0.25
expected = int(prop*N)
# get a fixed rng, so that the test is reproducible
rng = random.Random(176399)
rng = 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(rng=rng)[0] for _ in range(N))
# check that we get more or less the right proportion of layouts with dead ends
Expand Down
2 changes: 1 addition & 1 deletion test/test_maze_generation.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import random
import textwrap
from random import Random

import networkx as nx
import numpy as np
Expand Down
5 changes: 1 addition & 4 deletions test/test_player_base.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import pytest
import unittest

import random
import time
from random import Random

from pelita.game import setup_game, run_game, play_turn
from pelita.layout import parse_layout
Expand Down
3 changes: 2 additions & 1 deletion test/test_players.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from random import random
from random import Random

import pytest

from pelita.game import run_game
Expand Down
Loading

0 comments on commit bd349cd

Please sign in to comment.