コード例 #1
0
ファイル: main.py プロジェクト: dogauysal/Snake-Pygame
def gameStart():

    gv.INTRO = False
    gv.DONE = False
    snake = Snake(0)
    food = Food()

    while not gv.DONE:

        clock.tick(gv.SELECTED_LEVEL[1])

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gv.DONE = True
                pygame.quit()
                os._exit(1)
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    snake.switchDirection(Directions.RIGHT)
                elif event.key == pygame.K_LEFT:
                    snake.switchDirection(Directions.LEFT)
                elif event.key == pygame.K_UP:
                    snake.switchDirection(Directions.UP)
                elif event.key == pygame.K_DOWN:
                    snake.switchDirection(Directions.DOWN)

        if snake.move(snake.direction) != False:
            #Game
            gameSurface.fill((0, 0, 0))
            CheckSnakeFoodCollision(snake, food)
            snake.drawSnake(gameSurface)
            food.drawFood(gameSurface)
            screen.blit(gameSurface, (0, gv.TEXT_AREA_HEIGHT))

            pygame.draw.line(screen, Colors.WHITE, (0, gv.TEXT_AREA_HEIGHT),
                             (gv.SURFACE_WIDTH, gv.TEXT_AREA_HEIGHT), 2)

            # Text
            LEVEL_TEXT = FONT.render("Level " + str(gv.SELECTED_LEVEL[0]),
                                     True, Colors.WHITE)
            textSurface.fill(Colors.BLACK)
            SCORE_TEXT = FONT.render(str(snake.score), True, Colors.WHITE)
            textSurface.blit(LEVEL_TEXT, (50, 10))
            textSurface.blit(GAME_TEXT, (gv.SURFACE_WIDTH / 2 - 50, 10))
            textSurface.blit(SCORE_TEXT, (gv.SURFACE_WIDTH - 50, 10))
            screen.blit(textSurface, (0, 0))

            pygame.display.flip()
            pygame.display.update()

        else:
            gv.LAST_SCORE = snake.score
            gameOver()
コード例 #2
0
ファイル: gui.py プロジェクト: milimi974/OC_Projet_5
    def __init__(self, master):
        """ Class constructor
        Parameters:
        master -- object tkinter
        """
        super().__init__(master)

        # Add title -> windows
        self.master.title(self.title)

        # Set background color
        self.master['bg'] = 'white'

        # init Food object
        self.food = Food()

        # init User object
        self.user = User()

        # init Category object
        self.category = Category()

        # var categories
        self.category_ids = []

        # var foods
        self.food_data = []

        # var current category index
        self.current_category_idx = None

        # var current food index
        self.current_food_idx = None

        # var current food index
        self.aliment = None

        # Add element in windows
        self.category_list = None
        self.status_bar = None
        self.input_category = None
        self.product_list = None
        self.button_next_page = None
        self.button_before_page = None
        self.description_box = None
        self.button_save_food = None

        # construct window
        self.build_window()
        self.button_before_page.pack(side=tk.LEFT)
        self.button_next_page.pack(side=tk.LEFT)
コード例 #3
0
ファイル: update.py プロジェクト: milimi974/OC_Projet_5
    def __make_food(row):
        """ Method create an object food

        Keyword arguments:
        row -- list of food fields value

        """
        # Make time to database format
        created = datetime.datetime.fromtimestamp(int(
            row['created_t'])).strftime('%Y-%m-%d %H:%M:%S')
        updated = datetime.datetime.fromtimestamp(int(
            row['last_modified_t'])).strftime('%Y-%m-%d %H:%M:%S')

        # Arguments for instantiate Food
        args = {
            'PK_id': 0,
            'code': row['code'],
            'link': row['url'],
            'name': row['product_name'],
            'uri': row['product_name'],
            'description': row['ingredients_text'],
            'level': row['nutrition_grade_fr'],
            'created': created,
            'modified': updated,
            'shops': row['stores'],
            'categories': row['categories_fr'],
        }
        return Food(args)
コード例 #4
0
ファイル: update.py プロジェクト: milimi974/OC_Projet_5
    def __create_foods(foods):
        """ Method create bulk food

        Keyword arguments:
        foods -- list of food object

        """

        # Get foods from db with food list name
        codes = []
        for el in foods:
            # Add name of food into the list for search in db
            codes.append(el.code)

        db_data = (Food()).search_by(('code IN', codes))

        # Compare Db_Food with Csv_Food
        add_list = []
        if db_data:
            for food in foods:
                found = False
                for db_food in db_data:
                    if food.code == db_food.code:
                        # If exist compare for update
                        Update.__compare(food, db_food)
                        found = True
                        break
                # If new add to list for save
                if not found:
                    add_list.append(food)
        else:
            add_list = foods

        # save all new data
        if add_list:
            (Food()).bulk(add_list, False)
