def create_universe(self): """ This function creates a universe object that simulations will run in. The only asset in this \ simulation for an agent to use is a :class:`food.Food`. :return: the universe :rtype: universe.Universe """ # create the universe u = super(Eat_Lunch_Trial, self).create_universe() # this allows eating at work cafeteria = food.Food() cafeteria.location.local = location.OFF_SITE # allow the appropriate assets u.home.assets = { 'food': food.Food(), 'transport': transport.Transport(), 'workplace': workplace.Workplace(), 'cafeteria': cafeteria, } return u
def runTest(self): environment = Environment( ) #environment already initialized in test.py # test that environment is a singleton self.assertTrue(Environment() is environment) # test that environment initializes properly self.assertEquals(len(environment.cell_list), 10) self.assertEquals(len(environment.food_set), 10) self.assertTrue(environment.width > 0) self.assertTrue(environment.height > 0) # test that cells are within bounds for cell in environment.cell_list: self.assertTrue( cell.pos.x >= 0 and cell.pos.x <= environment.width and cell.pos.y >= 0 and cell.pos.y <= environment.height, "Cell location out of bounds.") # ..and food is within bounds for f in environment.food_set: self.assertTrue( f.pos.x >= 0 and f.pos.x <= environment.width and f.pos.y >= 0 and f.pos.y <= environment.height, "Food location out of bounds.") environment.cell_list = [] # test that a cell will find and eat food underneath it c = cells.Cell(environment.width / 2, environment.height / 2) environment.cell_list.append(c) food_count = len(environment.food_set) environment.food_set.add( food.Food(environment.width / 2, environment.height / 2)) environment.tick() # test that food list count was decremented after food is eaten self.assertEqual(len(environment.food_set), food_count) # test that food inside the cell is eaten environment.food_set.add( food.Food(environment.width / 2 + c.radius - 0.000001, environment.height / 2)) environment.tick() self.assertEqual(len(environment.food_set), food_count) # test that food outside the cell is not eaten environment.food_set.add( food.Food(environment.width / 2 + c.radius + 0.000001, environment.height / 2)) environment.tick() self.assertEqual(len(environment.food_set), food_count + 1) # test that add_cells adds the right number of cells num_cells = len(environment.cell_list) add_cells_count = random.randint(0, 100) environment.add_cells(add_cells_count) self.assertEqual( len(environment.cell_list) - add_cells_count, num_cells)
def game(): window.clear() window.nodelay(1) window.border() head = [dim[0] / 2, dim[1] / 2] body = [head[:]] * snakeLength direction = 1 # 0-up 1-right 2-down 3-left gameover = False deadcell = body[-1][:] foodmake = True foodGenerator = food.Food(dim[0] - 2, dim[1] - 2) timeSpeed = [0.1, 0.07, 0.04] while not gameover: while foodmake: y, x = list(foodGenerator.run()) if window.inch(y, x) == ord(' '): window.addch(y, x, 'o') foodmake = False step = window.getch() if step == curses.KEY_UP and direction != 2: direction = 0 if step == curses.KEY_RIGHT and direction != 3: direction = 1 if step == curses.KEY_DOWN and direction != 0: direction = 2 if step == curses.KEY_LEFT and direction != 1: direction = 3 window.addch(head[0], head[1], '#') if deadcell not in body: window.addch(deadcell[0], deadcell[1], ' ') if direction == 0: head[0] -= 1 if direction == 1: head[1] += 1 if direction == 2: head[0] += 1 if direction == 3: head[1] -= 1 deadcell = body[-1][:] for i in range(len(body) - 1, 0, -1): body[i] = body[i - 1][:] body[0] = head[:] if window.inch(head[0], head[1]) != ord(' '): if window.inch(head[0], head[1]) == ord('o'): for i in range(snakeGrowth): body.append(body[-1]) foodmake = True else: gameover = True window.refresh() time.sleep(timeSpeed[snakeLevel]) gameOver(len(body) - snakeLength)
def get_food_by_id_category(id_category): """ Select food in table food by the id of category :param id_category: :return: """ try: cursor = myDb.cursor() query = f"""SELECT id_food, product_name, generic_name, stores_tags, url, nutrition_grades, id_category FROM food WHERE id_category = {id_category};""" cursor.execute(query) results = cursor.fetchall() # print(results) myDb.commit() list_of_food_by_category = [] for result in results: food_by_id_category = food.Food(id_food=result[0], product_name=result[1], generic_name=result[2], stores_tags=result[3], url=result[4], nutrigrade=result[5], id_category=result[6]) list_of_food_by_category.append(food_by_id_category) return list_of_food_by_category except Error as e: message = f"select food encounter a mysql error : {e}" print(message)
def __init__(self): self.background = self.background.convert() self.player = player.Player() self.title = self.font.render("Fruit Shoot", True, constants.RED) self.player_select = Button("Select Player", (350, 600)) self.level1 = Button("Fruit in a Barrel", (200, 200)) self.level2 = Button("Raining Fruit", (300, 300)) self.level3 = Button("Fruit Pop", (400, 400)) self.level4 = Button("Fruit Flies", (500, 500)) self.level1.status = "New" self.food1 = food.Food() self.food2 = food.Food() self.food1.rect.x = 900 self.food1.rect.y = 150 self.food2.rect.x = 150 self.food2.rect.y = 500
def draw(self): screen_size = (self.width, self.height) screen = pygame.display.set_mode(screen_size) grid_instance = grid.Grid(self.square_side, self.width, self.height, self.grid_color) food_generator = food.Food(self.square_side, self.width, self.height, self.food_color) snake_instance = snake.Snake(self.square_side, self.width, self.height, self.snake_color, self.snake_head_color) food_generator.create_food() gameFinished = False while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: snake_instance.change_direction(event) if gameFinished: sleep(1) continue screen.fill(self.bg_color) success = snake_instance.move() if success == False: gameFinished = True continue if snake_instance.eat_food_if_exist(food_generator): food_generator.create_food() grid_instance.draw(screen) food_generator.draw(screen) snake_instance.draw(screen) pygame.display.flip() sleep(0.05)
def gameScene(state, screen, frameTime, gameClock, diff): """this is called when it's time to play the game, returns the new screen state""" # set up player and the game map mapRect = pygame.rect.Rect(50, 50, 700, 500) player = snake.Snake() fruit = food.Food(player.bodyList) if diff == 0: cooldown = 100 elif diff == 1: cooldown = 75 elif diff == 2: cooldown = 50 else: print("Difficulty selection failed, check the code") growSnake = False # initialises the score, as well as the font and the rect # which is used to define position and size of text (required for drawing) score = 0 scoreText = text.Text("Score: " + str(score), color=(100, 0, 100)) framesPerSec = text.Text() framesPerSec.rect.bottomleft = (0, 600) # main game loop of the game, only quits at change of game scene state while state == 1: frameTime += gameClock.tick(60) # logic updates if fruit.eaten(player): fruit.spawnFood() score += 10 scoreText.text = "Score: " + str(score) growSnake = True # will only displace the snake if the cooldown is over if frameTime >= cooldown: growSnake, state = player.update(growSnake, state, mapRect) frameTime = 0 framesPerSec.text = str(gameClock.get_fps())[:6] # drawing to the screen screen.fill((0, 150, 255)) pygame.draw.rect(screen, (0, 0, 0), mapRect, 3) player.draw(screen) fruit.draw(screen) scoreText.draw(screen) framesPerSec.draw(screen) pygame.display.flip() return state, score
def gameRunning(): running = True gameOver = False x = width / 2 y = height / 2 xspeed = 0 yspeed = 0 body = [] total = 1 Snake = snake.Snake(height, width, scale) Food = food.Food(xspeed, yspeed, scale, width, height) while running: clock.tick(15) surface.fill(black) if gameOver: surface.fill(black) message("OOPS, YOU LOST! Press SPACE-Restart or ESC-Exit", red, blue, surface) score(total - 1) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: running = False if event.key == pygame.K_SPACE: gameRunning() for event in pygame.event.get(): if event.type == pygame.QUIT: running = False xspeed, yspeed = Snake.direction(speed, event, xspeed, yspeed) gameOver = Snake.checkBoundaries(x, gameOver, y) x += xspeed y += yspeed Food.makeFood(red, surface) head = [] body, head = Snake.createSnake(x, y, head, body, total, white, surface) gameOver = Snake.checkSelf(gameOver, head, body) score(total - 1) pygame.display.update() total = Food.isEaten(x, y, total) Food.makeFood(green, surface) pygame.quit() quit()
def main(): width = 800 height = 600 gridColor = (43, 43, 43) frameRate = 10 gridSize = 20 gameOver = False score = 0 window = pygame.display.set_mode((width, height)) clock = pygame.time.Clock() ggrid = grid.Grid(gridSize, gridColor, width, height) folder = path.dirname(__file__) img_path = path.join(folder, 'assets/snake_sprite.png') spritesheet = sprites.SpriteSheet(img_path) my_snake = snake.Snake(3, (400, 300), gridSize, spritesheet) snack = food.Food(width, height, gridSize, spritesheet, (200, 300)) while not gameOver: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: my_snake.move_left() elif event.key == pygame.K_RIGHT: my_snake.move_right() elif event.key == pygame.K_UP: my_snake.move_up() elif event.key == pygame.K_DOWN: my_snake.move_down() # check for game over if my_snake.has_hit_wall(width, height): gameOver = True # check collision between cube and snack if hit_food(my_snake, snack): snack.move_random() my_snake.eat() score += 1 window.fill((0, 0, 0)) my_snake.move() ggrid.draw(window) snack.draw(window) my_snake.draw(window) displayScore(score, window) pygame.display.update() clock.tick(frameRate)
def addFood(self): while len(self.food) < MAX_FOOD_SUPPLY: f = food.Food( (random.randint(0, WIDTH), random.randint(0, HEIGHT)), food.COLOR, food.SIZE ) self.food.append(f)
def update(dt): for c in creature.creatures: c.do_stuff([i for i in creature.creatures if i != c], foods) if c in creature.creatures and c.health <= 0: creature.creatures.remove(c) if random.random() > 0.6: foods.append( food.Food(random.randint(0, window_width), random.randint(0, window_height)))
def __init__(self): pygame.init() self.screen = pygame.display.set_mode((400,400),0,32) self.clock = pygame.time.Clock() self.player = player.Snake(400,400) self.Food = food.Food() self.font = pygame.font.SysFont('Courier New',40)
def tick(self): self.clock.tick(60) moved = False for event in pygame.event.get(): if event.type == QUIT: raise GameException elif event.type == KEYDOWN: if event.key == 273: moved = self.snakeParts[0].moveTo(1) if event.key == 274: moved = self.snakeParts[0].moveTo(2) if event.key == 276: moved = self.snakeParts[0].moveTo(3) if event.key == 275: moved = self.snakeParts[0].moveTo(4) if not moved: self.move_timer = self.move_timer + 1 if self.move_timer == 10: self.move_timer = 0 self.moveAllSnakeParts() self.snakeParts[0].moveTo(self.snakeParts[0].lastDirection) else: self.move_timer = 0 self.moveAllSnakeParts() self.food_timer = self.food_timer - 1 if self.food_timer == 0: self.addObject( food.Food( random.randint(0, 100) * 8, random.randint(0, 75) * 8, self.background)) self.food_timer = random.randint(100, 200) for obj in self.gameObjects: for obj2 in self.gameObjects: if obj != obj2 and obj.rect.colliderect(obj2): obj.collide(self, obj2) # obj2.collide(self, obj) toRemove = [] for obj in self.gameObjects: if hasattr(obj, "dead"): if obj.dead: toRemove.append(obj) for obj in toRemove: self.removeObject(obj) self.drawThing = text.draw(20, 20, self.background, self.score) self.rdrawThing = pygame.sprite.RenderPlain(self.drawThing) self.sprites.update() self.screen.blit(self.background, (0, 0)) self.rdrawThing.draw(self.screen) self.sprites.draw(self.screen) pygame.display.flip()
def reinitialize(): global snake_obj global food_obj global state state = Game_state.PLAYING snake_obj = snake.Snake() food_obj = food.Food(snake_obj) score_obj.reset() hs_obj.reset()
def __init__(self): self.running = True self.player = player.Player() self.food = food.Food(config.tile_size * -1, config.tile_size * -1) self.screen = None x_size = int(config.screen_width / config.tile_size) y_size = int(config.screen_height / config.tile_size) self.empty = np.full((x_size, y_size), True, dtype=bool)
def _get_food_range(start_date, end_date): global FIRST foods = [] for date in daterange(start_date, end_date): d = date.strftime("%Y-%m-%d") print('Pulling {} from server...'.format(d)) foods.append((d, food.Food(d, FIRST))) FIRST = False return foods
def __init__(self): #dimensions self.width = 7 self.height = 7 #actors self.snakeIsdead = False self.snake = snake.Snake() self.food = food.Food(self.width, self.height)
def main(ls): get = True while get: print("Add to list options: ") print("1. Create new food") print("2. Import from another list") print("3. Go back") op = input() if op.isdigit(): if int(op) == 1: name = input("New food name: ") nights = input("Leftover nights: ") time = input("Prep+Cook time: ") ingredients = input( "List of ingredients (separate items with \",[SPACE]\"): " ).rsplit(", ") ls.append(food.Food(name, nights, time, ingredients)) print(f"{name.title()} added") elif int(op) == 2: print("Select a list: ") count = 1 lists = [] for f in os.listdir("../lists"): print(f"{count}. {f.replace('.txt', '').title()}") count += 1 lists.append(f) listChoice = input() if listChoice.isdigit(): if int(listChoice) < count: fname = lists[int(listChoice) - 1] file = open("../lists/" + fname, "r") list2 = makeFoodList(file, []) file.close() print(f"{fname.title()} List:") view.main(list2) print("Name of food to import: ") importFood = input() for foo in list2: if foo.getName().capitalize( ) is importFood.capitalize(): ls.append(importFood) print(f"{importFood} added") else: print("Invalid input") else: print("Invalid input") else: print("Invalid input") elif int(op) == 3: get = False else: print("Invalid input") else: print("Invalid input")
def addfood(self, food_coverage): amount = 0 takeClosest = lambda num,collection:min(collection,key=lambda x:abs(x-num)) squares = [1,4,9,16,25,36,49,64,81,100] amount = takeClosest(np.sqrt(self.area),squares) food_radius = np.sqrt((food_coverage*self.area)/(amount * math.pi)) for i in np.arange(self.width/np.sqrt(amount)/2, self.width + self.width/np.sqrt(amount)/2, self.width/np.sqrt(amount)): for j in np.arange(self.height/np.sqrt(amount)/2, self.height + self.width/np.sqrt(amount)/2, self.height/np.sqrt(amount)): food = f.Food(i, j, self, size = food_radius) self.food.append(food)
def __init__(self,background_img,splat_img,food_no): self.gui = gui.GUI(splat_img) self.player = player.Player() self.background = pygame.image.load(os.path.join('images', background_img)).convert() self.foods = [] for x in range(food_no): x = food.Food() self.foods.append(x) self.time = 70 t = threading.Timer(1.0,self.countdown) t.start()
def init(w, h, nc, nf): global cellCount weight = w height = h for _ in range(nc): position = [random.randrange(w),random.randrange(h)] cells.append(cell.Cell(position,randomDNK(24),cellCount)) cellCount += 1 for _ in range(nf): position = [random.randrange(w),random.randrange(h)] foods.append(food.Food(position))
def __init__(self): pygame.init() self.screen = pygame.display.set_mode((410, 410), 0, 32) self.clock = pygame.time.Clock() self.player = player.Snake(400, 400) self.foodpile = food.Food() self.font = pygame.font.SysFont('Comic Sans MS', 40) self.name = '' self.highscore = []
def create_food(self): """Готовка еды поворихой""" food = [["Селедка", 2.0, 150], ["Борщ", 0.5, 65], ["Говядина", 3.5, 210], ["Курица", 2.0, 110], ["Щи", 0.6, 70], ["Отбивная", 3.0, 310], ["Греча", 1.2, 110], ["Салат 'Морской'", 1.6, 90], ["Салат 'Весенний'", 1.10, 67], ["Рис", 1.30, 190]] dish = choice(food) self.money -= (dish[1]) / 2 new_dish = f.Food(dish[0], dish[1], dish[2]) return new_dish
def startup(): mapgen() for i in range(9): antList.append(ant.Ant((random.randint(0, 49), 23), 0)) for j in range(2): foodList.append(food.Food(random.randint(0,49), array))
def makeFoodList(file, ls=None): if ls is None: ls = [] for line in file: if line is not None: line = line.rsplit(":") ls.append( food.Food(line[0], nights=line[1], time=line[2], ingredients=line[3])) return ls
def update(): for i, c in enumerate(cells): live = c.update() if not live: cells.pop(i) for i, f in enumerate(foods): if not f.update(): foods.pop(i) for i in random.randrange(2): position = [random.randrange(width),random.randrange(height)] foods.append(food.Food(position)) pass
def __init__(self): pygame.init() self.clock = pygame.time.Clock() food_x, food_y = random.randint(1, 18), random.randint(1, 18) self.screen = pygame.display.set_mode((width, height), 0, 32) self.player = player.Snake() self.time = 0 self.start = True self.Food = food.Food() self.font = pygame.font.SysFont('Comic Sans MS', 30)
def __init__(self, clock): self.id = -1 self.category = APARTMENT self.population = 0 self.clock = clock self.location = loc.Location( loc.NORTH, loc.HOME) # list of assets all Homes have # recall need to set the location of the work asset wp1 = workplace.Workplace() # allows sleeping bed1 = bed.Bed() # allows commuting the_transport = transport.Transport() the_transport.max_users = 1 # food1 allows eating at home food1 = food.Food() # cafeteria allows eating at work cafeteria = food.Food() cafeteria.location.local = loc.OFF_SITE # store all of the assets self.assets = { 'workplace': wp1, 'bed': bed1, 'transport': the_transport, 'food': food1, 'cafeteria': cafeteria } # the revenue of the house self.revenue = 0.0 return
def play(self): pygame.init() x = 800 y = 600 squareSize = 10 clock = pygame.time.Clock() screen = pygame.display.set_mode((x, y), 0, 32) surface = pygame.Surface(screen.get_size()) surface = surface.convert() temp = pygame.Rect((0, 0), (800, 600)) pygame.draw.rect(surface, (100, 100, 100), temp) temp = pygame.Rect((0, 0), (800, 10)) pygame.draw.rect(surface, (0, 0, 0), temp) temp = pygame.Rect((0, 590), (800, 10)) pygame.draw.rect(surface, (0, 0, 0), temp) temp = pygame.Rect((0, 0), (10, 800)) pygame.draw.rect(surface, (0, 0, 0), temp) temp = pygame.Rect((790, 0), (10, 800)) pygame.draw.rect(surface, (0, 0, 0), temp) s = snaek.Snaek() f = food.Food() f.draw(surface) while (1): clock.tick(30) s.changeDirection(self.keypress()) try: s.move(surface) except: self.gameOver(surface, s.counter) if (s.ateFood(f.x, f.y)): s.addItem() while not s.foodValid(f.x, f.y): f = food.Food() if (s.foodValid(f.x, f.y)): f.draw(surface) break screen.blit(surface, (0, 0)) pygame.display.update()
def setup_screens(self): """Set up the game screens.""" self.level = level_screen.LevelScreen(self.theme) self.main_menu = main_menu_screen.MainMenuScreen(self.theme) self.start_title_loop = False self.pause_title_loop = False self.game_over_screen = game_over_screen.GameOverScreen(self.theme) # Instantiate snake & food objects in position for the main menu. self.snake_p1 = snake.Snake(self.theme, size=settings.CELL, speed=12, head_pos=[12, 27], direction='') self.food = food.Food(self.theme, settings.CELL, self.snake_p1, pos=[6, 27])