Exemplo n.º 1
0
    def __init__(self, data):
        self._turn = data['turn']
        self._width = data['board']['width']
        self._height = data['board']['height']
        self._nodes = dict()

        self._food_list = []
        self._enemy_list = []

        self._our_snake = None

        our_id = data['you']['id']

        # Process Snakes
        for snake in data['board']['snakes']:
            snake_info = SnakeInfo(snake, self, our_id)

            if snake_info.is_enemy():
                self._enemy_list.append(snake_info)
            else:
                self._our_snake = snake_info

            for point in snake['body']:
                new_snake = SnakeNode(point, snake_info)
                self._nodes[new_snake.get_point()] = new_snake

        snake_head = self._our_snake.get_head()
        # Process Food
        for raw_data in data['board']['food']:
            new_food = Food(raw_data, snake_head)
            self._food_list.append(new_food)
            self._nodes[new_food.get_point()] = new_food

        self._food_list = sorted(self._food_list,
                                 key=operator.attrgetter('_start_distance'))
Exemplo n.º 2
0
def main():
    '''
    s = Stack()
    arr = [11, 22, 33, 44, 55, 66]
    array_to_stack(s, arr)
    for v in s:
        print(v)
    stack_to_array(s,arr)
    print(arr)
    '''
    '''
    arr2 = [1,2,3,4]
    s2 = Stack()
    for a in arr2:
        s2.push(a)
    stack_test(s2)
    for v in s2:
        print(v)
    '''
    #testing the stack
    arr2 = [1, 2, 3, 4]
    stack_test(arr2)

    f = Food("bread", 10, True, 55)
    g = Food("grape", 6, False, 9)
    foods = [f, g]
    stack_test(foods)
    '''
Exemplo n.º 3
0
def main():
    food = Food("grape", 3, True, 2)
    food1 = Food("chicken", 2, False, 1)
    food2 = Food("sushi", 3, True, 12)
    foods = [food, food1, food2]
    avg = average_calories(foods)
    print(avg)
Exemplo n.º 4
0
def routineTo(sf, cf):
    gen = Genetic(sf, cf)
    fen = fenetre()
    food = Food(fen)
    #newFen = newFenTop()
    #texts = addScoreOnTopWindows(newFen, int(Params.p['sizePop']))
    pop = Population(fen, food)
    pop.setInitialPositions()
    for i in range(int(Params.p['nbEvol'])):
        popName = "pop_" + str(i)
        if i > 0:
            gen.createNewPopulation(pop)
            food = Food(fen)
            pop.setFood(food)
            pop.setInitialPositions()
        #newFen[1].itemconfig(newFen[2], text=popName)
        t = time.time()
        #while time.time() - t < Params.p['lifeTime']:
        j = 0
        while j < Params.p['lifeTime']:
            #refreshScores(newFen, texts, pop)
            pop.routineForPopulation()
            fen.refreshScreen()
            j += 1
        timeGen = time.time() - t
        print("Execution time: ", timeGen)
        savePop(pop, popName = popName)
    fen.fen.destroy()
Exemplo n.º 5
0
 def __init__(self):
     self.player = Player(self.screen ,self.x,self.y)
     self.collider=Collider(self.screen,self.player.arrows,self.badguys,self.player,self.foods)
     self.food = Food(self.screen,self.food_x, self.food_y)
     self.wl=WL(self.screen,self.exitcode)
     self.timer=Timer(self.screen,self.count)
     self.screen2=Screen2(self.screen,self.width,self.height)
Exemplo n.º 6
0
def get_food():
    """
    -------------------------------------------------------
    Creates a food object by requesting data from a user.
    Use: f = get_food()
    -------------------------------------------------------
    Returns:
        food - a completed food object (Food).
    -------------------------------------------------------
    """

    n = input("Enter Name:")
    
    print("Origin")
    
    # Create food object to use the origins function
    p = Food("Butter Chicken", 2 , True, 120)
    print(p.origins())
    
    o = int(input(":"))
    v = input("Vegetarian (Y/N):")
    if v == "Y":
        v = True
    
    if v == "N":
        v = False
        
    c = int(input("Calories:"))
    
    food = Food(n, o, v == True, c)

    return food
Exemplo n.º 7
0
    def instruction(self):
        self.elements = []
        self.text_menu = arcade.draw_text("Instruction",
                                          self.center,
                                          self.high,
                                          arcade.color.WHITE,
                                          30,
                                          align="center",
                                          anchor_x="center")

        icon_food = Food(0, self.center - 180, self.high - 50)
        icon_speed = Food(1, self.center - 180, self.high - 80)
        icon_slow = Food(2, self.center - 180, self.high - 110)
        icon_ghost_walk = Food(3, self.center - 180, self.high - 140)
        icon_color = Food(4, self.center - 180, self.high - 170)

        back_button = MenuButton("Close", self.center, self.high - 325, 15,
                                 self.setup)

        self.icons.append(icon_food)
        self.icons.append(icon_speed)
        self.icons.append(icon_slow)
        self.icons.append(icon_ghost_walk)
        self.icons.append(icon_color)

        self.elements.append(back_button)
        self.is_instruction = True
Exemplo n.º 8
0
def main():
    f1 = Food("not spring rolls", 1, False, 66)
    f2 = Food("spring rolls wrong", 2, True, 653)
    f3 = Food("good spring rolls", 1, True, 7)
    source = [f1, f2, f3]
    source2 = [6, 8, 2]
    list_test(source)
Exemplo n.º 9
0
def main():
    try:
        pygame.init()
        screen = pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption('Змейка')

        running = True

        board = Board(20, 15, 40)
        snake = Snake(board)
        # snake.set_self_onboard()

        food = Food(board)
        # food.set_self_onboard()

        board.add_food(food)
        board.add_snake(snake)

        fps = 6
        clock = pygame.time.Clock()

        if board.start_screen(screen, clock):
            while running:
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        running = False
                    elif event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_SPACE:  # пауза
                            print('main.py:"SPACE"')
                            board.pause_play()
                        elif event.scancode == pygame.KSCAN_R:  # перезапуск
                            food.restart()
                            snake.restart()
                            board.pause_play()
                        elif board.playing:
                            # управление стрелками
                            if event.key == pygame.K_UP:
                                snake.UP()
                                break
                            elif event.key == pygame.K_RIGHT:
                                snake.RIGHT()
                                break
                            elif event.key == pygame.K_DOWN:
                                snake.DOWN()
                                break
                            elif event.key == pygame.K_LEFT:
                                snake.LEFT()
                                break
                screen.fill((0, 0, 0))

                # food.set_self_onboard()
                if board.playing:
                    snake.next_frame(screen)
                board.render(screen)
                pygame.display.flip()
                clock.tick(fps)
    except Exception as e:
        print(e)
    pygame.quit()
Exemplo n.º 10
0
    def __init__(self):
        self.window = pygame.display.set_mode((500, 500))
        pygame.display.set_caption("Hacktoberfest Snake Game")
        self.fps = pygame.time.Clock()

        self.score = 0
        self.snake = Snake()
        self.food = Food()
Exemplo n.º 11
0
    def __init__(self, x, y):

        self.x = x
        self.y = y
        self.base_object = {}
        self.food_on_map = Food()
        self.material_on_map = Material()
        self.symbol = "X"
Exemplo n.º 12
0
def main():
    food = Food("grape", 3, True, 5)
    food1 = Food("chicken", 2, False, 67)
    food2 = Food("sushi", 3, True, 12)
    food3 = Food("water", 3, True, 0)
    foods = [food, food1, food2, food3]
    a = calories_by_origin(foods, 3)
    print(a)
Exemplo n.º 13
0
 def __init__(self):
     pygame.init()
     self.setting = Setting()
     self.screen = pygame.display.set_mode(
         (self.setting.WIDTH, self.setting.HIGH), 0, 32)
     self.food = Food(self)
     self.snake = Snake(self)
     self.message = Message(self)
     self.map = Map(self)
Exemplo n.º 14
0
def f_menu():
    print("---------------------- Food Menu ----------------------")
    print("   Name" + " " * 20 + "Price")
    index = 0
    for meal in food_list:
        item = Food(meal[0], meal[1], meal[2])
        item.food_menu(index)
        index += 1
    print("--------------------------------------------------------")
Exemplo n.º 15
0
 def place_food(self):
     x = randint(0, self.height - 1)
     y = randint(0, self.width - 1)
     food = Food(x, y)
     while food.position in self.snake.snakeBody:
         x = randint(0, self.height - 1)
         y = randint(0, self.width - 1)
         food = Food(x, y)
     return food
Exemplo n.º 16
0
def main():

    food = Food("grape", 3, True, 67)
    food1 = Food("chicken", 2, False, 67)
    food2 = Food("sushi", 3, True, 67)
    foods = [food, food1, food2]
    v = by_origin(foods, 3)
    for s in v:
        print(s)
Exemplo n.º 17
0
 def __init__(self):
     self.player = Player([400, 400])
     self.windowHeight = 768
     self.windowWidth = 1366
     self.screen = 0
     self.running = True
     self.nn = NeuralNetwork()
     self.food = Food([200, 200])
     self.countGeneration = 0
     self.score = 0
Exemplo n.º 18
0
 def __init__(self):
     pygame.init()
     self.status = 1
     self.screen = pygame.display
     self.surface = self.screen.set_mode((800, 600))
     self.snake = [Snake(200, 200, 'r')]
     self.fps = 100
     self.dir_change_location = {}
     self.food = Food()
     self.food.generate_food()
Exemplo n.º 19
0
def main():
    food = Food("grape", 3, True, 5)
    food1 = Food("chicken", 2, False, 67)
    food2 = Food("sushi", 3, True, 10)
    food3 = Food("water", 3, True, 0)
    foods = [food, food1, food2, food3]
    result = food_search(foods, -1, 0, True)

    for f in result:
        print(f)
Exemplo n.º 20
0
    def launch(self):
        self.snake=Snake()
        self.food=Food()
        pygame.init()
        screen_size=(self.W,self.H)
        screen=pygame.display.set_mode(screen_size)
        pygame.display.set_caption("Snake")
        clock=pygame.time.Clock()
        scores=0
        isdead=False

        while True:
            for event in pygame.event.get():
                if event.type==pygame.QUIT:
                    sys.exit()

                if event.type==pygame.KEYDOWN:
                    self.snake.change_direction(event.key)
                    if event.key==pygame.K_SPACE and isdead:
                        return self.launch()



            screen.fill((155,255,255))

            if not isdead:
                scores+=1
                self.snake.move()

            for rect in self.snake.body:
                pygame.draw.rect(screen,(20,220,39),rect,0)

            isdead=self.snake.isdead(self.W,self.H)
            if isdead:
                self.show_context(screen,(100,200),"YOU DEAD")

            if self.food.rect==self.snake.body[0]:
                scores+=50
                self.food.remove()
                self.snake.addnode()



            while True:
                self.food.set(self.W)
                if self.food.rect not in self.snake.body:
                    break

            pygame.draw.rect(screen,(136,0,21),self.food.rect,0)

            self.show_context(screen,(50,500),"SCORES:"+str(scores))

            pygame.display.update()
            clock.tick(5)
Exemplo n.º 21
0
 def __init__(self):
     # overhaul size of the screen by 16x16 pixels as 1 unit
     self.size = {'columns': 45, 'rows': 30}
     # time in ticks between each snake move
     self.snakepace = 6
     # snake state, alive = True, dead = False
     self.snakeState = True
     # game score
     self.score = 0
     # internal cool down to limit player movement
     self.cd = [9, 9, False]
     # screen size in pixels
     self.psize = {'width': 720, 'height': 480}
     # fps control
     self.clock = pygame.time.Clock()
     # time in ticks for internal control
     self.pace = 0
     # spawning snake and assigning to a variable
     self.snake = Snake(352, 240)
     # spawning food and assigning to a variable
     self.food = Food(
         randint(1, self.size['columns'] - 1) * 16,
         randint(1, self.size['rows'] - 1) * 16)
     # board
     self.rows = []
     self.screen = pygame.display.set_mode(
         (self.psize['width'], self.psize['height']))
     # rows
     for i in range(0, self.size['rows']):
         self.row = []
         # columns
         for j in range(0, self.size['columns']):
             if i == 0:
                 if j == 0:
                     self.row.append(LTCell(j * 16, i * 16))
                 elif j == self.size['columns'] - 1:
                     self.row.append(TRCell(j * 16, i * 16))
                 else:
                     self.row.append(TCell(j * 16, i * 16))
             elif i == self.size['rows'] - 1:
                 if j == 0:
                     self.row.append(BLCell(j * 16, i * 16))
                 elif j == self.size['columns'] - 1:
                     self.row.append(RBCell(j * 16, i * 16))
                 else:
                     self.row.append(BCell(j * 16, i * 16))
             elif i > 0 and j == 0:
                 self.row.append(LCell(j * 16, i * 16))
             elif i > 0 and j == self.size['columns'] - 1:
                 self.row.append(RCell(j * 16, i * 16))
             else:
                 self.row.append(Cell(j * 16, i * 16))
         self.rows.append(self.row)
Exemplo n.º 22
0
    def reset(self):
        self.move = Move()
        time.sleep(self.secs)

        self.buildGrid()

        self.move = Move()
        self.snake = Snake(self.width, self.height, self.border)
        self.food = Food(self.width, self.height, self.snake)
        self.score = 0

        self.reseting = True
Exemplo n.º 23
0
    def __init__(self,
                 numOfSnakes=Constants.numberOfSnakes,
                 gridSize=Constants.gridSize,
                 maxEpisodeLength=Constants.globalEpisodeLength):
        self.snakes = []
        for idx in range(numOfSnakes):
            self.snakes.append(Snake(idx))

        self.food = Food(Snake.snakeList)
        self.gameLength = maxEpisodeLength
        self.time_step = 0
        return
Exemplo n.º 24
0
def game_loop() -> None:

    game_over = False
    game_close = False

    while not game_close:

        while game_over and not game_close:
            surface.fill(BLACK)
            show_you_lost_screen()

            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    game_over = True
                    game_close = True
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_close = True
                        game_over = True
                    if event.key == pygame.K_c:
                        game_over = False

        snake = Snake(WIDTH, HEIGHT, snake_size)
        food = Food(WIDTH, HEIGHT, snake_size)
        score = 0
        while not game_over:

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    game_over = True
                    game_close = True
                if event.type == pygame.KEYDOWN:
                    snake.head_direction = event.key

            if snake.eat(food):
                food.generate(WIDTH, HEIGHT, snake_size)
                score += 1

            snake.move()

            if snake.died(WIDTH, HEIGHT):
                game_over = True

            surface.fill(BLACK)
            draw_snake(snake)
            draw_food(food)
            show_score(score)

            pygame.display.update()
            clock.tick(snake_speed)
Exemplo n.º 25
0
class Ground():
    def __init__(self, x, y):

        self.x = x
        self.y = y
        self.base_object = {}
        self.food_on_map = Food()
        self.material_on_map = Material()
        self.symbol = "X"

    def build_construction(self, building_class, fraction):  #budowanie
        """Buduje budynek, dodaje jego symbol i wartość do słownika i zwraca ten słownik."""

        self.building = building_class
        self.building.build(fraction)  #zbudowanie budynku
        self.building_dict = {}
        self.building = self.building.add_building(
            fraction)  #dodanie do słownika danych budynku
        return self.building

    def update_object_new(
            self):  #zaktualizowanie słownika na obszarze przy rysowaniu mapy
        """Metoda aktualizująca słownik pola o losowe wartości jedzenia i materiałów."""

        self.base_object.update(self.food_on_map.generate())
        self.base_object.update(self.material_on_map.generate())

    def update_object(
            self, obj):  #aktualizowanie oobszaru na mapie np. przy budowaniu
        """Metoda aktualizująca słownik o zadaną wartość."""

        self.base_object.update(obj)
Exemplo n.º 26
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        print("answer_price_food")
        food = str(tracker.get_slot('food'))
        if food is None:
            dispatcher.utter_message("Nhà hàng mình không có món kia bạn ạ")

        Max = SequenceMatcher(a=food, b="Lẩu dầu cay không vụn").ratio()

        for item in Menu():
            temp = SequenceMatcher(a=food, b=item.name).ratio()
            if temp >= Max:
                Max = temp
                max_food = Food(item.name, item.price, item.type, 0)

        if max_food.type == "beef":
            dispatcher.utter_message("Món " + max_food.name +
                                     " bên em đang bán có giá " +
                                     str(max_food.price) + "k/100g ạ")
        elif max_food.type == "special":
            dispatcher.utter_message(
                "Tiết mục " + max_food.name + " bên em đang bán có giá " +
                str(max_food.price) +
                "k bao gồm cả phần mì và nhân viên ra múa mì luôn ạ")
        elif max_food.type == "drink":
            dispatcher.utter_message("Dạ " + max_food.name +
                                     " bên em đang bán có giá " +
                                     str(max_food.price) + "k/chai ạ")
        else:
            dispatcher.utter_message("Món " + max_food.name +
                                     " bên em đang bán có giá " +
                                     str(max_food.price) + "k/suất ạ")

        return [SlotSet("food", None)]
Exemplo n.º 27
0
def buildLargeMenu(numItems, maxValue, maxCost):
    items = []
    for i in range(numItems):
        items.append(
            Food('num-' + str(i), random.randint(1, maxValue),
                 random.randint(1, maxCost)))
    return items
Exemplo n.º 28
0
    def loadWorld(self, worldFile):
        self.reset()
        self.main_gui.button_go["text"] = "Go =>"
        if self.charged > 0 and self.main_gui.is_modifying.get() == True:
            self.main_gui.on_modif_state_change()
        self.charged += 1

        with open(f"worlds/{worldFile}") as file:
            data = file.read()
            world_data = json.loads(data)
            try:
                for food in world_data['food']:
                    self.add_food(
                        Food(self.canvas, food['x'], food['y'], food['size']))

                for nest in world_data['nests']:
                    self.add_nest(
                        Nest(self, len(self.nests), nest['x'], nest['y'],
                             nest['species'], nest['size']))

                if (world_data["wall"]):
                    for wall in world_data["wall"]:
                        self.add_wall(wall[0], wall[1])

                for i, species in enumerate(world_data["species"]):
                    for trait, value in species.items():
                        self.species[i].update_trait(trait, value)
                        self.main_gui.update_species_entry(trait, value)

            except BaseException:
                pass
Exemplo n.º 29
0
def read_food(line):
    """
    -------------------------------------------------------
    Creates and returns a food object from a line of string data.
    Use: f = read_food(line)
    -------------------------------------------------------
    Parameters:
        line - a vertical bar-delimited line of food data in the format
          name|origin|is_vegetarian|calories (str)
    Returns:
        food - contains the data from line (Food)
    -------------------------------------------------------
    """

    line.strip()
    x = line.split("|")
    
    if x[2] == "True":
        x[2] = True
    if x[2] == "False":
        x[2] = False
        
    origin = int(x[1])
    
    food = Food(x[0], origin, x[2] , int(x[3]))

    return food
Exemplo n.º 30
0
def read_food(line):
    """
    -------------------------------------------------------
    Creates and returns a food object from a line of string data.
    Use: f = read_food(line)
    -------------------------------------------------------
    Parameters:
        line - a vertical bar-delimited line of food data in the format
          name|origin|is_vegetarian|calories (str)
    Returns:
        food - contains the data from line (Food)
    -------------------------------------------------------
    """

    l = line.split("|")
    name = l[0]
    ori = int(l[1])
    vegTemp = l[2]
    if vegTemp == "True":
        veg = True
    else:
        veg = False
    cal = int(l[3])
    food = Food(name, ori, veg, cal)

    return food
Exemplo n.º 31
0
	def __init__(self):
		# pygame initialization

		self.screen = pygame.display.set_mode((SCREEN_SIZE, SCREEN_SIZE))
		pygame.mouse.set_visible(0)

		self.background = pygame.Surface(self.screen.get_size())
		self.background = self.background.convert()
		self.background.fill((255, 255, 255))
		
		self.food = Food()
		self.food_sprite = pygame.sprite.RenderPlain(self.food) # create sprite group for the food

		self.seeker = Seeker()
		self.seeker_sprite = pygame.sprite.RenderPlain(self.seeker) # create sprite group for the seeker

		self._draw()

		# pybrain initialization
		self.action = [0.0, 0.0]
		
		self.reset()
Exemplo n.º 32
0
class ChemotaxisEnv(Environment):
	"""
	Experiment adapted from "Evolving Dynamical Neural Networks for Adaptive Behavior" (Beer & Gallagher, 1992)
	
	An seeker is enclosed in a square box with a food item inside.
	This food item emits a chemical signal whose intensity falls off
	as the inverse square of the distance from the food.
	The intensity of the chemical signal within the environment varies
	five orders of magnitude from the item to the far corners of the box, i.e. at a distance of root(2).
	We wish the seeker to find and remain in the vicinity of the food item,
	starting from arbitrary locations and orientations within the environment.

	To accomplish this task, the seeker is endowed with a circular body with a diameter of .01.
	The seeker possesses chemical sensors that can directly sense
	the intensity of the chemical signal at their location.
	These sensors are symmetrically placed about the center line of the body.
	In addition, the seeker has two effectors located on opposite sides of its body.
	These effectors can apply forces that move the body forward and rotate it.
	In the simplified physics of this environment,
	the velocity of movement is proportional to the force applied.

	State space (continuous):
		food		location of food item as a coordinate pair from (0,0) to (100,100)
		seeker.loc	location of the center of the seeker
		seeker.dir	angle of the seeker in radians from the positive x-axis, i.e. east=0
	Action space (continuous):
		l			output signal of the left effector neuron
		r			output signal of the right effector neuron
	"""
	
	def __init__(self):
		# pygame initialization

		self.screen = pygame.display.set_mode((SCREEN_SIZE, SCREEN_SIZE))
		pygame.mouse.set_visible(0)

		self.background = pygame.Surface(self.screen.get_size())
		self.background = self.background.convert()
		self.background.fill((255, 255, 255))
		
		self.food = Food()
		self.food_sprite = pygame.sprite.RenderPlain(self.food) # create sprite group for the food

		self.seeker = Seeker()
		self.seeker_sprite = pygame.sprite.RenderPlain(self.seeker) # create sprite group for the seeker

		self._draw()

		# pybrain initialization
		self.action = [0.0, 0.0]
		
		self.reset()

	def _draw(self):
		#self.seeker_sprite.update(self.background)
		self.screen.blit(self.background, (0, 0))
		self.food.update()
		self.food_sprite.draw(self.screen)
		self.seeker.update(self.screen) # we don't need to draw this here because we draw it with pymunk
		pygame.display.flip()

	def _calcDistance(self, loc1, loc2):
		""" Calculates the Euclidean distance between two coordinate pairs. """
		from math import sqrt
		return sqrt((loc2[0] - loc1[0]) ** 2 + (loc2[1] - loc1[1]) ** 2)

	def calcSignal(self, loc):
		""" Calculates the chemical signal at a specific location, which is
		the inverse square of the distance between the given location and the food. """

		dist = self._calcDistance(self.food.loc, loc)
		if dist == 0:
			return 1
		else:
			return 1/dist # why does changing the reward magnitude change the sensor-delta magnitude?

	def getSensors(self):
		""" the currently visible state of the world (the observation may be
			stochastic - repeated calls returning different values)

			:rtype: by default, this is assumed to be a numpy array of doubles
		"""
		# get sensor locations
		lx, ly, rx, ry = self.seeker.calcAbsoluteSensorPositions()

		# return the strength of the chemical signals at the seeker's left and right sensors
		return [ self.calcSignal(toPygame((lx, ly))), self.calcSignal(toPygame((rx, ry))) ]

	def performAction(self, action):
		""" perform an action on the world that changes its internal state (maybe
			stochastically).
			:key action: an action that should be executed in the Environment.
			:type action: by default, this is assumed to be a numpy array of doubles
			
			action[0] is the left motor/effector neuron output, action[1] is the right
		"""

		self.seeker.move_body(action[0], action[1])

		self.movement_tracker.append(toPygame(self.seeker.body.position))

		# redraw
		self._draw()

	def reset(self):
		""" Reinitializes the environment with the food in a random location
			and the seeker with a random direction in a random location.
		"""
		from random import random
		self.movement_tracker = []
		self.food.setLocation((random()*SCREEN_SIZE, random()*SCREEN_SIZE))
		self.seeker.reset()
Exemplo n.º 33
0
def main():
    #create display
    screen = pygame.display.set_mode((690, 601))
    screen.fill([156, 203, 250])

    clock = pygame.time.Clock()
    font = pygame.font.Font(None, 25)

    frameCount = 0
    frameRate = 10
    startTime = 90
    
    #tile map through which players will navigate
    fridgeMap = SpriteTileMap("maze.txt", "sprites.txt")

    #fPlayer navigates through the maze
    #sPlayer kills the mold, defends fPlayer
    fPlayer = Food()
    sPlayer = SprayBottle()

    #mold objects try to attack the food player
    mold1 = Mold('blue')
    mold2 = Mold('green')
    mold3 = Mold('blue')
    mold4 = Mold('green')
    mold5 = Mold('blue')
    mold6 = Mold('green')
    mold7 = Mold('blue')
    mold8 = Mold('green') 

    done = False
    
    #game loop 
    while not done:
        mouseX, mouseY = pygame.mouse.get_pos()

        for event in pygame.event.get():
            
            if event.type == pygame.QUIT:
                done = True                

            #arrow keys are assigned to the navigation movements
            #of fPlayer
            key = pygame.key.get_pressed()
            if key[pygame.K_RIGHT]:
                fPlayer.move("RIGHT", fridgeMap)
                
            elif key[pygame.K_LEFT]:
                fPlayer.move("LEFT", fridgeMap)

            elif key[pygame.K_UP]:
                fPlayer.move("UP", fridgeMap)

            elif key[pygame.K_DOWN]:
                fPlayer.move("DOWN", fridgeMap)
            
            #sPlayer moves with the mouse
            if event.type == pygame.MOUSEMOTION:
                sPlayer.move(mouseX, mouseY)
            if event.type == pygame.MOUSEBUTTONDOWN:
                mold1.decideNextState(sPlayer)
                mold2.decideNextState(sPlayer)
                mold3.decideNextState(sPlayer)
                mold4.decideNextState(sPlayer)
                mold5.decideNextState(sPlayer)
                mold6.decideNextState(sPlayer)

                print (isCollide(sPlayer,mold1))

        totalSeconds = startTime - (frameCount // frameRate)
        if totalSeconds < 0:
            totalSeconds = 0
        minutes = totalSeconds // 60
        seconds = totalSeconds % 60
        outputString = "Time left: {0:02}:{1:02}".format(minutes,seconds)

        text = font.render(outputString, True, (255,255,255))

        mold1.move()
        #mold2.move()
        #mold3.move()
        #mold4.move()
        #mold5.move()
        #mold6.move()

        frameCount += 1
        clock.tick(frameRate)
        
        pygame.display.flip()
        fridgeMap.drawMap(screen)
        screen.blit(fPlayer.getImage(), (fPlayer.getX(), fPlayer.getY()))
        screen.blit(mold1.getImage(), (mold1.getX(), mold1.getY()))
        screen.blit(mold2.getImage(), (mold2.getX(), mold2.getY()))
        screen.blit(mold3.getImage(), (mold3.getX(), mold3.getY()))
        screen.blit(mold4.getImage(), (mold4.getX(), mold4.getY()))
        screen.blit(mold5.getImage(), (mold5.getX(), mold5.getY()))
        screen.blit(mold6.getImage(), (mold6.getX(), mold6.getY()))
        screen.blit(sPlayer.getImage(), (sPlayer.getX(), sPlayer.getY()))
        pygame.draw.rect(screen, [250, 74, 47], [510, 10, 160, 40]) 
        screen.blit(text, [520, 23])
Exemplo n.º 34
0
def game(levels):
		
		global level 
		level = levels

		global foodlet
		global wormlet 

		foodlet = Food()
		prt1=Loc(250,250)
		wormlet = Worm([prt1])
		
		game = True
		
		while game == True:

			last = copy.deepcopy(wormlet.get(wormlet.length()-1))
	
			events = pygame.event.get()
			for event in events:
				if event.type == pygame.KEYDOWN:
					if event.key == pygame.K_LEFT:
						wormlet.setdir('left')
					
					elif event.key == pygame.K_RIGHT:
						wormlet.setdir('right')

					elif event.key == pygame.K_UP:
						wormlet.setdir('up')

					elif event.key == pygame.K_DOWN:
						wormlet.setdir('down')

					elif event.key == pygame.K_q:
						game = False

					elif event.key == pygame.K_p:
						a = pause()
						if a == 'menu':
							game = False

			
			wormlet.update() #advances worm in its direction
						
			first=wormlet.get(0)
			
			if foodlet.getlocation() == wormlet.getlocation():
				wormlet.add(last)
				foodlet.reset()
			while (level.checkloc(foodlet.getlocation()) == True or wormlet.checkloc(foodlet.getlocation()) == True):
				foodlet.reset()
							
			display()

			if (level.checkloc(first) == True):
				game = False
	
			for x in range (1, wormlet.length()):
				if first == wormlet.get(x):
					game = False
			
			window.blit(pygame.transform.smoothscale(screen,(ssize)),(0,0))
			pygame.display.flip()
			pygame.display.update()	
			if level.num == 2:
				pygame.time.wait(45)
			elif level.num == 1:
				pygame.time.wait(65)
			else:
				
				pygame.time.wait(80)
Exemplo n.º 35
0
from Food import Food
from Worm import Worm

w = 500
h = 500

screen = pygame.display.set_mode((w, h))

clock = pygame.time.Clock()

pygame.mixer.init()
chomp = pygame.mixer.Sound("chomp.wav")

score = 0
worm = Worm(screen)
food = Food(screen)
running = True
while running:

    screen.fill((0, 0, 0))
    worm.move()
    worm.draw()
    food.draw()

    if worm.crashed:
        running = False
    elif worm.x <= 0 or worm.x >= w - 1:
        running = False
    elif worm.y <= 0 or worm.y >= h - 1:
        running = False
    elif food.check(worm.x, worm.y):
Exemplo n.º 36
0
def gameLoop():
    global dirn, k, highscore, namehighscore
    pyExit = False
    pyOver = False
    #stop intro music and play in game music infinite loop
    intro_sound.stop()
    game_sound.play(-1)
    score = 0
    world_num = 0
    scorestr = "Score:0"
    # Initialize the game
    snake = Snake(200, 200, img)
    food = Food(int(width / 2), int(height / 2))
    blocks = worlds(width - 200, height, world_num)

    # Keeps track of the direction of the snake.
    dx, dy = 0, 0
    lossreason = ''

    while not pyExit:
        if pyOver == True:
            #play end music
            endgame_sound.play(-1)
        while pyOver:
            image = pygame.image.load(python_path)
            game_display.blit(image, (0, 0))

            message("Game Over! Press C to play Again, Q to Quit",
                    (255, 0, 0), -20)
            message(lossreason, (255, 0, 0), 30)
            # display score on game over
            message("Your" + scorestr, (255, 0, 0), 80)
            if totalscore > highscore:
                # message("Highscore!!!",(255,0,0),120)
                # write new highscore
                highscorefile = open('highscore.txt', 'wt')
                highscorefile.write(str(totalscore) + "\n")

                # name window
                def namewrite():
                    highscorefile.write(v.get())
                    scorewindow.destroy()

                scorewindow = Tk()
                scorewindow.geometry('300x100')
                frame = Frame(scorewindow, width=100, height=100)
                frame.pack()
                scorewindow.title("congratulations")

                Label(frame, text='you\'ve made highscore!!!!').pack(side='top')
                v = StringVar()
                v.set("type your name")
                textbox = Entry(frame, textvariable=v)
                textbox.pack(side='top')

                okbutton = Button(frame, text="ok", fg="black",
                                  bg="white", command=namewrite)
                okbutton.pack(side='bottom')

                scorewindow.mainloop()
                highscorefile.close()

                # incase user wants to countinue after creating highscore
                # to read his new score
                highscorefile = open('highscore.txt', 'rt')
                highscore = highscorefile.readline()
                highscore = int(highscore)
                namehighscore = highscorefile.readline()
                highscorefile.close()

            else:
                message("Highscore by " + namehighscore +
                        ":" + str(highscore), (255, 0, 0), 120)
            pygame.display.update()

            for event in pygame.event.get():
                keyp = action()
                if keyp != None or event.type == pygame.KEYDOWN:
                    try:
                        if keyp == 'q' or event.key == pygame.K_q:
                            pyExit = True
                            pyOver = False
                    except:
                        blank = []  # bypass the exception
                    try:
                        if keyp == 'c' or event.key == pygame.K_c:
                            #stop endgame music
                            endgame_sound.stop()
                            gameLoop()
                    except:
                        blank = []  # bypass the exception
                        
        """ Events """
        #the conditions are modified to work with the buttons
        for event in pygame.event.get():
            keyp = action()
            # blank is not used anywhere
            # it is just used to jump the exception
            if event.type == pygame.QUIT:
                pyExit = True
            if event.type == pygame.KEYDOWN or keyp != None:
                try:
                    if keyp == 'lt' or event.key == pygame.K_LEFT and dirn != "right":
                        dirn = "left"
                        dx = -1
                        dy = 0
                except:
                    blank = []
                try:
                    if keyp == 'rt' or event.key == pygame.K_RIGHT and dirn != "left":
                        dirn = "right"
                        dx = 1
                        dy = 0
                except:
                    blank = []
                try:
                    if keyp == 'up' or event.key == pygame.K_UP and dirn != "down":
                        dirn = "up"
                        dy = -1
                        dx = 0
                except:
                    blank = []
                try:
                    if keyp == 'dn' or event.key == pygame.K_DOWN and dirn != "up":
                        dirn = "down"
                        dy = 1
                        dx = 0
                except:
                    blank = []
                try:
                    if keyp == 'p' or event.key == pygame.K_p:
                        pause(scorestr)
                except:
                    blank = []
                try:
                    if keyp == 'q' or event.key == pygame.K_q:
                        pygame.quit()
                        quit(0)
                except:
                    blank = []

        # level changer value
        if score > 10:
            score = 0
            world_num += 1
            blocks = worlds(width - 200, height, world_num)
            food.x, food.y = int(width / 2), int(height / 2)

        # Engage boost of pressing shift
        keyp=action()
        keyPresses = pygame.key.get_pressed()
        boost_speed = keyPresses[pygame.K_LSHIFT] or keyPresses[pygame.K_RSHIFT] or keyp=='st'

        # if boost_speed is true it will move 2 blocks in one gameloop
        # else it will just move one block
        iterations = [1]
        if boost_speed == 1:
            iterations.append(2)

        for i in iterations:
            """ Update snake """
            snake.move(dx, dy, 10)
            snake.check_boundary(width, height)

            snake_rect = snake.get_rect()
            food_rect = food.get_rect()

            """ Snake-Snake collision """
            if snake.ate_itself():
                #stop game sound
                game_sound.stop()
                pyOver = True
                lossreason = 'Oooops You Hit YOURSELF'
                

            """ Snake-Block collision """
            for block in blocks:
                block_rect = block.get_rect()
                if block_rect.colliderect(snake_rect):
                    #stop game sound
                    game_sound.stop()
                    pyOver = True
                    lossreason = 'Ooops You Hit a BLOCKER'
                    
            """ Snake-Food collision """
            # if snake collides with food, increase its length.
            if food_rect.colliderect(snake_rect):
                score += 1
                snake.increment_length()

                sound = pygame.mixer.Sound(point_path)
                sound.set_volume(0.3)
                sound.play()

                # generate food at random x, y.
                food.generate_food(width, height)

                # try generating the food at a position where blocks are not present.
                while food_collides_block(food.get_rect(), blocks):
                    food.generate_food(width - food.size, height - food.size)

            """ Draw """
            game_display.fill((255, 255, 255))
            showButton()

            # draw the food and snake.
            snake.draw(game_display, dirn, (0, 155, 0))
            food.draw(game_display, (0, 255, 0))

        # draw the blocks.
        for block in blocks:
            block.draw(game_display, (255, 0, 0))
        # count and display score on screen
        totalscore = total(score, world_num)
        scorestr = 'Score: ' + str(totalscore)
        font = pygame.font.SysFont(None, 30)
        text = font.render(scorestr, True, (0, 0, 255))
        game_display.blit(text, (0, 0, 20, 20))

        pygame.display.update()
        clock.tick(FPS)

    pygame.quit()
    quit()