コード例 #5
0
ファイル: Game.py プロジェクト: MatWich/Pac-man
    def what_to_create(self, tile, row, col):
        if tile == 'P':
            self.player = Player(self, col, row)
        if tile == 'W':
            Wall(self, col, row)

        if tile == '1':
            Food(self, col, row)

        if tile == 'G':
            Ghost(self, col, row)

        if tile == '2':
            PowerUp(self, col, row)
        if tile == '3':
            CrossRoad(self, col, row)
            Ghost(self, col, row)
コード例 #6
0
ファイル: User.py プロジェクト: milimi974/OC_Projet_5
    def find_user_food(self, user_id):
        """ return list of user food saved

        Method arguments:
        user_id -- int

        """
        args = {
            'where': [('User_has_Foods.FK_user_id =', int(user_id))],
            'on': [
                ('Foods.PK_id =', 'User_has_Foods.FK_food_id'),
            ]
        }
        # get foods
        foods = (Food()).findjoin('User_has_Foods', args)
        return {
            'next_page': 0,
            'before_page': 0,
            'current_page': 1,
            'total': len(foods),
            'response': foods
        }
コード例 #7
0
    # Read foods data fom ext file
    f = open(foods_file_path, "r")
    lines = f.read().splitlines()

    # Each food has 5 attribute, so divide all lines by 5
    count = 0
    # foods count
    bc = 0
    # bfast count
    lc = 0
    # lunch count
    dc = 0
    # dinner count
    for y in range(0, int(len(lines) / 5)):
        y *= 5
        foods.append(Food(lines[y], lines[y + 1], lines[y + 2], lines[y + 3]))

        #Grouping of type of meals, into specific array
        lastChar = foods[count].meal_type[len(foods[count].meal_type) - 1]
        if y / 5 == int(len(lines) / 5) - 1:  # Prevent invalid next char
            nxtLastChar = "9"
        else:
            nxtLastChar = lines[y + 5][len(lines[y + 5]) - 1]

        if "breakfast" in foods[count].meal_type:
            breakfast[int(lastChar) - 1][bc] = count
            if int(nxtLastChar) > int(
                    lastChar
            ):  # Reset bcount for nxtchar != char(different set), else inc bc by 1
                bc = 0
            else:
