Example #1
0
 def __init__(self):
     pygame.init()
     pygame.mouse.set_visible(False)
     self.main_clock = pygame.time.Clock()
     window.set_caption('snake game')
     self.surface = window.set_mode(surface_size)
     self.snake = Snake(self.surface)
     self.food = Food(self.surface, self.snake.head)
     self.monster = Monster(self.surface, self.snake.head)
     self.food.on_collide_event = self.snake.grow_up
     self.eventHandler = EventHandler(pygame.KEYDOWN)
     self.add_events()
Example #2
0
 def delete(self, food_id):
     food = Food.objects().with_id(food_id)
     food.delete()
     if food != None:
         return {"message": "delete successful"}
     else:
         return {"message": "not found food"}
Example #3
0
class SnakeGame:
    def __init__(self):
        pygame.init()
        pygame.mouse.set_visible(False)
        self.main_clock = pygame.time.Clock()
        window.set_caption('snake game')
        self.surface = window.set_mode(surface_size)
        self.snake = Snake(self.surface)
        self.food = Food(self.surface, self.snake.head)
        self.monster = Monster(self.surface, self.snake.head)
        self.food.on_collide_event = self.snake.grow_up
        self.eventHandler = EventHandler(pygame.KEYDOWN)
        self.add_events()

    def add_events(self):
        # exit.
        self.eventHandler.add_event(QUIT, lambda event: exit(0))
        self.eventHandler.add_subevent(KEYDOWN, K_q, exit)
        # movement.
        self.eventHandler.add_subevent(KEYDOWN, K_UP, self.snake.go_up)
        self.eventHandler.add_subevent(KEYDOWN, K_RIGHT, self.snake.go_right)
        self.eventHandler.add_subevent(KEYDOWN, K_DOWN, self.snake.go_down)
        self.eventHandler.add_subevent(KEYDOWN, K_LEFT, self.snake.go_left)
        self.eventHandler.add_subevent(KEYDOWN, K_LSHIFT, self.snake.speed_up)
        self.eventHandler.add_subevent(KEYDOWN, K_SPACE, self.snake.shrink)
        # self.eventHandler.add_subevent(KEYDOWN, pygame.K_a, self.snake.grow_down_head)

    def update_screen(self):
        self.surface.fill(white)
        pygame.draw.rect(self.surface, black,
                         (0, 0, surface_size[0], surface_size[1]),
                         stroke_width)
        # draw borders.
        self.food.draw()
        self.snake.play()
        self.monster.play()
        self.food.check_collision()
        for i in range(self.food.fixed_counter):
            pygame.draw.rect(self.surface, cp[i % 4], borders_position[i],
                             stroke_width)
        pygame.display.flip()

    def start(self):
        while True:
            self.eventHandler.check_events()
            self.update_screen()
            self.main_clock.tick(50)
Example #4
0
 def put(self, food_id):
     parser = reqparse.RequestParser()
     parser.add_argument(name="rate", type=float, location="json")
     body = parser.parse_args()
     # name = body.name
     # url = body.url
     # coint_old = body.coint_old
     # coint_new = body.coint_new
     # cout_rate = body.cout_rate
     rate_res = body.rate
     food = Food.objects().with_id(food_id)
     cout_rate = food.cout_rate
     rate = food.rate
     rate_new = (cout_rate * rate + rate_res) / (cout_rate + 1)
     food.update(cout_rate=cout_rate + 1, rate=rate_new)
     add_food = Food.objects().with_id(food_id)
     return mlab.item2json(add_food)
