예제 #1
0
    def draw(self, xcam, ycam):
        if self.direction:
            anim_index = 0
        else:
            anim_index = 1
            
        if not self.land:
            if self.vy < 0:
                sprite = self.jumping[anim_index][1]
            else:
                sprite = self.jumping[anim_index][0]
        else:
            if self.right or self.left:
                sprite = self.walking[anim_index][self.frame]
                self.frame = (self.frame + 1) % len(self.walking[anim_index])                
            else:
                self.delta_frames = (self.delta_frames + 1) % 120                
                if self.delta_frames < 90:
                    sprite = self.idle[anim_index][0]
                else:
                    sprite = self.idle[anim_index][1]

        # Center image
        xoffset = -sprite.get_width()/2
        yoffset = -sprite.get_height()
        game.draw(sprite, (xcam + xoffset, ycam + yoffset))
        if DEBUG:
예제 #2
0
파일: snake.py 프로젝트: bravo585/Snake
def main_loop():
    pygame.init()
    pygame.display.set_caption(game.NAME)
    clock = pygame.time.Clock()

    background = pygame.Surface(game.screen.get_size()).convert()
    background.fill(pygame.Color(0, 0, 0))

    input_queue = multiprocessing.Queue()

    while True:
        # Choose player mode
        options = ["AI Demo", "Two players", "Three players", "Four players"]
        selection = Menu(options).show()
        if selection is False:
            return
        else:
            game.num_players = selection + 1

        # Choose level
        levels = level.get_levels()
        selection = Menu([lvl.name for lvl in levels]).show()
        if selection is False:
            continue
        else:
            game.level = levels[selection]

            # If single player, add an AI player
            if game.num_players == 1:
                game.num_players = 4
                game.init_level()

                ai_engines = []
                ai_processes = []
                ai_engines.append(ai_classes[0])
                ai_engines.append(ai_classes[1])
                ai_engines.append(ai_classes[2])
                ai_engines.append(ai_classes[1])
                shared_apples = multiprocessing.Array(process.GameObject,
                        list((apple.x, apple.y) for apple in game.apples))
                shared_players = multiprocessing.Array(process.MovableGameObject,
                        list(((player.x, player.y), player.direction)
                            for player in game.players))
                ai_processes = [_class(player_index=i, board=game.shared_board, players=shared_players, apples=shared_apples, player=game.players[i], args=(input_queue,)) for i, _class in enumerate(ai_engines)]
                # Load threaded AI
                if game.use_multiprocessing:
                    map(lambda proc: proc.start(), ai_processes)
                game.players[1].name = 'The Spirit of AI'
                game.players[1].name = 'Bebe Bot'
                game.players[2].name = 'The Will of AI'
                game.players[3].name = 'Bot Choy'
            else:
                game.init_level()

        # Start game loop
        return_to_menu = False
        game_status = None
        ai_frame_count = 1
        start_time = time.time()

        while not return_to_menu:
            clock.tick(game.frames_per_second)

            while True:
                # Process key presses from AI threads.
                # Pulls values from input queue, creates pygame Events, and
                # submits to event queue.
                try:
                    pygame.event.post(pygame.event.Event(KEYDOWN, {'key':
                        input_queue.get_nowait(),}))
                except Queue.Empty, qe:
                    break

            # Process non multiprocessing AI moves
            if not game.use_multiprocessing:
                # map(lambda proc: proc.execute(), ai_processes)
                for proc in ai_processes:
                    if not isinstance(proc, JasonAI):
                        proc.execute()

                if ai_frame_count < 3:
                    ai_frame_count += 1
                else:
                    for proc in ai_processes:
                        if isinstance(proc, JasonAI):
                            proc.execute()
                    ai_frame_count = 1

            # Get input
            for event in pygame.event.get():
                if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                    return_to_menu = True
                    # Shutdown all AI processes
                    if game.use_multiprocessing:
                        map(lambda proc: proc.shutdown(), ai_processes)
                    break

                if event.type == KEYDOWN:
                    if event.key == K_SPACE:
                        game.players[0].grow = True
                    elif event.key == K_RETURN and game_status == "win":
                        game.init_level()
                        game_status = None
                        continue
                    elif event.key in game.player_controls[0]:
                        game.players[0].set_direction(game.player_controls[0].index(event.key))
                    elif event.key in game.player_controls[1] and game.num_players > 1:
                        game.players[1].set_direction(game.player_controls[1].index(event.key))
                    elif event.key in game.player_controls[2] and game.num_players > 2:
                        game.players[2].set_direction(game.player_controls[2].index(event.key))
                    elif event.key in game.player_controls[3] and game.num_players > 3:
                        game.players[3].set_direction(game.player_controls[3].index(event.key))

            # Update effects
            for effect in game.effects:
                effect.update()

            # Update game
            game.update()

            # Update shared board
            for i, v in enumerate([(apple.x, apple.y) for apple in game.apples]):
                shared_apples[i] = v

            for i, v in enumerate([((player.x, player.y), player.direction, player.get_length()) for player in game.players]):
                shared_players[i] = v

            # Draw the screen
            game.screen.blit(background, (0, 0))
            game.draw()
            for effect in game.effects:
                effect.draw()

            # Draw scoreboard
            score_icon_size = 30
            score_width = 55
            score_margin = 120
            all_score_widths = game.num_players * score_width + (game.num_players-1) * score_margin
            score_x = (game.WINDOW_WIDTH - all_score_widths)/2
            score_y = game.WINDOW_HEIGHT - game.SCOREBOARD_HEIGHT + (game.SCOREBOARD_HEIGHT-score_icon_size)/2
            for i, player in enumerate(game.players):
                icon = pygame.Rect(score_x + i*(score_width+score_margin), score_y, score_icon_size, score_icon_size)
                text = str(len(player.kills))

                score = pygame.font.SysFont('impact', 30).render(text, 1, pygame.Color("white"))
                score_pos = score.get_rect(left = icon.right + 10, centery = icon.centery)

                game.screen.blit(score, score_pos)
                pygame.draw.rect(game.screen, player.color, icon)

            runtime = int(time.time() - start_time)
            runtime_min = runtime // 60
            runtime_sec = runtime % 60
            if runtime_min < 10:
                runtime_min = "0" + str(runtime_min)
            if runtime_sec < 10:
                runtime_sec = "0" + str(runtime_sec)
            runtime_text = "%s : %s" % (runtime_min, runtime_sec)

            time_text = pygame.font.SysFont('impact', 24).render(runtime_text, 1, pygame.Color("white"))
            time_pos = time_text.get_rect(x = game.WINDOW_WIDTH - 95, y = game.WINDOW_HEIGHT - 54)
            game.screen.blit(time_text, time_pos)

            # Check for the win condition
            winners = filter(lambda p: len(p.kills) >= game.level.kills_to_win, game.players)
            if winners:
                game_status = 'win'

                # Check for ties
                least_deaths = min(len(w.deaths) for w in winners)
                winners = filter(lambda w: len(w.deaths) == least_deaths, winners)
                if len(winners) > 1:
                    title = pygame.font.SysFont("impact", 100).render("Draw!", 1, pygame.Color("white"))
                else:
                    title = pygame.font.SysFont("impact", 100).render(winners[0].name + " wins!", 1, pygame.Color("white"))

                # Draw title
                title_pos = title.get_rect(centerx = game.WINDOW_WIDTH/2, centery = 200)
                game.screen.blit(title, title_pos)

                # Draw subtitle
                subtext = pygame.font.SysFont("verdana", 15).render("Press [ENTER] to play again, or [ESC] to return to the main menu.", 1, pygame.Color("white"))
                subtext_pos = subtext.get_rect(centerx = game.WINDOW_WIDTH/2, y = title_pos.bottom + 10)
                game.screen.blit(subtext, subtext_pos)

                # Draw summary
                header_width = 200
                header_height = 30
                header_margin = 0
                header_x = (game.WINDOW_WIDTH - header_width * game.num_players) / 2
                header_y = subtext_pos.bottom + 50
                cell_margin = 20

                for i, player in enumerate(game.players):
                    # Draw header box
                    header = pygame.Rect(header_x + (header_width+header_margin)*i, header_y, header_width, header_height)
                    pygame.draw.rect(game.screen, player.color, header)

                    # Draw header text
                    text = pygame.font.SysFont("arial", 16, bold=True).render(player.name, 1, pygame.Color("white"))
                    text_pos = text.get_rect(centerx = header.centerx, centery = header.centery)
                    game.screen.blit(text, text_pos)

                    # Draw death summary
                    s = "Total deaths: " + str(len(player.deaths))
                    death_summary_font = pygame.font.SysFont("arial", 14, bold=True).render(s, 1, pygame.Color("white"))
                    death_summary_pos = death_summary_font.get_rect(centerx = header.centerx, centery = header.bottom + cell_margin)
                    game.screen.blit(death_summary_font, death_summary_pos)

                    strings = []
                    strings.append(str(len(filter(lambda c: isinstance(c, game_objects.SnakePart) and c.player is not player, player.deaths))) + " by collision")
                    strings.append(str(len(filter(lambda c: isinstance(c, game_objects.Missile) and c.player is not player, player.deaths))) + " by missile")
                    strings.append(str(len(filter(lambda c: isinstance(c, game_objects.Wall), player.deaths))) + " by wall")
                    strings.append(str(len(filter(lambda c: (isinstance(c, game_objects.Missile) and c.player is player) or (isinstance(c, game_objects.SnakePart) and c.player is player), player.deaths))) + " by suicide")

                    for i, s in enumerate(strings):
                        text = pygame.font.SysFont("arial", 13).render(s, 1, pygame.Color("white"))
                        text_pos = text.get_rect(centerx = header.centerx, centery = death_summary_pos.bottom + (i+1)*cell_margin)
                        game.screen.blit(text, text_pos)

                    # Draw kill summary
                    s = "Total kills: " + str(len(player.kills))
                    kill_summary_font = pygame.font.SysFont("arial", 14, bold=True).render(s, 1, pygame.Color("white"))
                    kill_summary_pos = kill_summary_font.get_rect(centerx = header.centerx, centery = header.bottom + cell_margin + 130)
                    game.screen.blit(kill_summary_font, kill_summary_pos)

                    for i, opponent in enumerate(player.kills):
                        text = pygame.font.SysFont("arial", 13).render(opponent.name, 1, opponent.color)
                        text_pos = text.get_rect(centerx = header.centerx, centery = kill_summary_pos.bottom + (i+1)*cell_margin)
                        game.screen.blit(text, text_pos)


            # Display!
            pygame.display.flip()
