コード例 #1
0
ファイル: main.py プロジェクト: deoel/43
class Game:
    def __init__(self, tab_enemy=[]):
        self.flag = False
        self.t = None
        self.points = 0
        self.game_over = False
        self.tab_id_coins = list()
        self.all_id_widget = list()
        self.tab_enemy = tab_enemy
        self.creer_game_window()
        self.creer_canvas_game()
        self.creer_boutons_options()
        self.afficher_texte_sur_canvas(TITRE_GAME)

    def creer_game_window(self):
        self.root = Tk()
        self.w = self.root.winfo_screenwidth()
        self.h = self.root.winfo_screenheight()
        x = (self.w - WIDTH) // 2
        y = (self.h - HEIGHT) // 2
        self.root.geometry('{}x{}+{}+{}'.format(WIDTH, HEIGHT, x, y))

    def lancer_game_window(self):
        self.root.mainloop()

    def creer_canvas_game(self):
        self.can = Canvas(self.root, width=700, height=HEIGHT, bg=BG)
        self.can.grid(row=0, column=0, rowspan=10)

    def creer_boutons_options(self):
        self.score = Label(self.root,
                           text='Score : 0',
                           font=(FONT, 18),
                           width=10)
        self.score.grid(row=0, column=1, sticky=N, padx=5)
        self.bouton_jouer = Button(self.root,
                                   text="JOUER",
                                   font=("Comic Sans MS", 16),
                                   bg=COLOR_VIOLET,
                                   command=self.start,
                                   width=10)
        self.bouton_jouer.grid(row=2, column=1, sticky=N, padx=5, pady=5)
        Button(self.root,
               text="QUITTER",
               font=("Comic Sans Ms", 16),
               bg=COLOR_VIOLET,
               command=self.root.destroy,
               width=10).grid(row=3, column=1, sticky=N, padx=5, pady=5)

    # avant de jouer : afficher "The easyest game ever"
    # game over      : afficher "Game over, vous avez perdu"
    # bingo game     : afficher "Bingo, vous avez gagné"

    def afficher_texte_sur_canvas(self, texte):
        self.clean()
        f = tkFont.Font(size=30, family=FONT, weight="bold")
        id = self.can.create_rectangle(0,
                                       0,
                                       700,
                                       HEIGHT,
                                       fill=BG,
                                       outline=COLOR_VIOLET)
        self.all_id_widget.append(id)
        id = self.can.create_text(350,
                                  200,
                                  text=texte,
                                  fill=COLOR_BLACK,
                                  activefill=COLOR_YELLOW,
                                  font=f,
                                  justify="center")
        self.all_id_widget.append(id)

    def start(self):
        self.clean()
        self.score['text'] = "Score : 0"
        self.points = 0
        self.bouton_jouer['text'] = "Recommencer"

        self.creer_espace_jeu()
        self.creer_coins()
        self.creer_joueur()

        if not self.flag:
            self.creer_ennemis()
            self.flag = True

        if self.game_over:
            self.game_over = False

    def clean(self):
        for id in self.all_id_widget:
            self.can.delete(id)

    def creer_espace_jeu(self):
        self.bloc_mur = BlocMur("bloc_mur1.txt")
        self.bloc_mur.draw(self.can)
        self.espace_jeu = EspaceJeu()
        self.espace_jeu.draw(self.can)

    def creer_coins(self):
        self.coin = Coin("coins1.txt")
        self.tab_id_coins = self.coin.draw(self.can)
        for id in self.tab_id_coins:
            self.all_id_widget.append(id)

    def deplacer_joueur(self, a):
        self.collision_coin()
        if a.keysym == 'Down':
            a, b, c = self.c.go_down()
            if self.collision_mur():
                self.c.go_up()
            else:
                self.can.move(a, b, c)
        elif a.keysym == "Up":
            a, b, c = self.c.go_up()
            if self.collision_mur():
                self.c.go_down()
            else:
                self.can.move(a, b, c)
        elif a.keysym == "Left":
            a, b, c = self.c.go_left()
            if self.collision_mur():
                self.c.go_right()
            else:
                self.can.move(a, b, c)
        elif a.keysym == "Right":
            a, b, c = self.c.go_right()
            if self.collision_mur():
                self.c.go_left()
            else:
                self.can.move(a, b, c)
        self.win()

    def creer_joueur(self, x0=20, y0=20, x1=40, y1=40):
        self.c = CarreJoueur(x0, y0, x1, y1)
        id = self.c.draw(self.can)
        self.all_id_widget.append(id)
        self.root.bind('<Key>', self.deplacer_joueur)

    def creer_ennemis(self):
        for e in self.tab_enemy:
            e.draw(self.can)
        self.t = Thread(target=self.deplacer_ennemis)
        self.t.daemon = True
        self.t.start()

    def deplacer_ennemis(self):
        while True:
            if not self.game_over:
                for e in self.tab_enemy:
                    a, b, c = e.moving_around(700, HEIGHT)
                    try:
                        self.can.move(a, b, c)
                        self.collision_ennemi()
                    except:
                        exit()
                time.sleep(0.015)
            else:
                continue

    def collision_coin(self):
        for c in self.coin.tab_coins:
            x0, y0, x1, y1 = c[0], c[1], c[0] + 15, c[1] + 15
            coord_coin = Coord_XY_XY(x0, y0, x1, y1)
            coord_joueur = Coord_XY_XY(self.c.x0, self.c.y0, self.c.x1,
                                       self.c.y1)
            if coord_coin.collision(coord_joueur):
                self.points += 10
                self.score['text'] = "Score : %d" % (self.points)
                id = self.can.create_oval(x0,
                                          y0,
                                          x1,
                                          y1,
                                          outline=COLOR_VIOLET,
                                          fill=COLOR_VIOLET)
                self.all_id_widget.append(id)
                self.creer_joueur(self.c.x0, self.c.y0, self.c.x1, self.c.y1)

    def collision_mur(self):
        for bm in self.bloc_mur.tab_bloc_mur:
            x0, y0, x1, y1 = bm
            coord_bloc_mur = Coord_XY_XY(x0, y0, x1, y1)
            coord_joueur = Coord_XY_XY(self.c.x0, self.c.y0, self.c.x1,
                                       self.c.y1)
            if coord_bloc_mur.in_limite(coord_joueur):
                return False
        return True

    def collision_ennemi(self):
        for e in self.tab_enemy:
            coord_ennemi = Coord_XY_XY(e.x0, e.y0, e.x1, e.y1)
            coord_joueur = Coord_XY_XY(self.c.x0, self.c.y0, self.c.x1,
                                       self.c.y1)
            if coord_ennemi.collision(coord_joueur):
                self.game_over = True
                self.afficher_texte_sur_canvas(GAME_OVER)

    def win(self):
        coord_fin = Coord_XY_XY(600, 400, 650, 450)
        coord_joueur = Coord_XY_XY(self.c.x0, self.c.y0, self.c.x1, self.c.y1)
        if coord_fin.in_limite(coord_joueur):
            self.game_over = True
            self.afficher_texte_sur_canvas(GAME_WIN)