Example #5
0
 def post(self):
     parser = reqparse.RequestParser()
     parser.add_argument(name="name", type=str, location="json")
     parser.add_argument(name="url", type=str, location="json")
     parser.add_argument(name="coint_old", type=str, location="json")
     parser.add_argument(name="coint_new", type=str, location="json")
     parser.add_argument(name="cout_rate", type=int, location="json")
     parser.add_argument(name="rate", type=float, location="json")
     body = parser.parse_args()
     name = body.name
     url = body.url
     coint_old = body.coint_old
     coint_new = body.coint_new
     cout_rate = body.cout_rate
     rate = body.rate
     food = Food(name=name,
                 url=url,
                 coint_new=coint_new,
                 coint_old=coint_old,
                 cout_rate=cout_rate,
                 rate=rate)
     food.save()
     add_food = Food.objects().with_id(food.id)
     return mlab.item2json(add_food)
 def post(self, id):
     parser = reqparse.RequestParser()
     parser.add_argument(name="id_user", type=str, location="json")
     parser.add_argument(name="message", type=str, location="json")
     body = parser.parse_args()
     id_user = body["id_user"]
     message = body["message"]
     print(id_user)
     print(message)
     food = Food.objects().with_id(id)
     user = User.objects().with_id(id_user)
     date = datetime.datetime.utcnow() + datetime.timedelta(hours=7)
     comment = Comment(user=user,
                       message=message,
                       date=str(date),
                       food=food)
     comment.save()
     comment_add = Comment.objects().with_id(comment.id)
     return comment_add.get_json(), 200
Example #7
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument(name="items", type=list, location="json")
        parser.add_argument(name="address", type=str, location="json")
        parser.add_argument(name="phone_number", type=str, location="json")
        parser.add_argument(name="user", type=str, location="json")
        parser.add_argument(name="code", type=str, location="json")
        parser.add_argument(name="name", type=str, location="json")
        parser.add_argument(name="id", type=str, location="json")
        parser.add_argument(name="count", type=int, location="json")
        body = parser.parse_args()
        items = body["items"]
        date = datetime.datetime.today().strftime('%d-%m-%Y')
        address = body.address
        phone_number = body.phone_number
        user_id = body.user
        name = body.name
        code = body["code"]
        if items is None or date is None or address is None or phone_number is None or user_id is None:
            return {"message": "Thiếu trường "}, 400

        if len(str(phone_number)) > 11 or len(str(phone_number)) < 10:
            return {"message": "Số điện thoại cc gì! sdt 10 or 11 số!"}, 402
        try:
            sdt = float(phone_number)
        except:
            return {"message": "Số điện thoại lol gì mà có chữ?"}, 401
        API_KEY = "AIzaSyCEB4QVng3uFEQ-SwxfwOWAG4H3sr7Mfi8"
        url_request = "https://maps.googleapis.com/maps/api/distancematrix/json?origins={0}&destinations={1}&mode=driving&language=vi-VN&key={2}".format(
            "301 Trường Chinh,Hà nội",
            str(address) + " Hà Nội", API_KEY)
        ship_spend = 0
        try:
            req = requests.get(url_request)
            json_data = json.loads(req.content)
            list_add = json_data["rows"]
            elements = list_add[0]["elements"]
            km = elements[0]["distance"]["text"]
            txt = str(km).split(" ")
            distance = txt[0].replace(",", ".")
            ship_spend = float(distance) * 3000
        except:
            ship_spend = -1

        order_items = []
        spend = 0
        for i in range(0, len(items)):
            count = items[i]["count"]
            food_id = items[i]["id"]
            print("count:", items[i]["count"], ";id:", items[i]["id"])

            try:
                sl = int(count)
                if sl < 1:
                    return {"message": "Số lượng >0 ok?"}, 401
            except:
                return {"message": "count là số int ok?"}, 401
            food = Food.objects().with_id(food_id)
            single_order = SingleOrder(count=count, food=food)
            order_items.append(single_order)
            spend += (float(food["coint_new"]) * int(count))

        if spend == 0:
            return {"message": "Đặt hàng cc gì mà giá bằng 0?"}, 401
        try:
            user = User.objects().with_id(user_id)
            user.update(address=address, phone_number=phone_number, name=name)
        except:
            return {"message": "Đm gửi cái user id mà data mlab lưu ấy"}, 401
        oder = Oder()
        code = str(code).lower()
        gift = GiftCode.objects(code=code).first()
        try:
            spend_min = gift.spend_min
        except:
            spend_min = -1
        if (spend > 0 and (spend >= spend_min and spend_min != -1)):
            use_number = gift["use_number"]
            use_number -= 1
            if use_number == 0:
                gift.delete()
            else:
                gift.update(set__use_number=use_number)
            oder = Oder(items=order_items,
                        date=date,
                        address=address,
                        phone_number=phone_number,
                        user=User.objects().with_id(user_id),
                        is_Succues=False,
                        spend=spend + ship_spend - gift.price,
                        ship_money=ship_spend,
                        code_price=gift.price,
                        is_Received=False,
                        is_Shipping=False)
        else:
            oder = Oder(items=order_items,
                        date=date,
                        address=address,
                        phone_number=phone_number,
                        user=User.objects().with_id(user_id),
                        is_Succues=False,
                        spend=spend + ship_spend,
                        ship_money=ship_spend,
                        code_price=0,
                        is_Received=False,
                        is_Shipping=False)
        if oder in Oder.objects():
            return {"message": "Đăth lằm đặt lốn!"}, 404
        oder.save()
        add_oder = Oder.objects().with_id(oder.id)
        #apikey = "AAAAhgLLpbs:APA91bGLuFvqDwvWs7L7RNnMHwus426M1fi5oLSP2azB5jOhB2jW2i91uIZF7jrECoyUYk-c-h5yyp4DY0oKFhEgg3S6o7fsv7dc-M5aBDdwxbYaWgXVn3HFEqImNYEm6xfyeMqb4lAR"
        #push_service = FCMNotification(api_key=apikey)
        #push_service.notify_topic_subscribers(topic_name="admin", message_body="Có đơn hàng mới",
        #                                      message_title="Kiểm tra ngay")
        return mlab.item2json(add_oder), 200
