コード例 #1
0
    def update(self):
        self.handle_keys()

        self.trail_sprite_group.empty()
        #Collision
        for player in self.players:
            player.update()
            for i in player.trail:
                self.trail_sprite_group.add(i)
        for player in self.players:
            #Border Collision
            if player.rect.x < 0 or player.rect.x > (RESOLUTION[0] - CHUNK_SIZE):
                change_state()
            if player.rect.y < 0 or player.rect.y > (RESOLUTION[1] - CHUNK_SIZE):
                change_state()
            #Food Collision
            for hit in pygame.sprite.spritecollide(player, self.food_sprite_group, True):
                player.score += 1
                self.food_sprite = Food.Food(self.resolution, self.chunk_size, self.food)
                for sprite in self.trail_sprite_group.sprites():
                    if sprite.rect.x == self.food_sprite.rect.x and sprite.rect.y == self.food_sprite.rect.y:
                        self.food_sprite = Food.Food(self.resolution, self.chunk_size, self.food)
                self.food_sprite_group.add(self.food_sprite)
            for hit in pygame.sprite.spritecollide(player, self.trail_sprite_group, False):
                change_state()
コード例 #2
0
def test(screen):
    test_mold_eaten = Food(21, 39, 800, 800)
    test_mold_not_eaten = Food(100, 39, 800, 800)
    test_herbivore_eaten = Boid(21, 39, 800, 800)
    test_herbivore_not_eaten = Boid(201, 39, 800, 800)
    test_carnivore = WildBoid(21, 39, 800, 800)

    test_mold_eaten.rect = test_mold_eaten.rect.move(
        int(test_mold_eaten.position.x), int(test_mold_eaten.position.y))
    screen.blit(
        test_mold_eaten.image,
        (int(test_mold_eaten.position.x), int(test_mold_eaten.position.y)))
    test_mold_not_eaten.rect = test_mold_not_eaten.rect.move(
        int(test_mold_not_eaten.position.x),
        int(test_mold_not_eaten.position.y))
    screen.blit(test_mold_not_eaten.image, (int(
        test_mold_not_eaten.position.x), int(test_mold_not_eaten.position.y)))
    test_herbivore_eaten.rect = test_herbivore_eaten.rect.move(
        int(test_herbivore_eaten.position.x),
        int(test_herbivore_eaten.position.y))
    screen.blit(test_herbivore_eaten.image,
                (int(test_herbivore_eaten.position.x),
                 int(test_herbivore_eaten.position.y)))
    test_herbivore_not_eaten.rect = test_herbivore_not_eaten.rect.move(
        int(test_herbivore_not_eaten.position.x),
        int(test_herbivore_not_eaten.position.y))
    screen.blit(test_herbivore_not_eaten.image,
                (int(test_herbivore_not_eaten.position.x),
                 int(test_herbivore_not_eaten.position.y)))
    test_carnivore.rect = test_carnivore.rect.move(
        int(test_carnivore.position.x), int(test_carnivore.position.y))
    screen.blit(
        test_carnivore.image,
        (int(test_carnivore.position.x), int(test_carnivore.position.y)))

    food = [test_mold_eaten, test_mold_not_eaten]
    prey = [test_herbivore_eaten, test_herbivore_not_eaten]

    def test_eaten():
        assert test_herbivore_eaten.eaten(food) ==\
            (True, test_mold_eaten), "Should be (True, test_mold_eaten)"
        print("First test passed")

    def test_killed():
        assert test_carnivore.killed(prey) ==\
            (True, test_herbivore_eaten), "Should be (True, test_herbivore_eaten)"
        print("Second test passed")

    test_eaten()
    test_killed()
