def __init__(self, screen, settings, id, turn=False): # Initiate score to 0 self.score = Score(screen, settings, id + 1) self.settings = settings self.id = id # Used for scoring self.static_list = [[215, 0], [385, 0], [565, 0], [740, 0]] self.moving_list = [[125, 0], [300, 0], [475, 0], [650, 0], [830, 0]] # Convert to negative so as to make checking easy for player 2 if id == 1: self.static_list = list(map(lambda x: [-x[0], 0], self.static_list)) self.moving_list = list(map(lambda x: [-x[0], 0], self.moving_list)) # Make a sheep object self.sheep = Sheep(screen, settings, id + 1) # Set if turn is true or false self.turn = turn self.alive = True # True if player has currently completed the level self.level_complete = False self.consider_time = True
def init_levels(self): level1 = Level() self.generate_ground(level1) for i in range(2, 8): level1.blocks.add( Crate((1200, self.window_height - 102 * i), (0, 0), 100, 100, "crate")) level1.blocks.add( Stone((1500, self.window_height - 310), (0, 0), 200, 200, "stone")) level1.enemies.add( Sheep((1500, self.window_height - 400), (0, 0), 100, 100, "sheep")) level2 = Level() self.generate_ground(level2) level2.blocks.add( Crate((1200, self.window_height - 200), (0, 0), 100, 100, "crate")) level2.blocks.add( Stone((1300, self.window_height - 200), (0, 0), 100, 100, "stone")) level2.blocks.add( Ice((1400, self.window_height - 200), (0, 0), 100, 100, "Ice")) level2.enemies.add( Sheep((1500, self.window_height - 200), (0, 0), 100, 100, "sheep")) level2.enemies.add( Sheep((1000, self.window_height - 200), (0, 0), 100, 100, "sheep")) level3 = Level() self.generate_ground(level3) level3.enemies.add(Ice((400, 900), (0, 0), 100, 100, "Ice")) level3.enemies.add(Sheep((300, 900), (0, 0), 100, 100, "sheep")) self.levels = [level1, level2, level3]
class TestSheep(unittest.TestCase): def setUp(self): self._sheep = Sheep('Dolly', 'Finn Dorset') def test_name_should_be_equal(self): cloned_sheep = self._sheep.clone() self.assertEqual(cloned_sheep.name, 'Dolly') def test_breed_should_be_equal(self): cloned_sheep = self._sheep.clone() self.assertEqual(cloned_sheep.breed, 'Finn Dorset')
def sheep_holder(self): score = self.start_score / 10000000000 if self.number_of_sheeps < 3: if round(score) > (100*self.number_of_sheeps) and round(score) <= 750 or \ len(self.sheeps) == 0 or round(score) > (100*self.number_of_sheeps) + 750: self.number_of_sheeps = self.number_of_sheeps + 1 if round(score) > 750: self.sheeps.append(["sheep_%d" % (self.number_of_sheeps)]) self.sheeps[self.number_of_sheeps - 1] = Sheep( self.screen, 1300) self.sound_effect_sheep.play() else: self.sheeps.append(["sheep_%d" % (self.number_of_sheeps)]) self.sheeps[self.number_of_sheeps - 1] = Sheep( self.screen, 900) self.sound_effect_sheep.play() return self.sheeps
def import_from_json(f, meadow, scale, sheep_list_sheeps, points_list): meadow.delete("all") sheep_list_sheeps.clear() points_list.clear() scale.set(0) # zapis danych z pliku do zmiennej with open(f) as json_file: data = json.load(json_file) # zapis poszczegolnych fragmentow do zmiennych bg_color = data['bg_color'] wolf_color = data['wolf_color'] wolf_pos = data['wolf_pos'] sheep_color = data['sheep_color'] sheep_pos = data['sheep_pos'] # podzial zmiennej wolf_pos na liste z wspolrzednymi wilka wolf_after = wolf_pos.split(',') wolf_x = wolf_after[0] wolf_y = wolf_after[1] # przypisanie wszystkich atrybutow do wilka wolf = Wolf() wolf.x = float(wolf_x) wolf.y = float(wolf_y) wolf.wolf_color = wolf_color drawn_wolf = draw_wolf(meadow, wolf.x, wolf.y, wolf.wolf_color, scale) # ilosc owiec zapisanych w pliku length = len(sheep_pos) # stworzenie listy owiec, do ktorej zapisze sie dane z pliku sheep_list_sheeps = SheepList() for i in range(0, length): # dzielimy kazdy element listy na mniejsza tablice, ktorej pierwszy element to x, a drugi to y pom = sheep_pos[i].split(',') # konwertujemy elementy tablicy na float x = float(pom[0]) y = float(pom[1]) # dodajemy owce o wspolrzednych z pliku do stworzonej listy sheep_list_sheeps.sheep_add(Sheep(i, x, y)) # rysujemy te owce na lace point = draw_sheep(meadow, x, y, sheep_color, scale) # dodajemy narysowane punkty do listy sheep_list_sheeps.point_add(point) # każdej owcy z listy ustawiamy kolor wczytany z pliku for sheep in sheep_list_sheeps.sheep_list: sheep.sheep_color = sheep_color # zwracamy te elementy, ktore sa istotne przy kolejnych krokach symulacji return sheep_color, wolf, drawn_wolf, bg_color
def __init__(self, init_pos_limit, sheep_move_dist, wolf_move_dist, sheep_number, turns_number, wait): log = "Info level: Setting simulation details " + str(init_pos_limit) + " " + str(sheep_move_dist) + " " + \ str(wolf_move_dist) + " " + str(sheep_move_dist) + " " + str(sheep_number) + " " + str(turns_number) + " " logging.info(log) self.turns_number = turns_number self.wolf = Wolf(wolf_move_dist) self.wait_character = wait self.sheep_number = sheep_number self.alive_sheep_number = sheep_number for _ in range(sheep_number): self.sheep_list.append(Sheep(init_pos_limit, sheep_move_dist))
def paint_sheep(self, event): x1, y1 = event.x, event.y point = draw_sheep(self.meadow, x1, y1, self.sheep_color, self.scale_variable) # zmienna do numerowania owiec number = self.sheep_list_object.count() # dodanie owcy do listy owiec self.sheep_list_object.sheep_add(Sheep(number, x1, y1)) self.sheep_list_gui[-1].sheep_color = self.sheep_color # dodanie narysowanego punktu oznaczajacego owce do listy narysowanych punktow w obiekcie klasy SheepsList self.sheep_list_object.point_add(point) # aktualizacja etykiety z lista zywych owiec na podstawie liczby elementow listy owiec self.variable_sheep_number.set( str(self.sheep_list_object.count_alive_sheeps()))
def create_world(): global player, tile, background, sheeps, bullets, portal, bgm_sound, restart restart = Restart() portal = Portal() player = Player() tile = Tile() background = Background() sheeps = [Sheep() for i in range(5)] bullets = list() if bgm_sound == None: bgm_sound = load_music("Sound/stage_1.mp3") bgm_sound.set_volume(64) bgm_sound.repeat_play()
def __init__(self, width=800, height=600, food_size=5, n_agents=1, caption='Mundo das ovelhas', food_energy=10, time_to_growth=400, flat=False, mutation=1, speed=4, energy=20, reproduction_energy=40): self.width = width self.height = height self.food_size = food_size self.n_agents = n_agents self.sheeps = list() self.foods = list() self.world = World(width, height, caption, flat) self.mutation = mutation # Instancia os recursos for x in range(0, self.world.width, food_size): for y in range(0, self.world.height, food_size): self.foods.append( Grass(x, y, food_size, food_energy, time_to_growth)) # Instancia os agentes for i in range(N_AGENTS): self.sheeps.append( Sheep( randint(0, self.world.width), randint(0, self.world.height), #random(width), #random(height), choice(SHEEP_COLORS), speed, energy, reproduction_energy))
from sheep import Sheep from shepherd import Shepherd import numpy as np import time sheep = Sheep(pos=np.array([1, 1])) shepherd = Shepherd(pos=np.array([0, 0])) shepherd_2 = Shepherd(pos=np.array([0, 0])) l = [shepherd_2, shepherd] l.remove(shepherd_2) print(shepherd_2 == shepherd) print(shepherd_2 == shepherd_2) print(l) print('test', shepherd.get_control([sheep], [shepherd])) print(sheep.get_distance(shepherd))
def add_sheep(self, x, y): sheep = Sheep(self.init_pos_limit, self.sheep_move_dist, x, y) self.sheep_arr.append(sheep) self.alive_sheep += 1
def setUp(self): self._sheep = Sheep('Dolly', 'Finn Dorset')
class Player(): """A class which handles all the information about the player""" def __init__(self, screen, settings, id, turn=False): # Initiate score to 0 self.score = Score(screen, settings, id + 1) self.settings = settings self.id = id # Used for scoring self.static_list = [[215, 0], [385, 0], [565, 0], [740, 0]] self.moving_list = [[125, 0], [300, 0], [475, 0], [650, 0], [830, 0]] # Convert to negative so as to make checking easy for player 2 if id == 1: self.static_list = list(map(lambda x: [-x[0], 0], self.static_list)) self.moving_list = list(map(lambda x: [-x[0], 0], self.moving_list)) # Make a sheep object self.sheep = Sheep(screen, settings, id + 1) # Set if turn is true or false self.turn = turn self.alive = True # True if player has currently completed the level self.level_complete = False self.consider_time = True def update(self): """Update player score and position""" pos_y = self.sheep.centery if self.id == 0 and pos_y < 30: self.level_complete = True if self.id == 1 and pos_y > self.settings.screen_height - 30: self.level_complete = True if self.id == 1: pos_y = -pos_y for i in enumerate(self.static_list): if (self.static_list[i[0]][1] == 0 and pos_y < self.static_list[i[0]][0]): self.static_list[i[0]][1] = 1 for i in enumerate(self.static_list): if self.static_list[i[0]][1] == 1: self.score.update_score(5) self.static_list[i[0]][1] = 2 for i in enumerate(self.moving_list): if (self.moving_list[i[0]][1] == 0 and pos_y < self.moving_list[i[0]][0]): self.moving_list[i[0]][1] = 1 for i in enumerate(self.moving_list): if self.moving_list[i[0]][1] == 1: self.score.update_score(10) self.moving_list[i[0]][1] = 2 self.sheep.blitme() self.score.blitme() def kill(self): """Kill the player and remove it from the screen""" self.alive = False self.sheep.reset() def reset(self): """Reset player after each round if not dead""" if self.alive: self.sheep.reset() # Used for scoring self.static_list = [[215, 0], [385, 0], [565, 0], [740, 0]] self.moving_list = [[125, 0], [300, 0], [475, 0], [650, 0], [830, 0]] # Convert to negative so as to make checking easy for player 2 if self.id == 1: self.static_list = list( map(lambda x: [-x[0], 0], self.static_list)) self.moving_list = list( map(lambda x: [-x[0], 0], self.moving_list)) self.level_complete = False
def init(cont): sheep = Sheep(cont.owner) cont.owner.controller = cont sheep.setState(FlockState(sheep)) cont.owner['initialized'] = True
def __init__(self): # tworzenie okna: self.window = Tk() self.window.title("Python 3 Simulation") self.window.geometry('500x420') self.window.resizable(False, False) self.window.configure(background="grey") # atrybuty instancyjne: # zmienna z kolorem tła: self.bg_color = "chartreuse2" self.init_pos_limit = 200.0 # tworzymy obszar, ktory bedzie łaką (meadow) self.meadow = Canvas(self.window, bg=self.bg_color, height=1.5 * self.init_pos_limit, width=1.5 * self.init_pos_limit) # suwak do przyblizania / oddalania self.scale_variable = DoubleVar() self.scale = Scale(self.window, variable=self.scale_variable, command=self.zooming, activebackground="green", bg="white", from_=0, to=5, label="ZOOM") # wartosc domyslna dla suwaka self.default_value = 0 # ustawiamy na początku na 0 self.scale.set(self.default_value) # tworzymy wilka na start na srodku laki self.wolf = Wolf() self.drawn_wolf = draw_wolf(self.meadow, 145, 145, self.wolf.wolf_color, self.scale_variable) # owca, ktora nie jest pokazywana na lace self.sheep = Sheep(0, 100, 100) self.sheep_color = "light blue" # utworzenie obiektu lista owiec self.sheep_list_object = sheepsList.SheepList() self.sheep_list_gui = self.sheep_list_object.sheep_list self.points_list_gui = self.sheep_list_object.points_list # etykieta z liczba zywych owiec i zmienna do zmiany wartosci self.variable_sheep_number = StringVar() self.variable_sheep_number.set("0") self.label_how_many_sheep = Label( self.window, textvariable=self.variable_sheep_number, bg="grey", font="calibri 20 bold") # menu self.menu_bar = Menu(self.window) # przycisk step self.step = Button(self.window, text="STEP", height=2, width=15, justify=CENTER, bg="white", font="calibri 10 bold", command=self.step) # przycisk Reset self.reset = Button(self.window, text="RESET", height=2, width=15, justify=CENTER, bg="white", font="calibri 10 bold", command=self.reset) # przycisk start/stop self.var = StringVar() self.var.set("START") self.start_stop = Button(self.window, textvariable=self.var, height=2, width=15, justify=CENTER, bg="white", font="calibri 10 bold", command=self.start_stop_click) # zmienna dla czasu pojedynczego ruchu self.interval = 1.0 # flaga do tego czy ruch ma trwać self.perform_flag = False
#oil level instructions import pygame from sheep import Sheep from oilCharacters import * import oilPlay sheep = Sheep() oilScrapie = oilScrapie() fire = firePic() evilFace = evil() rock = rock1() class oilPlayExplanation(object): def __init__(self, width=800, height=600, fps=50): self.width = width self.height = height self.fps = fps self.img_back = pygame.image.load('images/rothko_black.jpg') self.background = pygame.transform.scale(self.img_back, (self.width, self.height)) self.space = 20 self.letterSpace = 80 self.all_sprites_list = pygame.sprite.Group() sheep.rect.x = self.width/3 sheep.rect.y = self.height - (self.height/5) oilScrapie.rect.x = (2*self.space) oilScrapie.rect.y = self.height - (self.height/3) fire.rect.x = self.width - 9*self.space fire.rect.y = self.height - (self.height/8)
def main(): # default params init init_pos_limit = 10.0 epochs = 50 sheep_count = 15 sheep_move_dist = 0.5 wolf_move_dist = 1.0 log_lvl = None # sheep list flock = [] # sheep positions sheep_pos = [] # file data json_data = [] csv_data = [] # path to pos.json and alive.csv files data_dir = os.getcwd() # parse arguments parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', type=file_type, metavar='FILE', help='specify config file with initial values', dest='conf_file') parser.add_argument( '-d', '--dir', type=dir_type, metavar='DIR', help='specify path to catalog that holds generated files', dest='data_dir') parser.add_argument( '-l', '--log', type=int, metavar='LEVEL', help= 'choose level of logs saved in chase.log file: 10: DEBUG, 20: INFO, ' '30: WARNING, 40: ERROR, 50: CRITICAL', dest='log_lvl') parser.add_argument('-r', '--rounds', type=int, metavar='NUM', help='specify max number of iterations', dest='rounds_no') parser.add_argument('-s', '--sheep', type=int, metavar='NUM', dest='sheep_no', help='specify number of sheep in flock') parser.add_argument( '-w', '--wait', action='store_true', dest='wait_flag', help='wait for user at the end of each round to continue') parser.add_argument('-q', '--quiet', action='store_false', dest='quiet_flag', help='do not print info in terminal') args = parser.parse_args() # check optional args wait_flag = args.wait_flag print_flag = args.quiet_flag if args.data_dir: data_dir = os.path.join(data_dir, args.data_dir) if args.log_lvl: for lvl in [10, 20, 30, 40, 50]: if args.log_lvl == lvl: log_lvl = lvl if log_lvl is None: raise ValueError('no such level: ' + str(args.log_lvl)) print(os.path.join(data_dir, 'chase.log')) logging.basicConfig(filename=os.path.join(data_dir, 'chase.log'), filemode='w', level=log_lvl) if args.conf_file: config = configparser.ConfigParser() config.read(args.conf_file) terrain = config['Terrain'] movement = config['Movement'] if float(terrain['InitPosLimit']) < 0: logging.critical( 'ValueError raised: incorrect value in InitPosLimit config file' ) raise ValueError('negative value in config file: InitPosLimit') if float(movement['SheepMoveDist']) < 0: logging.critical( 'ValueError raised: incorrect value in SheepMoveDist config file' ) raise ValueError('negative value in config file: SheepMoveDist') if float(movement['WolfMoveDist']) < 0: logging.critical( 'ValueError raised: incorrect value in WolfMoveDist config file' ) raise ValueError('negative value in config file: WolfMoveDist') init_pos_limit = float(terrain['InitPosLimit']) sheep_move_dist = float(movement['SheepMoveDist']) wolf_move_dist = float(movement['WolfMoveDist']) if args.rounds_no: if args.rounds_no > 0: epochs = args.rounds_no elif log_lvl is not None: logging.warning( 'value passed by -r/--rounds is incorrect, continuing with default values' ) if args.sheep_no: if args.sheep_no > 0: sheep_count = args.sheep_no elif log_lvl is not None: logging.warning( 'value passed by -s/--sheep is incorrect, continuing with default values' ) # animals init wolf = Wolf(wolf_move_dist) for round_no in range(sheep_count): flock.append(Sheep(sheep_move_dist, round_no, init_pos_limit)) sheep_pos.append(flock[round_no].position) # log formatter epoch_log = '[{:2}]\twolf pos.: ({: >7.3f}, {: >7.3f})\tnumber of sheep: {:2}' eaten_log = ' •———— sheep [{:2}] is dead' tmp_str = epoch_log.format(0, wolf.position[0], wolf.position[1], len(flock)) if print_flag: print(tmp_str) logging.info(tmp_str) # wait for user input if wait_flag: input('Press enter to continue: ') # main loop for round_no in range(1, epochs + 1): # move and update sheep for sheep in flock: sheep.move() sheep_pos[sheep.id] = sheep.position # find closest sheep to wolf closest_sheep = flock[0] for sheep in flock: x = fun.calc_euclid_dist(wolf.position, sheep.position) if x < fun.calc_euclid_dist(wolf.position, closest_sheep.position): closest_sheep = sheep wolf.closest_sheep_pos = closest_sheep.position logging.info('sheep closest to wolf found ({})'.format( closest_sheep.position)) # eat or chase sheep if fun.calc_euclid_dist(wolf.position, closest_sheep.position) < wolf.move_dist: tmp_str = eaten_log.format(closest_sheep.id) if print_flag: print(tmp_str) logging.info(tmp_str) flock.remove(closest_sheep) sheep_pos[closest_sheep.id] = None else: wolf.move() logging.info('Wolf is chasing closest sheep') # print epoch summary tmp_str = epoch_log.format(round_no, wolf.position[0], wolf.position[1], len(flock)) if print_flag: print(tmp_str) logging.info(tmp_str) # append data to csv file csv_data.append([round_no, len(flock)]) # append data to json file cloned_sheep_pos_list = sheep_pos[:] json_data.append({ 'round_no': round_no, 'wolf_pos': wolf.position, 'sheep_pos': cloned_sheep_pos_list }) # end loop if no sheep in flock if len(flock) < 1: logging.info('simulation ended: all sheep were eaten') break # wait for user input if wait_flag and input('Press enter to continue: ') == 'exit': logging.info('simulation ended: user stopped the simulation') break # write to json file with open(os.path.join(data_dir, 'pos.json'), mode='w', newline='') as json_file: json_file.write(json.dumps(json_data, indent=4)) logging.info('data written to pos.json') # write to csv file with open(os.path.join(data_dir, 'alive.csv'), mode='w', newline='') as csv_file: writer = csv.writer(csv_file) writer.writerow(['epoch_no', 'living_sheep']) writer.writerows(csv_data) logging.info('data written to alive.csv')
from random import randint from tiger import Tiger from sheep import Sheep from room import Room import time print("*********游戏开始*********") #循环创建实例--10个房间实例--游戏初始化操作 roomList = [] for one in range(0, 10): #左含右不含 0----9 #随机取动物 if randint(0, 1) == 1: #老虎 ani = Tiger() else: #羊 ani = Sheep() room = Room(one, ani) #创建实例 roomList.append(room) startTime = time.time() while True: endTime = time.time() if endTime - startTime > 10: print("*********游戏结束*********") for roomNo, room in enumerate(roomList): print("房间号:%s 房间里的动物是:%s 动物的体重是:%s" % (roomNo + 1, room.animal.classname, room.animal.weight)) break roomNum = randint(0, 9) room = roomList[roomNum] print("当前房间号:%s,请选择敲门(k)/还是喂食(f)?" % (room.num + 1)) while True:
from rps.utilities.controllers import * from sheep import Sheep from shepherd import Shepherd import numpy as np import time # Instantiate Robotarium object N_SHEEP = 3 N_SHEPHERD = 2 N = N_SHEEP + N_SHEPHERD ITERATIONS = 500 sheeps = [Sheep() for _ in range(N_SHEEP)] shepherds = [Shepherd() for _ in range(N_SHEPHERD)] initial_conditions = np.array( np.mat('1 0.5 -0.5 0 0.28; 0.8 -0.3 -0.75 0.1 0.34; 0 0 0 0 0')) r = robotarium.Robotarium(number_of_robots=N, show_figure=True, initial_conditions=initial_conditions, sim_in_real_time=True) # Create barrier certificates to avoid collision uni_barrier_cert = create_unicycle_barrier_certificate() si_to_uni_dyn, uni_to_si_states = create_si_to_uni_mapping() # define x initially