Example #8
0
 def get_json(self):
     return {
         "food": Food.objects().with_id(self.food.id).get_json(),
         "count": self.count
     }
Example #9
0
 def get(selfk, food_id):
     food = Food.objects().with_id(food_id)
     return mlab.item2json(food)
Example #10
0
 def get(self):
     food = Food.objects()
     return mlab.list2json(food)
Example #11
0
 def get(self, id):
     food = Food.objects().with_id(id)
     comments = Comment.objects(food=food)
     return [comment.get_json() for comment in comments], 200
Example #12
0
 def get(self):
     food = Food.objects()
     return mlab.item2json(food)
Example #13
0
def play_game(genomes, config):
    global screen
    global best_fitness
    global pop

    dx = 1
    dy = 0
    best_foods = 0
    generation_number = 0
    best_instance = None
    genome_number = 0

    # Create the field, the snake and a bit of food
    theField = Field(screen, gu.field_width, gu.field_height, gu.blockSize,
                     gu.field_color)

    # Outer loop is for all the genomes
    for genome_id, genome in genomes:
        net = neat.nn.FeedForwardNetwork.create(genome, config)
        dx = 1
        dy = 0
        score = 0.0
        calories = 100

        # create food at random position
        theFood = Food(theField)

        # Snake starts from a fixed location
        theSnake = Snake(theField,
                         gu.snake_color,
                         5,
                         x=int(gu.field_width / 2),
                         y=int(gu.field_height / 2))

        # initialize an empty set for loop detection
        loopPoints = set()
        food_count = 0  # keep counting of food

        while True:
            event = pygame.event.wait()

            # Window is going to be closed
            if event.type == pygame.QUIT:
                print("Quitting the game now ...")

                ## save the population
                gu.save_object(pop, gu.pop_data_file)
                pygame.quit()
                sys.exit()

            # Every TIME_DURATION there will be a SNAKE_EVENT to move the snake
            if event.type == SNAKE_EVENT:
                # initially dx = 1 and dy = 0 i.e. moving to the right on X axis

                # current distance from the food
                hx, hy = theSnake.position()
                fx, fy = theFood.position()
                dist_before_move = math.sqrt((hx - fx)**2 + (hy - fy)**2)

                # find out current input points (total 9 for now)
                inputs = gu.get_inputs(theSnake.body[0], theFood.position(),
                                       (gu.field_width, gu.field_height),
                                       (dx, dy))

                # it will generate 3 outputs (continue straight, left or right)
                outputs = net.activate(inputs)

                # find index of maximum value and determine the direction (0 - straight, 1 - left or 2 - right)
                direction = outputs.index(max(outputs))

                # decide the movement direction based on the outcome
                if direction == 1:  # turn left
                    (dx, dy) = gu.left((dx, dy))
                elif direction == 2:  # turn right
                    (dx, dy) = gu.right((dx, dy))
                else:  # keep going straight (direction = 0)
                    # dx and dy values will remain same
                    pass

                # because of movement calories will burn
                calories -= 1

                # move the snake now, also check if move is invalid or calories are exausted
                # if not theSnake.move(dx, dy) or calories <= 0:
                if (theSnake.move(dx, dy) == False) or (theSnake.body[0]
                                                        in loopPoints):
                    # too bad snake died
                    # genome.fitness = 0
                    loopPoints = set()
                    break

                # Reward the snake for being alive
                score += gu.ALIVE_SCORE

                # punish for the loop
                # if theSnake.body[0] in loopPoints:
                #    score -= gu.LOOP_SCORE

                # keep tracking head positon till next food grab
                loopPoints.add(theSnake.body[0])

                # distance from the food after the move
                hx, hy = theSnake.position()
                dist_after_move = math.sqrt((hx - fx)**2 + (hy - fy)**2)

                # adjust the score
                if (hx, hy) == (fx, fy):
                    # if snake grabs the food
                    food_count += 1
                    score += gu.FOOD_SCORE
                    calories += gu.FOOD_CALORIES  # found food, got calories
                    theSnake.grow()  # grow by one length

                    # Make new food now
                    theFood = Food(theField)

                    # Also reset loopPoints
                    loopPoints = set()
                elif dist_after_move > dist_before_move:
                    score -= gu.FAR_SCORE
                elif dist_after_move < dist_before_move:
                    score += gu.NEAR_SCORE
                else:
                    # place holder for something else
                    score += 0
            # end of SNAKE_EVENT

            # Render snake and food
            theField.draw()
            theFood.draw()
            theSnake.draw()
            pygame.display.update()
            pygame.time.wait(gu.renderdelay)
        # end of while loop

        # while loop is done for the current genome
        for i in range(0, 2):
            theField.draw()
            theFood.draw()
            theSnake.draw(damage=(i % 2 == 0))
            pygame.display.update()

        # Tell about the fitness
        genome.fitness = score / 100

        # Keep saving best instance
        if not best_instance or genome.fitness > best_fitness:
            best_instance = {
                'num_generation': generation_number,
                'fitness': genome.fitness,
                'score': score,
                'genome': genome,
                'net': net,
            }

        best_foods = max(best_foods, food_count)
        best_fitness = max(best_fitness, genome.fitness)
        # if gu.debug_on:
        roudn_places = 5
        print(f"Generation {generation_number} \t" + \
              f"Genome {genome_number} \t" + \
              f"Foods {food_count} \t" + \
              f"BF {best_foods} \t" + \
              f"Fitness {round(genome.fitness, roudn_places)}  \t" + \
              f"Best fitness {round(best_fitness, roudn_places)}  \t" + \
              f"Score {round(score, roudn_places)}")
        genome_number += 1
    # end of for loop, all genomes are done

    # Save end results
    gu.save_best_generation_instance(best_instance)
    generation_number += 1
    if generation_number % 20 == 0:
        gu.save_object(pop, gu.pop_data_file)
        print("Exporting population")
        # export population
        # gu.save_object(pop,gu.pop_data_file)
        # export population

    global list_best_fitness
    global fig
    list_best_fitness.append(best_fitness)
    line_best_fitness.set_ydata(np.array(list_best_fitness))
    line_best_fitness.set_xdata(list(range(len(list_best_fitness))))
    plt.xlim(0, len(list_best_fitness) - 1)
    plt.ylim(0, max(list_best_fitness) + 0.5)
    fig.canvas.draw()
    fig.canvas.flush_events()