예제 #3
0
파일: main.py 프로젝트: cravay/keggly
import pygame, game, sys

# Game initialization
game.init()
game.load_screen(0)

clock = pygame.time.Clock()

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

	game.update()
	game.draw()

	pygame.display.flip()

	clock.tick(30)
예제 #4
0
def bless(cur,ene):
    print("{} 獲得加護,身上的毒素一掃而空,並回復三點生命,還抽取了兩張手牌".format(cur.name))
    cur.poison = 0 # 解毒
    cur.life += 3
    for _ in range(2):
        game.draw(cur)
예제 #5
0
def game():
    group = pygame.sprite.Group()
    player_anim = Anime(group, (228, 288))
    board = Board.load_map(None, name)
    board.set_view(30, 30, 30)
    lst = []
    if sum(board.hero[0]):
        player = Player(screen, player_anim, board, board.hero[0])
        player_anim.resize(30)
    if sum(board.hero[1]):
        tverdolobiy = Tverdolobiy(group, board.hero[1], board, player)
        tverdolobiy.resize(30)
        lst.append(tverdolobiy)
    if sum(board.hero[2]):
        merzopakostniy = Merzopakostniy(group, board.hero[2], board, player)
        merzopakostniy.resize(30)
    if sum(board.hero[3]):
        legushka = Legushka(group, board.hero[3], board, player)
        legushka.resize(30)
        lst.append(legushka)
    running = True
    c = 0
    while running:
        c += 1
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                board.get_click(event.pos)
            if event.type == pygame.KEYDOWN:
                if event.key in up:
                    player.set_dir('up')
                if event.key in down:
                    player.set_dir('down')
                if event.key in left:
                    player.set_dir('left')
                if event.key in right:
                    player.set_dir('right')
                if event.key == pygame.K_LEFT:
                    player.set_dir('left')
                if event.key == pygame.K_RIGHT:
                    player.set_dir('right')
                if event.key == pygame.K_UP:
                    player.set_dir('up')
                if event.key == pygame.K_DOWN:
                    player.set_dir('down')
        screen.fill((0, 0, 0))
        board.render()
        if not len(board.check_points):
            board.check_points.add(None)
        if not board.are_left():
            board.reset()
        player.move([])
        player_anim.rect.x, player_anim.rect.y = player.x, player.y
        if sum(board.hero[2]):
            merzopakostniy.move()
        if not c % 2:
            if sum(board.hero[3]):
                legushka.move()
            if sum(board.hero[1]):
                tverdolobiy.move()
        group.draw(screen)
        if c % 20 == 0:
            player_anim.update()
        if sum(board.hero[2]):
            check = Check(player, merzopakostniy.num_bomb() + lst)
        elif sum(board.hero[0]):
            check = Check(player, lst)
        if check.checkaed():
            running = False
        draw(str(len(board.check_points) - 1 + board.count))
        pygame.display.flip()
    Finish(group, str(len(board.check_points) - 1 + board.count))
