当前位置: 首页>>代码示例>>Python>>正文


Python Ball.draw方法代码示例

本文整理汇总了Python中ball.Ball.draw方法的典型用法代码示例。如果您正苦于以下问题:Python Ball.draw方法的具体用法?Python Ball.draw怎么用?Python Ball.draw使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ball.Ball的用法示例。


在下文中一共展示了Ball.draw方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import draw [as 别名]
def main():
    pygame.init()

    FPS = 30
    FPS_CLOCK = pygame.time.Clock()

    # COLOR LIST
    WHITE = pygame.Color(255, 255, 255)

    # Code to create the initial window
    window_size = (500, 500)
    SCREEN = pygame.display.set_mode(window_size)

    # set the title of the window
    pygame.display.set_caption("Bouncing Ball Animation")

    # change the initial background color to white
    SCREEN.fill(WHITE)

    b1 = Ball(0, 0, 4, 5)

    b1.draw(SCREEN)

    while True:  # <--- main game loop
        for event in pygame.event.get():
            if event.type == QUIT:  # QUIT event to exit the game
                pygame.quit()
                sys.exit()

        SCREEN.fill(WHITE)
        b1.move(SCREEN)
        b1.draw(SCREEN)

        pygame.display.update()  # Update the display when all events have been processed
        FPS_CLOCK.tick(FPS)
开发者ID:DustinY,项目名称:CS332L_Python,代码行数:37,代码来源:ball_animation.py

示例2: main

# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import draw [as 别名]
def main():
    """ Main function for the game. """
    pygame.init()

    # Set the width and height of the screen [width,height]
    size = [800, 600]
    screen = pygame.display.set_mode(size)

    pygame.display.set_caption("CMSC 150 is cool")

    # Loop until the user clicks the close button.
    done = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()


    theBall = Ball()
    theBall.x = 100
    theBall.y = 100
    theBall.change_x = 2
    theBall.change_y = 1
    theBall.color = [255,0,0]

    # -------- Main Program Loop -----------
    while not done:
        # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
        # ALL EVENT PROCESSING SHOULD GO ABOVE THIS COMMENT

        # ALL GAME LOGIC SHOULD GO BELOW THIS COMMENT

        # ALL GAME LOGIC SHOULD GO ABOVE THIS COMMENT

        # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT

        # First, clear the screen to white. Don't put other drawing commands
        # above this, or they will be erased with this command.

        # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

        screen.fill(BLACK)
        theBall.move()
        theBall.draw(screen)

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

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

    # Close the window and quit.
    # If you forget this line, the program will 'hang'
    # on exit if running from IDLE.
    pygame.quit()
开发者ID:tazz0009,项目名称:pygameTest1,代码行数:59,代码来源:ball_main.py

示例3: new_random_ball

# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import draw [as 别名]
 def new_random_ball(self, canvas=None):
     while True:
         i1 = randint(0, CELLS - 1)
         j1 = randint(0, CELLS - 1)
         if not self.find(i1, j1):
             break
     new_ball = Ball(i1, j1, choice(colors))
     self.data.append(new_ball)
     if canvas:
         new_ball.draw(canvas)
开发者ID:r47717,项目名称:PyLines,代码行数:12,代码来源:ballset.py

示例4: main

# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import draw [as 别名]
def main():
    set_clear_color(1, 1, 1)
    enable_smoothing()
    
    ball = Ball(20, 20, 0, 0, .3, .3, 1.)

    while not window_closed():
        clear()
    
        ball.draw(PIXELS_PER_METER)

        ball.update_position(TIMESTEP)
        ball.update_velocity(TIMESTEP)
   
        request_redraw()
        sleep(TIMESTEP)
开发者ID:CS98,项目名称:TheOneRepo,代码行数:18,代码来源:ball_example2.py

示例5: start

# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import draw [as 别名]
def start(size):
    main_clock = pygame.time.Clock()
    pygame.display.init()
    window  = pygame.display.set_mode(size)
    window_ = window.copy() 
    b = Ball()
    r_right   = Racket('R')
    r_left    = Racket('L')
    while True:
        # Event manager
        for event in pygame.event.get():
            if event.type == QUIT:
                end()
            elif event.type == MOUSEBUTTONDOWN:
                if event.button == 1:
                    pass
            elif event.type == KEYDOWN:
                #print(event.key)
                if event.key == 273: # Direction key up
                    r_right.direction = 'up'
                    break
                if event.key == 274: # Direction key down
                    r_right.direction = 'down'
                    break
            r_right.direction = False
                    
        window.blit(window_, (0, 0))
        r_right.draw(window)
        r_right.update()
        r_left.computerAI(b)
        r_left.draw(window)
        r_left.update()
        b.draw(window)
        b.update()
        b.collides(r_right, r_left)
        Interface.draw(window, r_left.mark, r_right.mark)
        pygame.display.flip()
        main_clock.tick(100)
开发者ID:Margaruga,项目名称:Games,代码行数:40,代码来源:main.py

示例6: __init__

# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import draw [as 别名]
class Board:

    def __init__(self, window, path="."):

        self.window = window
        self.h, self.w = window.getmaxyx()

        self.cells_x = self.w // Block.WIDTH
        self.cells_y = self.h // Block.HEIGHT
        self.field = [[None] * self.cells_x  for i in range(self.cells_y)]

        self._gen_blocks(path)
        self.ball = Ball(self.h-2, self.w//2)

        self.paddle = Paddle(self.h-1, self.w//2)

    def draw(self):
        for row in self.field:
            for cell in row:
                if cell is not None:
                    cell.draw(self.window)

        self.window.attron(curses.color_pair(1))

        self.ball.draw(self.window)
        self.paddle.draw(self.window)

    def move(self, offset):
        self.paddle.move(offset, self.w)

    def animate(self):
        self.ball.animate(self.h, self.w)
        self._collide_endzone()
        self._collide_blocks()
        self._collide_paddle()

    def _collide_blocks(self):
        cell_x = self.ball.x // Block.WIDTH
        cell_y = self.ball.y // Block.HEIGHT

        if (cell_y >= self.cells_y) or (cell_x >= self.cells_x):
            return

        block = self.field[cell_y][cell_x]
        if block is not None:

            self.field[cell_y][cell_x] = None # destroy the block

            # deflect the ball
            if (self.ball.y == block.top()) or \
               (self.ball.y == block.bottom()):
                self.ball.bounce_y()

            if (self.ball.x == block.left()) or \
               (self.ball.x == block.right()):
                self.ball.bounce_x()

            if block.isdir:
                self._gen_blocks(block.f)
            else:
                pass
                #block.destroy()

    def _collide_endzone(self):
        if self.ball.y == self.h - 1:
            exit()

    def _collide_paddle(self):
        if self.paddle.contacts(self.ball):
            self.ball.bounce_y()

    def _add_block(self, f):
        for y, row in enumerate(self.field):
            for x, cell in enumerate(row):
                if cell is None:
                    b = Block(f, y, x)
                    self.field[y][x] = b
                    return

    def _gen_blocks(self, path):
        for f in os.listdir(path):
            self._add_block(os.path.join(path, f))
开发者ID:Nolski,项目名称:rm-out,代码行数:84,代码来源:board.py

示例7: Level

# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import draw [as 别名]
class Level(object):
    """
    Main Level class, handles most of the gameplay
    """
    def __init__(self, screen, draw_offset, control_set, player_color, finish_game):
        """
        Init with... way too many parameters
        :param screen: Main PyGame surface to draw the objects/UI on
        :param draw_offset: Drawing offset used in multiplayer
        :param control_set: Key-set used to control the Paddle
        :param player_color: Color of the player's Paddle
        :param finish_game: Function passed to the constructor, triggered on
        the game end
        :return:
        """
        self.screen = screen
        self.draw_offset = draw_offset
        self.control_set = control_set
        self.prev_input_x = 0
        self.level_number = 1
        self.block_count = 0
        self.player = Player("Derp")
        self.paddle = Paddle(LEVEL_WIDTH/2 - Paddle.WIDTH/2, LEVEL_HEIGHT - 40,
                             player_color, parent=self, owner=self.player)
        self.ball = Ball(self.paddle.rect.x + Paddle.WIDTH/2 - Ball.RADIUS,
                         self.paddle.rect.y - Ball.RADIUS * 2)
        self.items = None
        self.blocks = []
        self.blocks_surface = None
        self.blocks_surface_dirty = True
        self.entities = []
        self.font = Assets.font
        self.score_label = None
        self.lives_label = None
        self.level_label = None
        self.load_level(self.level_number)
        self.finish_game = finish_game

    def handle_input(self, events):
        """
        Handles incoming input events
        :param events: input events from the main app
        :return:
        """
        BONUS_SPAWN_X = 305
        BONUS_SPAWN_Y = 200
        for event in events:
            if event.type == KEYDOWN:
                if event.key == self.control_set[0]:
                    if self.paddle.vx != 0:
                        self.prev_input_x = 1
                    self.paddle.vx = -1

                elif event.key == self.control_set[2]:
                    if self.paddle.vx != 0:
                        self.prev_input_x = -1
                    self.paddle.vx = 1

                # elif event.key == K_SPACE:
                #     self.paddle.change_size(self.paddle.rect.width+10)

                elif event.key == K_1:
                    # self.add_entity(ItemExpand(BONUS_SPAWN_X, BONUS_SPAWN_Y))
                    self.spawn_item(BONUS_SPAWN_X, BONUS_SPAWN_Y, 1)

                elif event.key == K_2:
                    # self.add_entity(ItemLaserGun(BONUS_SPAWN_X, BONUS_SPAWN_Y))
                    self.spawn_item(BONUS_SPAWN_X, BONUS_SPAWN_Y, 2)

                elif event.key == K_3:
                    # self.add_entity(ItemShrink(BONUS_SPAWN_X, BONUS_SPAWN_Y))
                    self.spawn_item(BONUS_SPAWN_X, BONUS_SPAWN_Y, 3)

                elif event.key == K_4:
                    # self.add_entity(ItemPaddleNano(BONUS_SPAWN_X, BONUS_SPAWN_Y))
                    self.spawn_item(BONUS_SPAWN_X, BONUS_SPAWN_Y, 4)

                elif event.key == K_5:
                    # self.add_entity(ItemLife(BONUS_SPAWN_X, BONUS_SPAWN_Y))
                    self.spawn_item(BONUS_SPAWN_X, BONUS_SPAWN_Y, 5)

                elif event.key == K_6:
                    # self.add_entity(ItemLife(BONUS_SPAWN_X, BONUS_SPAWN_Y))
                    self.spawn_item(BONUS_SPAWN_X, BONUS_SPAWN_Y, 6)

            elif event.type == KEYUP:
                if event.key == self.control_set[0]:
                    if self.prev_input_x < 0:
                        self.prev_input_x = 0
                    elif self.prev_input_x > 0:
                        self.paddle.vx = 1
                        self.prev_input_x = 0
                    else:
                        self.paddle.vx = 0

                elif event.key == self.control_set[2]:
                    if self.prev_input_x > 0:
                        self.prev_input_x = 0
                    elif self.prev_input_x < 0:
                        self.paddle.vx = -1
#.........这里部分代码省略.........
开发者ID:Kranek,项目名称:BlockBuster,代码行数:103,代码来源:levels.py

示例8: Window

# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import draw [as 别名]
        sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING)
        self.window = sdl2.SDL_CreateWindow(c_char_p(b"Haxball"), 100, 100, self.w, self.h, sdl2.SDL_WINDOW_SHOWN)
        self.ren = sdl2.SDL_CreateRenderer(self.window, -1, sdl2.SDL_RENDERER_ACCELERATED)

w = Window()
p = Player(w)
b = Ball(w, rad=9,x=100,y=100)
s = SpeedVector(p)
sdl2.SDL_RenderClear(w.ren)
e = sdl2.SDL_Event()
quit = False
timer = Timer()
while not quit:
    sdl2.SDL_SetRenderDrawColor(w.ren, 0,0,0,255)
    sdl2.SDL_RenderClear(w.ren)
    while(sdl2.SDL_PollEvent(byref(e))):
            if e.type == sdl2.SDL_QUIT:
                quit = True
            p.handle_event(e)
    dt = timer.tick()

    p.update(dt)
    b.update(dt)

    p.draw()
    b.draw()
    s.draw()
    p.collision(b)
    sdl2.SDL_RenderPresent(w.ren)
    sdl2.SDL_Delay(2)
开发者ID:JerzySpendel,项目名称:Ball,代码行数:32,代码来源:main.py

示例9: Game

# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import draw [as 别名]
class Game(object):
    """Main program"""

    def __init__(self):
        #Initialize pygame and window
        pygame.init()
        self.screen_width, self.screen_height = 400, 600
        self.screen = pygame.display.set_mode((self.screen_width, self.screen_height), 0, 32)
        self.screen.fill(blue)
        pygame.display.update()

        #Clock
        self.clock = pygame.time.Clock()

        #Bricks
        self.blocks = list()
        for w in range(1,self.screen_width,50):
			for h in range(23, 198, 22):
				self.blocks.append(Block(self.screen_width, self.screen_height, w, h, orange, blue_shadow))

        #Paddle
        self.paddle = Paddle(self.screen_width, self.screen_height, purple, blue_shadow)

        #Ball
        self.ball = Ball(self.screen_width, self.screen_height, green, blue_shadow)

    def update(self):
        self.clock.tick(game_speed)

        self.paddle.update()
        self.ball.update(self.paddle)

    def draw(self):
        #Redraw Background
        self.screen.fill(blue)

        for block in self.blocks:
            block.draw_shadow(self.screen)

        self.ball.draw_shadow(self.screen)
        self.paddle.draw_shadow(self.screen)

        for block in self.blocks:
            block.draw(self.screen)

        self.ball.draw(self.screen)
        self.paddle.draw(self.screen)


    def new_game(self):
        self.game_over = False
        self.round = 0

        self.play()

    def new_round(self):
        pass

    def play(self):
        while not self.game_over:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
						self.ball.serve()
                    if event.key == pygame.K_LEFT:
                        self.paddle.x_vel = -4
                    elif event.key == pygame.K_RIGHT:
                        self.paddle.x_vel = 4
                if event.type == pygame.KEYUP:
                    if event.key == pygame.K_LEFT and self.paddle.x_vel < 0:
                        self.paddle.x_vel = 0
                    if event.key == pygame.K_RIGHT and self.paddle.x_vel > 0:
                        self.paddle.x_vel = 0
            self.update()
            self.draw()
            pygame.display.update()
开发者ID:SkylerKidd,项目名称:CodeZ,代码行数:81,代码来源:game.py

示例10: __init__

# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import draw [as 别名]

#.........这里部分代码省略.........
            if pressed[K_RIGHT]:
                if self.player.move(PLAYER_SPEED) and self.state == STATES["IDLE"]:
                    self.ball.move(PLAYER_SPEED, 0)

    def updateState(self):
        if self.state == STATES["STARTED"]:  # started state - ball is moving
            self.ball.update()
            if (self.ball.y >= SCREEN_HEIGHT - BALL_RADIUS*2):
                # game over
                self.gameover()
            # check collision with blocks and if any left
            blocksLeft = False
            for obj in self.objects():
                if obj.getHealth() != 0 and not blocksLeft:
                    blocksLeft = True
                result = obj.collision(self.ball)
                if result["collided"]:
                    self.sound_brick_collide.play()
                    self.points += result["points"]
                    self.ball.bounce(0)
            if not blocksLeft:
                self.win()
            # check collision with platform
            if self.player.collision(self.ball):
                self.sound_player_collide.play()
                angleDiff = self.player.angleDiff(self.ball)
                self.ball.bounce(angleDiff)
                # print "Angle: " + str(angleDiff)
            # print self.points

    def handleMouse(self):
        self.player.update(pygame.mouse.get_pos()[0])

    def drawSprites(self):
        self.display.fill(BLACK)
        self.player.draw(self.display)
        self.ball.draw(self.display)
        for obj in self.objects():
            obj.draw(self.display)

    def drawScore(self):
        text = self.smallFont.render("Score: " + str(self.points), True, WHITE)
        self.display.blit(text, [10, 5])

    def gameover(self):
        self.sound_gameover.play()
        display = True
        self.state = STATES["GAMEOVER"]
        self.running = False
        self.display.blit(self.background, (0, 0))
        text = self.largeFont.render("GAME OVER", True, WHITE)
        self.display.blit(text, [60, 60])
        pygame.display.flip()
        while display:
            e = pygame.event.wait()
            if e.type == pygame.MOUSEBUTTONDOWN or e.type == pygame.KEYDOWN:
                display = False

    def win(self):
        self.sound_win.play()
        display = True
        self.state = STATES["GAMEOVER"]
        self.running = False
        self.display.blit(self.background, (0, 0))
        text = self.largeFont.render("You have won", True, WHITE)
        self.display.blit(text, [60, 60])
开发者ID:mshi,项目名称:bricks,代码行数:70,代码来源:game.py

示例11: Game

# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import draw [as 别名]
class Game(PygameGame):
    def __init__(self):
        width = 800
        height = 500
        fps = 40
        fullCh = 255
        bgColor = (fullCh, fullCh, fullCh)
        title = "Bouncy Bouncy Revamped"
        super().__init__(width, height, fps, title, bgColor)

    def initStyles(self):
        assert(pygame.font.get_init())
        assert(pygame.image.get_extended())
        self.font = Struct()
        textSize = 16
        self.font.text = pygame.font.SysFont("Arial", textSize)
        titleSize = 30
        self.font.title = pygame.font.SysFont("Arial", titleSize)
        self.font.titleEmph = pygame.font.SysFont("Arial", titleSize,
            bold=True, italic=True)
        self.margin = 10

    def initMaps(self):
        self.maps = Maps(self.margin + 100, self.margin,
            self.width - 2*self.margin, self.height - 2*self.margin)
        self.progress = Progress(self.maps.levels, self)

    def initMainMenu(self):
        top = 130
        left = 80
        entries = ["Play", "Level select", "Instructions"]
        actions = [self.playLevel, self.doLevelMenu, self.doHelp]
        self.mainMenu = Menu(left, top, entries, actions)

    def initLevelMenu(self):
        top = 60
        left = 130
        entries = []
        actions = []
        for i, level in enumerate(self.maps.levels):
            prevLevel = self.maps.levels[i - 1]
            if i > 0 and self.progress[prevLevel]["score"] == None:
                entries.append("Level %s    Locked" % level)
                actions.append(None)
                continue
            elif self.progress[level]["score"] == None:
                entries.append("Level %s    Unlocked" % level)
            else:
                entries.append("Level %s    Highscore: %d    Best time: %s" %
                    (level, self.progress[level]["score"],
                        Stopwatch.secToMin(self.progress[level]["time"])))
            # Locally scope level
            actions.append(lambda level=level: self.playLevel(level))
        entries += ["Return to main menu", "Clear progress"]
        actions += [self.doMainMenu, self.progress.clear]
        self.levelMenu = Menu(left, top, entries, actions)

    def initPauseMenu(self):
        def play():
            self.mode = "play"
        top = 200
        left = 300
        width = 140
        height = 80
        entries = ["Continue", "Main menu", "Turn sound off"]
        actions = [play,
                   self.doMainMenu,
                   self.toggleSound]
        self.pauseMenu = Menu(left, top, entries, actions)
        background = pygame.Surface((width + self.margin, height + self.margin))
        background.fill(self.bgColor)
        pygame.draw.rect(background, (0, 0, 0), background.get_rect(), 2)
        self.pauseMenu.background = background

    def initMenus(self):
        self.initMainMenu()
        self.initLevelMenu()
        self.initPauseMenu()

    def init(self):
        self.initStyles()
        self.initMaps()
        Terrain.initImages()
        Terrain.initSounds()
        self.initMenus()
        self.stopwatch = Stopwatch()
        self.initHelp()
        self.mode = "menu"
        self.menu = self.mainMenu

    def loadLevel(self):
        terrain, self.startpos = self.maps.load(self.level)
        self.terrain = pygame.sprite.Group(*terrain)
        self.ball = Ball(*self.startpos)
        self.score = 0
        self.stopwatch.restart()
        if self.level != "test":
            highscore = self.progress[self.level]["score"]
            bestTime = self.progress[self.level]["time"]
        else:
#.........这里部分代码省略.........
开发者ID:daniel-wen,项目名称:bouncier,代码行数:103,代码来源:main.py

示例12:

# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import draw [as 别名]
        display.fill((0, 86, 27))

        # for better code readability rend is pygame.font.Font.render
        score_image = font.render('{0} : {1}'.format(env.teamAscore,
                                                     env.teamBscore),
                                  True, (255, 255, 255))
        textpos = score_image.get_rect(centerx=WIDTH/2,
                                       centery=HEIGHT+TABLE_HEIGHT/2)
        display.blit(score_image, textpos)

        env.draw_field()
        for robot in robots:
            robot.sense()
            robot.act_handler(robot)

            robot.update()
            robot.draw()

        ball.stay_in()
        ball.draw()

        for prop in props:
            prop.draw()

        b2world.Step(TIME_STEP, 10, 10)
        pygame.display.flip()
        clock.tick(FPS)

    pygame.quit()
开发者ID:xlcteam,项目名称:py-soccersim,代码行数:31,代码来源:soccersim.py

示例13: GameStateImpl

# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import draw [as 别名]

#.........这里部分代码省略.........
                # Evaluate the 'action' key to know what to do. The action dictates what other information is required to be in the message
                if msg['payload']['action'] == 'call_function':
                    # The registered listener had better have the function call available heh... otherwise, kaboom
                    objRef = listener_obj_dict['ref']
                    fn_ptr = getattr(objRef, msg['payload']['function_name'])
                    argsDict = eval("dict({})".format(msg['payload']['params']))    # params should be a comma-separated list of key=value pairs, e.g. "a = 5, b = 3"

                    #print "function args: {}".format(argsDict)
                    if argsDict:
                        # In this particular gamestate, we want an argsdict to translate to kwargs. This is because the mixer class is written with kwargs (other classes in other gamestates use dicts, in which case, we pass in argsDict as-is))
                        fn_ptr(self, **argsDict)
                    else:
                        fn_ptr(self)

            msg = self._eventQueue.Dequeue()

    def Update(self, engineRef, dt_s, cell_size):
        # NOTE: How should we Update() and PreRender()? (Acceptable answers also include _not_distinguishing and simply making the PreRender() do what Update() does, and getting rid of Update())
        if self.vital_stats._gameState == "Playing":
            self.ball.update(dt_s, cell_size, self.vital_stats)
            self.rm.update(dt_s, cell_size, self.vital_stats)
            self.mm.update(dt_s, cell_size, self.vital_stats)

            self.updateDifficulty()

    def PreRenderScene(self, engineRef):
        self.doCollisions()
        self.enforceConstraints()

    def RenderScene(self, engineRef):
        self.surface_bg.fill((0,0,0))
        self.game_viewport.fill(self.bg_col)
        
        self.drawGrid(self.game_viewport, self.cell_size, self.game_size)
        self.rm.draw(self.game_viewport, self.cell_size)
        self.ball.draw(self.game_viewport, self.cell_size)


    def drawGrid(self, screen, cell_size, screen_size):
        for i in range(0, 63):
            color = 192, 192, 192
            pygame.draw.line(screen, color, ( (i + 1) * cell_size[0], 0                      ), ( (i + 1) * cell_size[1], screen_size[1]         ) )
            pygame.draw.line(screen, color, ( 0                     , (i + 1) * cell_size[0] ), ( screen_size[1]        , (i + 1) * cell_size[1] ) )

    def PostRenderScene(self, engineRef):
        self.updateScore()
        self.displayMessages()
        self.displayGameStats()

        #for i in range(0, ball.getGameState()):
        #    print "BallGameState:{}".format(self.ball.getGameState()),
        #print

        self.surface_bg.blit(self.game_viewport, (0, 0))    # blit the game viewport onto the bigger surface_bg

        pygame.display.flip()


    def enforceConstraints(self):
        # (e.g. constrain ball to screen space)
        for i in range(0, 2):
            if self.ball._position[i] < 0:
                self.ball._position[i] = 0
                if i == 1 and not self.vital_stats._gotCrushed:
                    self.vital_stats._gotCrushed = True
                    self.vital_stats._gameState = "Crushed"
开发者ID:masskonfuzion,项目名称:falldown_low_rez,代码行数:70,代码来源:game_state_playing.py

示例14: Breakout

# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import draw [as 别名]
class Breakout(object):
	def __init__(self):
		# Initilaize pygame and the display/window
		pygame.init()
		self.screen_width, self.screen_height = 600, 800
		self.screen = pygame.display.set_mode((self.screen_width, self.screen_height))  # , pygame.FULLSCREEN)
		pygame.display.set_caption('Breakout')
		
		# Create the game objects
		self.paddle = Paddle(self.screen_width, self.screen_height)
		self.ball = Ball(self.screen_width, self.screen_height)
		self.bricks = list()
		for i in range(0,600,60):
			for j in range(42, 211, 42):
				self.bricks.append(Brick(self.screen_width, self.screen_height, i, j))

		# Let's control the frame rate
		self.clock = pygame.time.Clock()

	def new_game(self):
		"""Start a new game of Breakout.

		Resets all game-level parameters, and starts a new round.
		"""
		self.game_over = False
		self.round = 0
		self.paddle.reset()

		self.new_round()

	def new_round(self):
		"""Start a new round in a Breakout game.

		Resets all round-level parameters, increments the round counter, and
		puts the ball on the paddle.
		"""
		self.round += 1
		self.ball.reset(self.paddle)

	def play(self):
		"""Start Breakout program.

		New game is started and game loop is entered.
		The game loop checks for events, updates all objects, and then
		draws all the objects.
		"""
		self.new_game()
		while not self.game_over:           # Game loop
			self.clock.tick(50)             # Frame rate control
			font = pygame.font.SysFont("monospace", 15)
			round_counter = font.render("Round " + str(self.round), 2, (255,255,0))
		
			for event in pygame.event.get():
				if event.type == pygame.QUIT or event.type == pygame.MOUSEBUTTONDOWN:
					self.game_over = True
					break
				if event.type == pygame.KEYDOWN:
					if event.key == pygame.K_SPACE:
						self.ball.serve()
					if event.key == pygame.K_LEFT:
						self.paddle.x_velocity = -4
					elif event.key == pygame.K_RIGHT:
						self.paddle.x_velocity = 4
					if event.key == pygame.K_a:
						self.ball.x_velocity = -3
					elif event.key == pygame.K_d:
						self.ball.x_velocity = 3

					# This starts a new round, it's only here for debugging purposes
					if event.key == pygame.K_r:
						self.new_round()
					# This starts a new game, it's only here for debugging purposes
					if event.key == pygame.K_g:
						self.new_game()
				if event.type == pygame.KEYUP:
					if event.key == pygame.K_LEFT and self.paddle.x_velocity < 0:
						self.paddle.x_velocity = 0
					if event.key == pygame.K_RIGHT and self.paddle.x_velocity > 0:
						self.paddle.x_velocity = 0
			else:
				self.paddle.update()
				contact = self.ball.update(self.paddle, self.bricks)
				for brick in self.bricks:
					if contact == brick:
						self.bricks.remove(brick)
					

				self.screen.fill((0, 0, 0))
				self.screen.blit(round_counter, (0, 0))
				ball_loc = font.render(str(self.ball.x) + "," + str(self.ball.y), 2, (255,255,0))
				self.screen.blit(ball_loc, (0, 14))
				self.paddle.draw(self.screen)
				self.ball.draw(self.screen)
				pygame.display.flip()
		
		
				for brick in self.bricks:
					brick.draw(self.screen)
				
				pygame.display.flip()
#.........这里部分代码省略.........
开发者ID:oc-cs170,项目名称:breakout,代码行数:103,代码来源:breakout.py


注:本文中的ball.Ball.draw方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。