コード例 #8
0
ファイル: gui.py プロジェクト: milimi974/OC_Projet_5
class Gui(tk.Frame):
    """ Class manage gui inherit tk module frame """

    # Class attributes
    config = {
        'max_entries':
        250,
        'csv_uri':
        'http://world.openfoodfacts.org/data/fr.openfoodfacts.org.products.csv'
    }

    # windows title -- str
    title = "Pure Beurre"

    def __init__(self, master):
        """ Class constructor
        Parameters:
        master -- object tkinter
        """
        super().__init__(master)

        # Add title -> windows
        self.master.title(self.title)

        # Set background color
        self.master['bg'] = 'white'

        # init Food object
        self.food = Food()

        # init User object
        self.user = User()

        # init Category object
        self.category = Category()

        # var categories
        self.category_ids = []

        # var foods
        self.food_data = []

        # var current category index
        self.current_category_idx = None

        # var current food index
        self.current_food_idx = None

        # var current food index
        self.aliment = None

        # Add element in windows
        self.category_list = None
        self.status_bar = None
        self.input_category = None
        self.product_list = None
        self.button_next_page = None
        self.button_before_page = None
        self.description_box = None
        self.button_save_food = None

        # construct window
        self.build_window()
        self.button_before_page.pack(side=tk.LEFT)
        self.button_next_page.pack(side=tk.LEFT)

    def run(self):
        """ Display windows """
        # Start event loop
        self.master.mainloop()

    def build_window(self):
        # main Paned
        main_paned = tk.PanedWindow(self.master, orient=tk.VERTICAL)

        # title
        title = tk.Label(main_paned,
                         text='Open Food Facts',
                         font='system 24 bold',
                         bg="white")
        main_paned.add(title)

        # container
        container_paned = tk.PanedWindow(main_paned, orient=tk.HORIZONTAL)
        container_paned.pack(expand="yes")

        ## left container
        container_left = tk.PanedWindow(container_paned, orient=tk.VERTICAL)
        container_left.pack(expand="yes")
        self.build_left_element(container_left)
        container_paned.add(container_left)

        ## right container
        container_right = tk.PanedWindow(container_paned, orient=tk.VERTICAL)
        container_right.pack(expand="yes")
        self.build_right_element(container_right)
        container_paned.add(container_right)

        main_paned.add(container_paned)

        # status bar
        self.status_bar = tk.Label(main_paned,
                                   text='Waiting ...',
                                   bd=1,
                                   relief=tk.SUNKEN,
                                   anchor=tk.W)
        self.status_bar.pack(fill='x')
        main_paned.add(self.status_bar)

        # Display
        main_paned.pack(fill="both", expand="yes")

    def build_left_element(self, container_paned):
        """ build element on left side """
        # Found User Food
        label_frame_my = tk.LabelFrame(container_paned,
                                       text="Afficher la sauvegarde",
                                       padx=15,
                                       pady=15)
        label_frame_my.pack(fill="both", expand="yes")
        button_my_foods = tk.Button(label_frame_my,
                                    text='Retrouver mes aliments substitués',
                                    command=self.display_my_food_list)
        button_my_foods.pack()
        container_paned.add(label_frame_my)

        # Search category
        label_frame_search = tk.LabelFrame(container_paned,
                                           text="Rechercher une catégorie",
                                           padx=15,
                                           pady=15)
        label_frame_search.pack(fill="both", expand="yes")
        self.input_category = tk.Entry(label_frame_search)
        self.input_category.pack(side=tk.LEFT)
        button_search_category = tk.Button(label_frame_search,
                                           text='rechercher',
                                           command=self.display_food_category)
        button_search_category.pack(side=tk.LEFT)
        container_paned.add(label_frame_search)

        # Categories list
        label_frame_category = tk.LabelFrame(container_paned,
                                             text="Liste de catégories",
                                             padx=15,
                                             pady=15)
        label_frame_category.pack(fill="both", expand="yes")

        self.category_list = tk.Listbox(label_frame_category)
        self.category_list.pack(fill="both", expand="yes")
        self.category_list.bind('<<ListboxSelect>>',
                                self.bind_category_selected)
        container_paned.add(label_frame_category)

    def build_right_element(self, container_paned):
        """ build element in right side """
        # foods list
        label_frame_foods = tk.LabelFrame(
            container_paned,
            text="Liste des aliments d'une categorie",
            padx=15,
            pady=15)
        label_frame_foods.pack(fill="both", expand="yes")

        self.product_list = tk.Listbox(label_frame_foods)
        self.product_list.pack(fill="both", expand="yes")
        self.product_list.bind('<<ListboxSelect>>', self.bind_food_selected)
        self.button_before_page = tk.Button(label_frame_foods,
                                            text='Précedente',
                                            command=self.display_before_page,
                                            state=tk.DISABLED)
        self.button_before_page.pack(side=tk.LEFT)
        self.button_next_page = tk.Button(label_frame_foods,
                                          text='Suivante',
                                          command=self.display_next_page,
                                          state=tk.DISABLED)
        self.button_next_page.pack(side=tk.LEFT)

        container_paned.add(label_frame_foods)

        # description
        label_frame_description = tk.LabelFrame(container_paned,
                                                text="Aliment de substitution",
                                                padx=15,
                                                pady=15)
        label_frame_description.pack(fill="both", expand="yes")
        self.description_box = tk.Text(label_frame_description)
        self.description_box.pack(fill="both", expand="yes")
        self.button_save_food = tk.Button(label_frame_description,
                                          text='Sauvegarder',
                                          command=self.add_user_food,
                                          state=tk.DISABLED)
        self.button_save_food.pack(side=tk.LEFT)
        container_paned.add(label_frame_description)

    def display_food_category(self):
        """ Display food menu selection """
        # Get category name insert by user
        category_name = str(self.input_category.get())
        self.reset_form()
        if category_name:
            # status bar message
            self.status_bar['text'] = 'Answering database ...'
            # get categories from database
            categories = self.category.get_list(
                ('PK_id', 'name'), ('name LIKE', '%{}%'.format(category_name)))
            # clear category list
            self.category_list.delete(0, tk.END)
            # clear category ids list
            self.category_ids = []
            # display all category
            for category in categories:
                pk_id, name = category
                self.category_list.insert(tk.END, name)
                self.category_ids.append(pk_id)
            # status bar message
            self.status_bar['text'] = ''

    def bind_category_selected(self, event):
        """ user select a category"""

        w = event.widget
        if w.curselection():
            self.status_bar['text'] = 'Recherche des aliments de la categorie'
            self.reset_form()
            self.current_category_idx = int(w.curselection()[0])
            self.display_category_food_list()
        else:
            self.current_category_idx = None

    def display_category_food_list(self, page=1):
        """ Display category food list

        Keyword arguments:
        page -- int

        """
        # Get category index selected by user

        if not self.current_category_idx == None:

            pk_id = self.category_ids[self.current_category_idx]
            if pk_id:
                # read all food for category
                self.food_data = self.food.find_by_category(pk_id, page)
                self.display_food_list()

                if self.food_data['before_page'] > 0:
                    self.button_before_page['state'] = tk.ACTIVE
                else:
                    self.button_before_page['state'] = tk.DISABLED

                if self.food_data['next_page'] > 0:
                    self.button_next_page['state'] = tk.ACTIVE
                else:
                    self.button_next_page['state'] = tk.DISABLED

    def display_food_list(self):
        """ Add food in list box"""
        if self.food_data:
            # clear food list
            self.product_list.delete(0, tk.END)
            # Add food in name list
            if self.food_data['response']:
                for food in self.food_data['response']:
                    self.product_list.insert(tk.END, str(food.name))
            # status bar message
            self.status_bar['text'] = 'Page : ' + str(
                self.food_data['current_page'])

    def display_my_food_list(self):
        """ Display user food list """
        self.food_data = (User()).find_user_food(1)
        self.display_food_list()

    def bind_food_selected(self, event):
        """ user select a category"""
        w = event.widget
        if w.curselection():
            self.status_bar['text'] = 'Recherche de l\'aliment de substitution'
            self.current_food_idx = int(w.curselection()[0])
            self.aliment = self.food_data['response'][self.current_food_idx]
            self.description_box.delete(1.0, tk.END)
            self.button_save_food['state'] = tk.ACTIVE
            self.display_food_description()

    def display_food_description(self):
        """ Display the description of food selected """

        # A product selected

        if self.aliment:
            foods = self.food.find_better_nutricode(self.aliment)
            for food in foods:
                self.show_in_description_box(food)
                self.description_box.insert(
                    tk.END, "--------------------------------"
                    "------------------------------------\n")
            self.status_bar[
                'text'] = 'Affichage aliment de substitution : {}'.format(
                    str(food.name))

    def show_in_description_box(self, food):
        """ wrote on description box

        Keyword arguments:
        food -- object

        """
        self.description_box.insert(
            tk.END, "Nutri-code : {} \n".format(str(food.level).upper()))
        self.description_box.insert(tk.END,
                                    "Aliment : {} \n".format(food.name))
        self.description_box.insert(
            tk.END, "Description : {} \n".format(str(food.description)))
        self.description_box.insert(
            tk.END,
            "Categorie(s) : {} \n".format(','.join(food.get_categories_name)))
        self.description_box.insert(
            tk.END, "Magasin(s) : {} \n".format(','.join(food.get_shops_name)))
        self.description_box.insert(tk.END, "lien : {}\n".format(food.link))

    def display_next_page(self):
        """ Display next page foods """
        if self.food_data and self.food_data['next_page'] > 0:
            self.display_category_food_list(self.food_data['next_page'])

    def display_before_page(self):
        """ Display before page foods """
        if self.food_data and self.food_data['before_page'] > 0:
            self.display_category_food_list(self.food_data['before_page'])

    def add_user_food(self):
        """ save user food selected """

        if not self.current_food_idx == None:
            aliment = self.food_data['response'][self.current_food_idx]
            # if save doesn't exist
            args = {'FK_user_id': 1, 'FK_food_id': aliment.PK_id}
            user_food = UserFood(args)
            # check if save exist
            exist = user_food.findone({
                'where': [('FK_user_id =', 1), ('FK_food_id =', aliment.PK_id)]
            })
            if not exist:
                user_food.save()
                self.status_bar['text'] = 'Sauvegarde : ' + str(aliment.name)
            else:
                self.status_bar['text'] = 'Sauvegarde déjà existante.'

            self.current_food_idx = None
        self.button_save_food['state'] = tk.DISABLED

    def update_data_base(self):
        """ update dat in database from Open data food """
        (Update()).update_db

    def reset_form(self):
        """ hide and empty element """
        self.product_list.delete(0, tk.END)
        self.description_box.delete(1.0, tk.END)
        self.aliment = None
        self.current_food_idx = None
        self.button_save_food['state'] = tk.DISABLED
        self.button_before_page['state'] = tk.DISABLED
        self.button_next_page['state'] = tk.DISABLED