예제 #6
0
    def run(self, clock, windowWidth, windowHeight):
        gameMenu = menu.Menu(
            (windowWidth - (gameMenuWidth + 1) * gameMenuScale) / 2,
            (windowHeight - 7.3 * gameMenuScale) / 2,
            (gameMenuWidth + 1) * gameMenuScale, 7.3 * gameMenuScale,
            gameMenuScale, gameMenuItemList, self.screen)
        gameMenu.enabled = False

        exitGame = False
        backToMenu = False  # exit game mode
        while not backToMenu and not exitGame:
            #=======[ Game-Input - Begin ]========================
            for event in pygame.event.get():
                menuItem = gameMenu.updateInput(event)
                if menuItem == "resume":
                    gameMenu.enabled = False
                    self.gameInput.state = "running"
                    gameMenu.reset()
                elif menuItem == "main_menu":
                    backToMenu = True
                elif menuItem == "exit":
                    exitGame = True

                # exit application
                if event.type == pygame.QUIT:
                    exitGame = True

                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE and self.gameInput.state != "gameover":
                        if gameMenu.enabled:
                            gameMenu.enabled = False
                            self.gameInput.state = "running"
                            gameMenu.reset()
                        else:
                            gameMenu.enabled = True
                            self.gameInput.state = "paused"
                            gameMenu.reset()
                    if event.key == pygame.K_ESCAPE and self.gameInput.state == "gameover":
                        backToMenu = True

                self.gameInput.updateInput(event)

            if self.gameInput.state == "running":
                self.gameInput.updatePressedImput()
            #=======[ Game-Input - End ]==========================

            #=======[ Draw Game - Begin ]=========================
            self.screen.fill(color=configs.clBlack)  # "clear" the screen

            # draw next block box
            (xSize, ySize) = self.text_score.get_size()
            xRacPos = int(gameFiledBorderDistanceX * configs.zoom)
            yRacPos = int(gameFiledBorderDistanceY * configs.zoom) - 1
            xRacWidth = int(6 * configs.zoom)
            yRacHeight = int(3.2 * configs.zoom) + ySize
            pygame.draw.rect(self.screen,
                             color=configs.clBlack,
                             rect=[xRacPos, yRacPos, xRacWidth, yRacHeight])
            pygame.draw.rect(self.screen,
                             color=configs.clWhite,
                             rect=[xRacPos, yRacPos, xRacWidth, yRacHeight],
                             width=1)

            # draw next block header
            xFontOffset = xRacPos
            yFontOffset = yRacPos + int(0.25 * configs.zoom)
            self.screen.blit(
                self.text_next,
                [xFontOffset + int((xRacWidth - xSize) / 2), yFontOffset])
            yFontOffset += ySize + 0.5 * configs.zoom
            # update next block
            _block = self.gameList[0].nextBlock
            blockSize = 0
            if 3 in _block.image() or 7 in _block.image(
            ) or 11 in _block.image() or 16 in _block.image():
                blockSize = 4
            elif 2 in _block.image() or 6 in _block.image(
            ) or 10 in _block.image() or 15 in _block.image():
                blockSize = 3
            else:
                blockSize = 2
            functions.DrawSingleBlock(
                self.screen, xFontOffset + int(
                    (xRacWidth - blockSize * configs.zoom) / 2), yFontOffset,
                _block)

            # draw score box
            (xSize, ySize) = self.text_level.get_size()
            yRacPos += int(0.5 * configs.zoom) + yRacHeight
            yRacHeight = int(
                1 * configs.zoom) + ySize + self.value_font.get_height()
            pygame.draw.rect(self.screen,
                             color=configs.clBlack,
                             rect=[xRacPos, yRacPos, xRacWidth, yRacHeight])
            pygame.draw.rect(self.screen,
                             color=configs.clWhite,
                             rect=[xRacPos, yRacPos, xRacWidth, yRacHeight],
                             width=1)

            # draw score header
            yFontOffset = yRacPos + 0.25 * configs.zoom
            self.screen.blit(
                self.text_score,
                [xFontOffset + int((xRacWidth - xSize) / 2), yFontOffset])
            yFontOffset += ySize
            # update score
            scoreValueText = self.value_font.render(str(self.gameInput.score),
                                                    True, configs.clWhite)
            (xSize, ySize) = scoreValueText.get_size()
            yFontOffset += 0.5 * configs.zoom
            self.screen.blit(
                scoreValueText,
                [xFontOffset + int((xRacWidth - xSize) / 2), yFontOffset])

            # draw level box
            yRacPos += int(0.5 * configs.zoom) + yRacHeight
            pygame.draw.rect(self.screen,
                             color=configs.clBlack,
                             rect=[xRacPos, yRacPos, xRacWidth, yRacHeight])
            pygame.draw.rect(self.screen,
                             color=configs.clWhite,
                             rect=[xRacPos, yRacPos, xRacWidth, yRacHeight],
                             width=1)

            # draw level header
            (xSize, ySize) = self.text_level.get_size()
            yFontOffset = yRacPos + 0.25 * configs.zoom
            self.screen.blit(
                self.text_level,
                [xFontOffset + int((xRacWidth - xSize) / 2), yFontOffset])
            yFontOffset += ySize
            # update level
            levelUpdateText = self.value_font.render(str(self.gameInput.level),
                                                     True, configs.clWhite)
            (xSize, ySize) = levelUpdateText.get_size()
            yFontOffset += 0.5 * configs.zoom
            self.screen.blit(
                levelUpdateText,
                [xFontOffset + int((xRacWidth - xSize) / 2), yFontOffset])

            # draw every field
            for game in self.gameList:
                # update current block - go to the ground
                if game.state == "running":
                    game.goDown()

                game.draw(self.screen)

                # draw game over screen
                if game.state == "gameover":
                    (xSize, ySize) = self.text_gameover.get_size()
                    xOffset = int((windowWidth * configs.zoom - xSize -
                                   configs.zoom * 0.5) / 2)
                    yOffset = int((windowHeight * configs.zoom - ySize -
                                   configs.zoom * 0.5) / 2)
                    pygame.draw.rect(self.screen,
                                     color=configs.clBlack,
                                     rect=[
                                         xOffset,
                                         int(9.175 * configs.zoom),
                                         int(17 * configs.zoom),
                                         int(3.25 * configs.zoom)
                                     ])
                    pygame.draw.rect(self.screen,
                                     color=configs.clWhite,
                                     rect=[
                                         xOffset,
                                         int(9.175 * configs.zoom),
                                         int(17 * configs.zoom),
                                         int(3.25 * configs.zoom)
                                     ],
                                     width=1)
                    self.screen.blit(self.text_gameover, [
                        int((windowWidth * configs.zoom - xSize) / 2),
                        int((windowHeight * configs.zoom - ySize) / 2)
                    ])

            gameMenu.drawMenu()
            pygame.display.flip()  # update screen
            #=======[ Draw Game - End ]===========================

            clock.tick(configs.fps)  # wait time to reach the fps

        return exitGame