コード例 #3
0
    def __init__(self):
        try:
            address = sys.argv[1]
            port = int(sys.argv[2])
            self.event = KEY_RIGHT
            self.dir = "right"
            self.totalSnakes = int(sys.argv[3])
            self.connections = []
            self.addresses = []
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.bind((address, port))
            self.sock.listen(1)
            self.snakes = []
            self.data = {
                "win": 0,
                "dead": [],
                "snakes": [],
                "food": [],
                "scores": [],
            }
            for i in range(0, self.totalSnakes):
                self.snakes.append(Snake.Snake(i + i))
                self.data["scores"].append(0)
                self.data["dead"].append(False)
                self.data["snakes"].append(self.snakes[i].getBody())
            self.food = Food.Food()
            self.data["food"] = self.food.getCor()

        except Exception as e:
            print(e)
            self.sock.close()
            exit()
コード例 #4
0
    def __init__(self):
        super().__init__()
        self.name = "GameState"

        #Textures
        self.snake = pygame.transform.scale(pygame.image.load('Snake.png').convert(), (CHUNK_SIZE, CHUNK_SIZE))
        self.trail = pygame.transform.scale(pygame.image.load('Trail.png').convert(), (CHUNK_SIZE, CHUNK_SIZE))
        self.food = pygame.transform.scale(pygame.image.load('Food.png').convert(), (CHUNK_SIZE, CHUNK_SIZE))

        self.highscore = int(open('Score.dat', 'r').readline())
        #Colors
        self.background = (51, 51, 51)
        self.white = (255, 255, 255)

        #Sprites
        self.player_sprite = Player.Player(RESOLUTION, CHUNK_SIZE, 2, 0, SNAKE, TRAIL)
        self.player_sprite_group = pygame.sprite.Group()

        self.food_sprite = Food.Food(RESOLUTION, CHUNK_SIZE, FOOD)
        self.food_sprite_group = pygame.sprite.Group()
        self.food_sprite_group.add(self.food_sprite)

        self.trail_sprite = Trail.Trail(RESOLUTION, CHUNK_SIZE, 2, 2, FOOD)
        self.trail_sprite_group = pygame.sprite.Group()
        self.trail_sprite_group.add(self.trail_sprite)

        #Other
        self.chunk_size = 16
        self.chunk_amount = 32
        self.resolution = (self.chunk_size * self.chunk_amount, self.chunk_size * self.chunk_amount)
コード例 #5
0
 def __init__(self):
     # try:
     address = sys.argv[1]
     port = int(sys.argv[2])
     self.event = KEY_RIGHT
     self.dir = "right"
     self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.sock.connect((address, port))
     self.rdata = json.loads(str(self.sock.recv(2048)))
     self.id = self.rdata["id"]
     self.data = self.rdata["data"]
     self.totalSnakes = len(self.data["snakes"])
     curses.initscr()
     self.score = 0
     self.window = curses.newwin(HEIGHT, WIDTH, 0, 0)
     self.window.timeout(TIMEOUT)
     self.window.keypad(1)
     curses.noecho()
     curses.curs_set(0)
     self.window.border(0)
     self.snakes = []
     for i in range(0, self.totalSnakes):
         self.snakes.append(Snake.Snake(self.window,
                                        self.data["snakes"][i]))
     self.food = Food.Food(self.window, self.data["food"][0],
                           self.data["food"][1])
コード例 #6
0
 def decode(self, encoded):
     self.board = Board(src=encoded["board"])
     self.id_snakes = {
         sid: Snake(src=s)
         for sid, s in encoded["snakes"].items()
     }
     self.foods = {fcell: Food(fcell) for fcell in encoded["foods"]}