コード例 #9
0
    def loop_game(self, snake, ai_function, speed, data_state={}):
        self.count_food = 0

        snake_player = snake
        snake_player.set_start_position(self.width_game // 2,
                                        self.height_game // 2)

        food_block = Food(
            round(
                random.randrange(0, self.width_game - self.block) / self.block)
            * self.block,
            round(
                random.randrange(0, self.height_game - self.block) /
                self.block) * self.block, self.block, self.block,
            self.food_image, self.block)

        # Inicio del juego
        while self.run_game:
            self.clock.tick(speed)

            # Guardo en data_state los valores actuales (para la AI)
            data_state["snake_size"] = len(snake_player.body)
            data_state["snake_body"] = snake_player.body
            data_state["snake_head"] = snake_player.body[-1]
            data_state["snake_tail"] = snake_player.body[0]
            data_state["food_count"] = self.count_food
            data_state["food_position"] = [(food_block.x, food_block.y)]
            data_state["STATUS"] = "PLAYING"
            data_state["direction"] = snake_player.direction

            # Eventos de teclado o IA
            if ai_function is None:
                key = self.get_events()
                if key == "QUIT":
                    self.run_game = False
                    self.run_loop = False
                if key == "SPACE":
                    self.pause = not self.pause
                if not self.pause and key is not None:
                    snake_player.move_snake(key)
            else:
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        self.run_game = False
                        self.run_loop = False
                predicted_move = ai_function(data_state)
                key = None
                if predicted_move == "UP":
                    key = "U"
                elif predicted_move == "DOWN":
                    key = "D"
                elif predicted_move == "LEFT":
                    key = "L"
                elif predicted_move == "RIGHT":
                    key = "R"
                snake_player.move_snake(key)

            if not self.pause:
                # Colision con el cuerpo
                for body in snake_player.body[:len(snake_player.body) - 1]:
                    if body[0] == snake_player.x and body[1] == snake_player.y:
                        self.run_game = False
                        data_state["STATUS"] = "GAMEOVER"
                        break

                # Cuerpo de la snake_player
                snake_player.add_body(snake_player.x, snake_player.y)

                # Agarrar comida
                if snake_player.x == food_block.x and snake_player.y == food_block.y:
                    self.count_food += 1
                    possible_placemments = food_block.possible_placements(
                        snake_player.body, self.width_game, self.height_game)
                    if len(possible_placemments) > 0:
                        food_block.set_food_position(snake_player.body,
                                                     self.width_game,
                                                     self.height_game)
                    else:
                        self.run_game = False
                        data_state["STATUS"] = "WINNER"
                        break
                else:
                    snake_player.remove_tail()

                # Colision con los limites
                if snake_player.x > self.width_game - snake_player.width or snake_player.x < 0 or snake_player.y > self.height_game - snake_player.height or snake_player.y < 0:
                    self.run_game = False
                    data_state["STATUS"] = "GAMEOVER"
                    break

            # Dibujo la ventana
            self.draw_window(self.width_game, self.width_game // self.block,
                             self.screen)
            snake_player.draw(self.screen)
            food_block.draw(self.screen)

            # Texto / Puntaje dentro del juego
            if self.pause:
                text_pause = self.font.render('PAUSA', True,
                                              self.config["colors"]["white"],
                                              self.config["colors"]["black"])
                self.screen.blit(
                    text_pause,
                    (self.width_game // 2 - 20, self.height_game // 2))
            else:
                text_pause = self.font.render('', True,
                                              self.config["colors"]["white"],
                                              self.config["colors"]["black"])
                self.screen.blit(
                    text_pause,
                    (self.width_game // 2 - 20, self.height_game // 2))

            text_title = self.font.render('SNAKE GAME', True,
                                          self.config["colors"]["white"],
                                          self.config["colors"]["black"])
            self.screen.blit(text_title, (self.width_window - 180, 10))
            text_score = self.font_2.render(f"Score: {self.count_food}", True,
                                            self.config["colors"]["white"],
                                            self.config["colors"]["black"])
            self.screen.blit(text_score, (self.width_window - 180, 70))

            # Actualizar ventana
            pygame.display.update()
        return data_state