コード例 #2
0
def start():
    # Create board and players
    board = Board(GRID_NUM, RATIO)
    searcher = Player("Searcher", 0, 0,"./searcher.png",3,3)
    monster = Player("Monster", GRID_NUM-1, GRID_NUM-1,"./monster.jpg",BOARD_SIZE-50,BOARD_SIZE-50)
    board.board[searcher.row][searcher.col].players.append(searcher.name)
    board.board[monster.row][monster.col].players.append(monster.name)
    players = [searcher,monster]
    done = False

    # Create board view
    boardview = [ [WHITE for col in range(GRID_NUM)] for row in range(GRID_NUM) ]
    scoreview = pygame.Rect(GRID_MARGIN, (GRID_SIZE+GRID_MARGIN) * GRID_NUM + GRID_MARGIN, BOARD_SIZE, SCORE_HEIGHT)
    searcher.collectCoin(board)

    def distanceToMonster(player):
        return abs(player.row - monster.row) + abs(player.col - monster.col)

    def monsterRandomMove():
        rand = random.randint(0, 3)
        if rand == 0: monster.moveUp(board)
        elif rand == 1: monster.moveDown(board)
        elif rand == 2: monster.moveLeft(board)
        elif rand == 3: monster.moveRight(board)

    def monsterSmartMove(player):
        if abs(monster.row - player.row) > abs(monster.col - player.col): # monster move on x axis
            if monster.row < player.row: monster.moveDown(board)
            else: monster.moveUp(board)
        else: # monster move on y axis
            if monster.col < player.col: monster.moveRight(board)
            else: monster.moveLeft(board)

    def moveInput(player):
        m = event.key
        if player.move(m,board): 
            ### player meets monster
            if player.row == monster.row and player.col == monster.col:
                eat_sound.play()
                return
            player.collectCoin(board)
            if distanceToMonster(player) <= GRID_NUM * 2 // 4:
                monsterSmartMove(player)
            else: monsterRandomMove()
            ### player meets monster
            if player.row == monster.row and player.col == monster.col:
                eat_sound.play()
        else: print("Invalid Move")

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()
    end = False
    max = 3
    curshow = []
    while not done:
        for event in pygame.event.get():  # User did something
            if event.type == pygame.QUIT:
                done = True
                break
            if not end: 
                if event.type == pygame.MOUSEBUTTONDOWN and len(curshow) != max:
                    # User clicks the mouse. Reveal the tile underneath
                    pos = pygame.mouse.get_pos()
                    # Change the x/y screen coordinates to grid coordinates
                    col = pos[0] // (GRID_SIZE + GRID_MARGIN)
                    row = pos[1] // (GRID_SIZE + GRID_MARGIN)
                    if row < GRID_NUM and col < GRID_NUM and [row,col] not in curshow:
                        curshow.append([row,col])   
                        board.board[row][col].show = True
                elif event.type == pygame.KEYDOWN: #and len(curshow) == 3: #may delete second condition for better user experience.
                    ### player is moving
                    moveInput(searcher)
                    for n in curshow:
                        board.board[n[0]][n[1]].show = False
                    curshow = []

        # Set the screen background
        screen.fill(BLACK)

        # Restart listener
        restart.listen(pygame.event.get())
        # Quit listener
        quit.listen(pygame.event.get())
        
        # Draw the board
        for row in range(GRID_NUM):
            for col in range(GRID_NUM):
                pygame.draw.rect(screen,
                                 WHITE,
                                 [(GRID_MARGIN + GRID_SIZE) * col + GRID_MARGIN,
                                  (GRID_MARGIN + GRID_SIZE) * row + GRID_MARGIN,
                                  GRID_SIZE,
                                  GRID_SIZE])
                if board.board[row][col].show:
                    #If both monster and coin, shows half and half picture
                    if row == monster.row and col == monster.col and board.board[row][col].coins:
                        coin = Coin(row, col, "./monstercoin.jpg", (GRID_MARGIN+GRID_SIZE)*col+GRID_MARGIN, (GRID_MARGIN+GRID_SIZE)*row+GRID_MARGIN)
                        coin.draw(screen)  
                    elif row == monster.row and col == monster.col: 
                        monster.draw(screen)
                    elif board.board[row][col].coins:
                        coin = Coin(row, col, "./coin.jpg", (GRID_MARGIN+GRID_SIZE)*col+GRID_MARGIN, (GRID_MARGIN+GRID_SIZE)*row+GRID_MARGIN)
                        coin.draw(screen)       
        # Draw searcher
        searcher.draw(screen)
        
        # Draw score board and quit button 
        pygame.draw.rect(screen, WHITE, scoreview)
        updateCoins(searcher.coins)
        restart.draw()
        quit.draw()

        ### player collected all the coins
        if searcher.coins >= int(GRID_NUM * GRID_NUM * RATIO * RATIO):
            updateResult('You win!')
            end = True
        ### player meets monster
        elif searcher.row == monster.row and searcher.col == monster.col:
            updateResult('You lose!')
            end = True

        # Limit to 60 frames per second
        clock.tick(60)

        # Go ahead and update the screen with what we've drawn.
        pygame.display.flip()