コード例 #7
0
ファイル: States.py プロジェクト: Prhmma/Snake
    def __init__(self):
        super(PlayState, self).__init__()

        # PLAYER, BOARD, FOOD
        self.player = Player((NUM_ROWS // 2, NUM_COLS // 2), 'START', BLUE, 2)
        self.board = Board()
        self.food = Food()
        self.initialized = True  # flag used for initial board generation

        # FITNESS FUNCTION KILL SWITCH
        self.moves_since_food = 0

        # PLAYER NAMES & SCORES
        self.font = pygame.font.SysFont(FONT, 24)
        self.player_text = self.font.render(
            "Player 1: {0:>4d}".format(self.player.score), True,
            WHITE)  # TODO make color generic for choice
        self.player_text_pos = self.player_text.get_rect()

        self.player_text_pos.x = self.player_text_pos.y = CELL_SIDE

        # LOGO
        self.logo_text = pygame.font.SysFont(FONT, 48).render(
            "SNAKE", True, (0, 255, 0))
        self.logo_text_pos = self.logo_text.get_rect()
        self.logo_text_pos.x = SCREEN_WIDTH // 2
        self.logo_text_pos.y = CELL_SIDE
コード例 #8
0
 def feed(self,food_stor):
     self.current_image = random.choice(self.images)
     if (self.y_mouse > 90 and self.y_mouse < 590 and
     self.x_mouse > 15 and self.x_mouse < 765) and (self.max_food < 8) and self.bank_value > 4: #mouse is in the tank and bank has money
             food_stor.add(Food(self.current_image,self.x_mouse,self.y_mouse))
             self.max_food += 1
             self.bank_value -= 5
             return True
コード例 #9
0
ファイル: Engine.py プロジェクト: undisputeDD/SimulaCrum
 def generate_food(self):
     for i in range(amount_food):
         food = Food.Food(self.screen, self.sim_data['design'])
         self.food_list.append(food)
         x = 20 + round(random.random() * width)
         y = 20 + round(random.random() * height)
         self.food_coords.append((x, y))
         food.draw(x, y)
コード例 #10
0
    def spawn_food(self):
        x = int(random.random() * Const.GRID_NR_W) * Const.BODY_SIZE + Const.BODY_SIZE / 2
        y = int(random.random() * Const.GRID_NR_H) * Const.BODY_SIZE + Const.BODY_SIZE / 2
        type = int(random.random() * 5)
        # thank to this if normal apple (type 0) should appear 50% of the time
        if type != 0:
            type = int(random.random() * 5)

        self.food = Food.Food(type, x, y)
コード例 #11
0
ファイル: Game.py プロジェクト: JacenWilliams/DeadishCells
    def update(self):
        self.recalculate_vectors()
        self.kdtree = KDTree(self.vectors)
        neighbor_distances, neighbor_indexes = self.kdtree.query(self.vectors,
                                                                 k=6)
        neighbor_indexes = neighbor_indexes[:, 1:]
        num_cells = len(self.cells)
        # self.food_spawn_rate = math.ceil(len(self.cells) / 30)

        for i, cell in enumerate(self.cells):
            input_list = [
                cell.position.x, cell.position.y, cell.velocity.x,
                cell.velocity.y, cell.health
            ]

            for index in neighbor_indexes[i]:
                if index > num_cells - 1:
                    input_list.append(1.0)
                    input_list.append(self.food[index - num_cells].position.x)
                    input_list.append(self.food[index - num_cells].position.y)
                else:
                    input_list.append(0.0)
                    input_list.append(self.cells[index].position.x)
                    input_list.append(self.cells[index].position.y)

            cell.update(input_list)
            nearest_index = neighbor_indexes[i][1]
            if nearest_index < len(self.cells):
                nearest = self.cells[nearest_index]

            else:
                nearest = self.food[nearest_index - num_cells]
            collide = cell.collision(nearest)

            if collide:
                if isinstance(nearest, Food.Food):
                    cell.health += 0.1
                    cell.score += 1
                    self.eaten_food.append(
                        [nearest, nearest_index - num_cells])
                elif cell.breed_cooldown < 0 and nearest.breed_cooldown < 0:
                    self.breed_cells(cell, nearest)
                    cell.score += 2
                    nearest.score += 2

            if cell.health < 0:
                self.dead_cells.append([cell, i])

        for i in range(self.food_spawn_rate):
            food = Food.Food(np.random.random() * self.width,
                             np.random.random() * self.height)
            self.new_food.append(food)

        self.remove_dead_objects()
        self.add_new_objects()
        self.counter += 1
コード例 #12
0
    def __init__(self):
        pygame.init()

        self.S = Snake()
        self.F = Food()
        # self.M = Menu()

        self.CLOCK = pygame.time.Clock()

        self.reset()
コード例 #13
0
 def set_food(self, food):
     if food == 1:
         self.food_type = food
         self.food = Food.Food(self.rect.x, self.rect.y, self.game, self)
     elif food == 0:
         self.food_type = food
         self.food = None
     elif food == 2:
         self.food_type = food
         self.food = Food.Energiser(self.rect.x, self.rect.y, self.game,
                                    self)
コード例 #14
0
 def __init__(self, Grid):
     self.grid = Grid
     self.body = [(10, 6), (10, 7), (10, 8)]
     self.direction = "Up"
     self.status = ['run', 'stop']
     self.speed = 300
     self.color = "#FFC64B"
     self.food = Food(self.grid)
     self.display_food()
     self.gameover = False
     self.score = 0
コード例 #15
0
ファイル: Game.py プロジェクト: dewdevil99/Snakey
	def setup(self):
		self.scoreText=self.font_big.render("SCORE : 0",True,pygame.Color(0,255,0))
		self.snake_head=Snake.Snake(150,150)
		self.snake_head.image.fill(pygame.Color(0,0,255))
		self.spritesList.add(self.snake_head)
		for i in range(1,3):
			segment=Snake.Snake(150,150+i*10)
			self.snake_segs.append(segment)
			self.spritesList.add(segment)
		self.food=Food.Food()
		self.score=0
コード例 #16
0
ファイル: notable.py プロジェクト: holychikenz/ISRecipes
def main():
    with open("foods.json") as jj:
        ingredients = json.load(jj)
    with open("recipes.json") as jj:
        recipes = json.load(jj)
    chef = Food(ingredients, recipes, level=60)

    print(f'Max depth: {len(chef.allIngredients())}')
    print(chef.allIngredients())
    exclude = ['raw tuna', 'raw trout', 'raw shark']
    deepsearch(chef, exclude=exclude)
コード例 #17
0
ファイル: main.py プロジェクト: ArBond/My-projects
 def __init__(self):
     pygame.init()
     self.width = 500
     self.height = 500
     self.clock = pygame.time.Clock()
     pygame.display.set_caption("Snake")
     pygame.display.set_icon(pygame.image.load('images\icon.png'))
     self.font = pygame.font.SysFont('Comic Sans MS', 20)
     self.screen = pygame.display.set_mode([self.width, self.height])
     self.snake = Snake(self.width, self.height)
     self.food = Food(self.width, self.height)
     self.fail_sounds = self.GetOggFiles("sounds\\fail")
コード例 #18
0
    def spawnOneFood(self, origin=(0, 0), random=False):

        if random:
            x, y = self.getSpawnLocationDistribution(origin)
        else:
            x, y = origin

        self.pos_food[(x, y)] = Food(
            x, y,
            Globals.glwidget.createImage(
                Globals.datadir + 'images/food/food.png', 2, [32, 32, 32, 32],
                [x * 32, y * 32, 32, 32]))
        self.occupiedTiles[(x, y)] = True
コード例 #19
0
 def __init__(self):
     try:
         curses.initscr()
         self.score = 0
         self.window = curses.newwin(HEIGHT, WIDTH, 0, 0)
         self.window.timeout(TIMEOUT)
         self.window.keypad(1)
         curses.noecho()
         curses.curs_set(0)
         self.window.border(0)
         self.snake = Snake.Snake(self.window)
         self.food = Food.Food(self.window)
     except:
         curses.endwin()
コード例 #20
0
def check_eat(snake, food):
    """
    Checks if snake ate the food. Calls generation of new position if food is eaten.

    Args:
        snake (obj): Object of class Snake
        food (obj): Object of class Food
    """

    if snake.get_head_position() == food.position:
        snake.length += 1
        snake.points += Variables.score_multi
        Variables.is_eaten = True
        Food.Food().generate_food_pos()
コード例 #21
0
    def enter(self, chunk_size, chunk_amount):
        self.player_sprite = Player.Player(self.resolution, self.chunk_size, 2, 2, self.snake, self.trail)
        self.player_sprite_group = pygame.sprite.Group()
        self.player_sprite_group.add(self.player_sprite)
        self.players = [self.player_sprite]

        #Setup for food
        self.food_sprite = Food.Food(self.resolution, self.chunk_size, self.food)
        self.food_sprite_group = pygame.sprite.Group()
        self.food_sprite_group.add(self.food_sprite)

        #Setup for trails
        self.trail_sprite = Trail.Trail(self.resolution, self.chunk_size, 2, 2, self.food)
        self.trail_sprite_group = pygame.sprite.Group()
        self.trail_sprite_group.add(self.trail_sprite)
コード例 #22
0
ファイル: Cell.py プロジェクト: DeForestt/Petri-Dish
    def eat_food(self, dish):

        closest_food = Food((1000000, 1000000), dish)
        go = False
        for food in dish.food:
            if food.distance(self.position) < closest_food.distance(
                    self.position):
                closest_food = food
                go = True
        if go:
            if closest_food.distance(self.position) <= self.radius:
                self.hunger = 0
                dish.food.remove(closest_food)
                closest_food.eat()
            self.move_towards(closest_food.position,
                              closest_food.distance(self.position))
コード例 #23
0
    def __init__(self, type, index, left, top, game, food_type=0):
        #1 - food, 2 - energiser

        self.game = game
        self.type = type
        self.image = pygame.image.load("res\\" + type + ".gif")
        self.rect = self.image.get_rect(topleft=(left, top))
        self.is_wall = not (type == "empty")
        self.index = index
        self.food_type = food_type
        if self.food_type == 0:
            self.food = None
        if food_type == 1:
            self.food = Food.Food(left, top, game, self)
        if food_type == 2:
            self.food = Food.Energiser(left, top, game, self)
            print(self.food.rect.width)
コード例 #24
0
ファイル: Game.py プロジェクト: JacenWilliams/DeadishCells
    def init_objects(self):
        i = 0
        while i < self.initial_cell_count:
            cell = Cell.Cell(np.random.random() * self.width,
                             np.random.random() * self.height, self.width,
                             self.height, self.friction, self.input_size,
                             self.hidden_size, self.output_size,
                             self.mutation_rate, self.crossover_rate)
            self.cells.append(cell)
            i += 1

        i = 0

        while i < self.initial_food_count:
            f = Food.Food(np.random.random() * self.width,
                          np.random.random() * self.height)
            self.food.append(f)
            i += 1
コード例 #25
0
ファイル: PlayMap.py プロジェクト: yazici/python-animations
    def updateState(self):
        """
                function to update the current state of the game board
                aka what is the state one time unit in the future

                Transition: moves snake, grows, or dies based on situation
                input:none
                output:none
                """

        self.snake.move()
        # deal with food

        head = self.snake.points[0]
        if head == self.food.position:
            self.snake.grow()
            self.food = Food()
            self.score += 1
コード例 #26
0
ファイル: PlayMap.py プロジェクト: yazici/python-animations
    def __init__(self):
        """
                Constructor method for PlayMap
                Transition: initialized into new game state
                input:none
                output:none
                """

        self.height = 500
        self.width = 550
        self.snake = Snake()  # starting coord of snake
        self.food = Food()
        self.powerUp = PowerUp()

        self.powerUpStatus = True
        self.gameStatsBar = pygame.Rect(0, 0, 550, 20)
        self.powerUpIndicator = pygame.Rect(10, 0, 10, 10)
        self.score = len(self.snake.points)
        self.diff = 0
コード例 #27
0
def game_init():
    global screen, font, timer, backbuffer, snake
    global food_group

    pygame.init()
    pygame.display.set_caption("Snake Game")
    screen = pygame.display.set_mode((24*32, 18*32))
    font = pygame.font.Font(None, 30)
    timer = pygame.time.Clock()

    # create a drawing surface
    backbuffer = pygame.Surface((screen.get_rect().width, screen.get_rect().height))

    # create snake
    snake = Snake()

    # create food
    food_group = pygame.sprite.Group()
    food = Food()
    food_group.add(food)
コード例 #28
0
def game_loop():
    """
    The main loop of the game. It creates the snake, calls functions for drawing elements and checks key events.
    """

    snake = Snake.Snake()
    food = Food.Food()

    while True:
        for event in Variables.pygame.event.get():
            if event.type == Variables.pygame.QUIT:
                Variables.Functions.end_game()
            elif event.type == Variables.pygame.KEYDOWN:
                if event.key == Variables.pygame.K_UP:
                    snake.change_direction(Variables.UP)
                elif event.key == Variables.pygame.K_DOWN:
                    snake.change_direction(Variables.DOWN)
                elif event.key == Variables.pygame.K_LEFT:
                    snake.change_direction(Variables.LEFT)
                elif event.key == Variables.pygame.K_RIGHT:
                    snake.change_direction(Variables.RIGHT)
                elif event.key == Variables.pygame.K_SPACE:
                    Variables.Screens.pause(snake)

        Variables.screen.blit(Variables.surface, [0, 0])
        snake.move()
        Variables.Functions.check_eat(snake, food)
        food.draw()
        snake.draw(Variables.screen)
        Variables.Functions.score(snake.points)
        Variables.Functions.length(snake.length)
        Variables.pygame.display.update()
        if Variables.is_eaten:
            # that you can see the open mouth!
            time.sleep(.1)
            Variables.is_eaten = False
        if Variables.is_dead:
            Variables.Screens.lost()
        # it's getting harder and harder...
        Variables.clock.tick(Variables.fps + snake.length / 3)
コード例 #29
0
    def level_1(self):
        """
        Level 1: Pac-man know the food’s position in map and monsters do not appear in map.
        There is only one food in the map.
        """
        graph_map, pacman_pos, food_pos = Map.read_map_level_1(
            MAP_INPUT_TXT[self.current_level - 1][self.current_map_index])
        path = GraphSearchAStar.search(graph_map, pacman_pos, food_pos)

        pacman = Pacman.Pacman(self, pacman_pos)
        pacman.appear()

        food = Food.Food(self, food_pos)
        food.appear()

        if self.ready():
            if path is not None:
                back_home = False
                goal = path[-1]
                path = path[1:-1]

                for cell in path:
                    pacman.move(cell)
                    self.update_score(SCORE_PENALTY)
                    pygame.time.delay(
                        int(SPEED // self.speed_list[self.cur_speed_index][1]))

                    if self.launch_game_event():
                        back_home = True
                        break

                if not back_home:
                    pacman.move(goal)
                    self.update_score(SCORE_PENALTY + SCORE_BONUS)
                    self.state = STATE_VICTORY
                    pygame.time.delay(2000)
            else:
                self.state = STATE_GAMEOVER
                pygame.time.delay(2000)
コード例 #30
0
ファイル: Game.py プロジェクト: ninaricci29/CSC290Pacdude
    def setup_level(self):
        w = len(MAP[0])
        h = len(MAP) + 1  # We add a bit of space for the text at the bottom
        self.barriers = []
        self.ghosts = []
        self.foods = []
        self.stage_width, self._stage_height = w, h - 1
        self.size = (w * ICON_SIZE, h * ICON_SIZE)

        for i in range(len(MAP)):
            for j in range(len(MAP[i])):
                key = MAP[i][j]
                if key == 'P':
                    self.set_player(Pacman(i, j, 24, 24, {}))
                elif key == 'G':
                    self.add_ghost(Ghost(i, j, 24, 24, {}))
                elif key == 'O':
                    self.add_food(Food(i, j, 10, 10, {}))
                elif key == 'X':
                    self.add_barrier(Barrier(i, j, 24, 24, {}))

        self.goal_CGPA = 3.0
        self.current_CGPA = 0.0
        self.goal_message = "Objective: Collect good marks to meet your CGPA!"