本文整理汇总了Python中ball.Ball.update方法的典型用法代码示例。如果您正苦于以下问题:Python Ball.update方法的具体用法?Python Ball.update怎么用?Python Ball.update使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ball.Ball
的用法示例。
在下文中一共展示了Ball.update方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Game
# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import update [as 别名]
class Game():
def __init__(self):
self.window = curses.initscr()
self.window.nodelay(True)
self.window.keypad(True)
curses.cbreak()
SCRH, SCRW = self.window.getmaxyx()
self.ball = Ball(2, 2)
self.paddle1 = Paddle(0, 0, 5, [curses.KEY_LEFT, curses.KEY_RIGHT])
self.paddle2 = Paddle(0, SCRH - 1, 5, [97, 100])
self.scorex = 0
self.scorey = 0
self.score = Label(1, 1, "Score: 0:0")
def loop(self):
while True:
key = self.window.getch()
self.ball.update(self.window, [self.paddle1, self.paddle2])
self.paddle1.update(self.window, key)
self.paddle2.update(self.window, key)
self.window.clear()
draworder = sorted([self.ball, self.paddle1, self.paddle2, self.score], key=lambda o: o.x)
for o in draworder:
o.draw(self.window)
self.window.refresh()
curses.flushinp()
curses.napms(1000 / TICKRATE)
示例2: add_ball
# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import update [as 别名]
def add_ball(self, release_instantly=False):
ball = Ball(self.ball_image, (230+82, 625), Vector(-3,-5), self.is_time_distortion_field_active, attached=True, attach_pos=self.balls_on_paddle)
self.balls.add(ball)
self.balls_on_paddle += 1
if release_instantly:
ball.update(1, self.paddle, self.balls, self.blocks, self.invulnerable_blocks)
self.release_a_ball()
示例3: start
# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import update [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)
示例4: Window
# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import update [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)
示例5: Match
# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import update [as 别名]
class Match(object):
snd_whistle = pygame.mixer.Sound("data/sound/etw/fischiolungo.wav")
#TODO: add field choice
def __init__(self,teamA,teamB):
self.goal_image=pygame.image.load("data/goal.png")
self.start_image=pygame.image.load("data/start.png")
self.message_drawing_time=50
self.message_image=self.start_image
self.clock_image=pygame.image.load("data/clock.png")
self.is_finished=False
self.teamA_filename=teamA
self.teamB_filename=teamB
self.match_time=0
self.human_players=[-1,0,0] #max two players, player num 0 does not exist
self.pause=False
self.ball=Ball()
self.player_list=[]
self.team={}#
#read xml file to get colors !
self.team[-1]=Team(self.teamA_filename)
self.team[1]=Team(self.teamB_filename)
def init(self,nbr_players_human_teamA,nbr_players_teamA,nbr_players_human_teamB,nbr_players_teamB,difficulty=8,length=60):
Player_CPU.difficulty=difficulty
Player_GK.difficulty=difficulty
self.goal_image=pygame.image.load("data/goal.png")
self.start_image=pygame.image.load("data/start.png")
self.message_drawing_time=50
self.message_image=self.start_image
self.clock_image=pygame.image.load("data/clock.png")
self.is_finished=False
self.match_time=length
self.human_players=[-1,0,0] #max two players, player num 0 does not exist
self.pause=False
self.ball=Ball()
self.player_list=[]
human_players_teamA=[]
human_players_teamB=[]
if (nbr_players_human_teamA>0):
human_players_teamA.append( 1+len(human_players_teamA)+len(human_players_teamB) )
if (nbr_players_human_teamA>1):
human_players_teamA.append( 1+len(human_players_teamA)+len(human_players_teamB) )
if (nbr_players_human_teamB>0):
human_players_teamB.append( 1+len(human_players_teamA)+len(human_players_teamB) )
if (nbr_players_human_teamB>1):
human_players_teamB.append( 1+len(human_players_teamA)+len(human_players_teamB) )
self.field=Field(self.team[-1].top_color,self.team[-1].bottom_color,self.team[1].top_color,self.team[1].bottom_color)
self.cam=Camera(self.field)
self.team[-1].create_from_xml(-1,nbr_players_teamA,human_players_teamA,self)
self.player_list+=self.team[-1].players
self.team[1].create_from_xml(1,nbr_players_teamB,human_players_teamB,self)
self.player_list+=self.team[1].players
print("Match starts")
def update(self):
Inputs.readkeys()#read all the actual keys
if (Inputs.player_just_Start[1] or Inputs.player_just_Start[2]):
self.pause=not self.pause
if (self.match_time<=0):
self.is_finished=True
else:
if (configuration["sound"]=="on"):
Match.snd_whistle.play()
if (not self.pause):
if (self.message_drawing_time<10):
if (self.message_drawing_time>0):
self.message_drawing_time-=1*configuration["delta_time"]
if (self.message_drawing_time>5)and(self.message_image==self.start_image):#kick off
if (configuration["sound"]=="on"):
Match.snd_whistle.play()
self.message_drawing_time=5
if (self.match_time>0):#when time is out, players stop
self.match_time-=1.0/30*configuration["delta_time"] #30 FPS
self.team[-1].update(self)
self.team[1].update(self)
if (-1<self.match_time<0):
if (configuration["sound"]=="on"):
Match.snd_whistle.play()
self.ball.update(self)
else:
self.message_drawing_time-=1*configuration["delta_time"]
#camera moves even if there is a message
if (self.ball.owner==0):
self.cam.aim_to([self.ball.pos[0],self.ball.pos[1],self.ball.pos[2]/2],0,50)
#.........这里部分代码省略.........
示例6: IceBlocks
# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import update [as 别名]
class IceBlocks(cocos.layer.ColorLayer):
is_event_handler = True
keys_pressed = {}
def __init__(self):
super(IceBlocks, self).__init__(*BG_COLOR, a=255)
self.keys_pressed = []
self.current_lives = LIVES
self.level = BlockFactory().get_level(0)
self.schedule(self.update)
self.peddle = Peddle()
self.ball = Ball()
self.add(self.peddle, z=1)
self.add(self.ball, z=1)
self.draw_blocks()
self.collman = cm.CollisionManagerGrid(0, WINDOW_W,
0, WINDOW_H,
self.width, self.height)
self.draw_lives()
def restart_game(self):
self.remove(self.message)
self.current_lives = LIVES
self.level = BlockFactory().get_level(0)
self.draw_blocks()
self.draw_lives()
self.ball.update_position((self.peddle.position[0] +
self.peddle.width / 2, self.peddle.height))
self.resume_scheduler()
def blocks_remaining(self):
count = 0
for z, node in self.children:
if isinstance(node, Block):
count += 1
return count
def level_up(self):
self.pause_scheduler()
self.ball.update_position((self.peddle.position[0]
+ self.peddle.width
/ 2, self.peddle.height))
try:
self.level = BlockFactory().get_level(self.level.level + 1)
except Exception as ex:
message, code = ex.args
if code == 0:
self.message = MessageLayer()
self.message.show_message(message, self.restart_game)
self.add(self.message)
return
self.draw_blocks()
self.message = MessageLayer()
self.message.show_message('Level ' + str(self.level.level
+ 1), self.resume_scheduler)
self.add(self.message)
#self.draw_blocks()
#self.resume_scheduler()
def update(self, dt):
if self.current_lives > -1:
self.peddle.update(self.keys_pressed)
result = self.ball.update(self.peddle)
if result == -1:
self.current_lives -= 1
self.update_lives()
#self.pause_scheduler()
self.collman.clear()
for z, node in self.children:
if isinstance(node, Block):
self.collman.add(node)
for obj in self.collman.objs_colliding(self.ball):
ball_rcornerx = math.ceil(self.ball.position[0] + self.ball.width)
ball_rcornery = math.ceil(self.ball.position[1] + self.ball.width)
ball_lcornerx = math.ceil(self.ball.position[0])
ball_lcornery = math.ceil(self.ball.position[1])
block_lcornerx = math.ceil(obj.position[0])
block_lcornery = math.ceil(obj.position[1])
block_rcornerx = math.ceil(obj.position[0] + obj.width)
block_rcornery = math.ceil(obj.position[1] + obj.width)
if ball_rcornerx <= block_lcornerx :
if ball_rcornerx == block_lcornerx and (block_lcornery == (ball_rcornery+self.ball.height) or (block_lcornery+obj.height) == ball_rcornery):
self.ball.dx = self.ball.dx * -1
self.ball.dy = self.ball.dy * -1
else :
self.ball.dx = self.ball.dx * -1
elif ball_lcornerx >= block_rcornerx :
if ball_lcornerx == block_rcornerx and (block_rcornery == (ball_lcornery+self.ball.height) or (block_rcornery+obj.height) == ball_lcornery) :
self.ball.dx = self.ball.dx * -1
self.ball.dy = self.ball.dy * -1
#.........这里部分代码省略.........
示例7: Game
# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import update [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()
示例8: __init__
# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import update [as 别名]
class Game:
# initialize resource files
def __init__(self):
# initialize pygame stuff
pygame.init()
pygame.mixer.init()
self.sound_player_collide = pygame.mixer.Sound(SOUND_PLAYER_COLLIDE)
self.sound_brick_collide = pygame.mixer.Sound(SOUND_BRICK_COLLIDE)
self.sound_start = pygame.mixer.Sound(SOUND_GAME_START)
self.sound_gameover = pygame.mixer.Sound(SOUND_GAME_OVER)
self.sound_win = pygame.mixer.Sound(SOUND_WIN)
self.display = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
pygame.display.set_caption(NAME + " v" + VERSION)
self.clock = pygame.time.Clock()
# initialize objects
self.player = Player(SCREEN_WIDTH/2)
self.ball = Ball(self.player.posX(), self.player.posY())
self.grid = [[None for i in xrange(GRID_WIDTH)] for j in xrange(GRID_HEIGHT)]
self.running = False
self.state = STATES["IDLE"]
self.points = 0
self.background = pygame.image.load(IMAGE_BACKGROUND).convert_alpha()
self.font = pygame.font.Font(None, 36)
self.smallFont = pygame.font.Font(None, 16)
self.largeFont = pygame.font.Font(None, 64)
self.mouseMode = False
# returns list of all elements in grid that are non-empty
def objects(self):
ret = []
for i in xrange(len(self.grid)):
ret += filter(lambda x: x is not None, self.grid[i])
return ret
# Generate the bricks. Fill the grid for now. Todo: randomly generate or load from file
def generateStage(self):
for row in xrange(GRID_HEIGHT):
for col in xrange(GRID_WIDTH):
# randomize chance for "special" brick
rand = random.randint(1, BRICK_RANDOM_CHANCE)
if rand == 1: # 1/10 for indestructable
self.grid[row][col] = Brick.CreateBrick(col, row, 0)
elif rand <= 5: # 1/2 for level 1
self.grid[row][col] = Brick.CreateBrick(col, row, 1)
else: # remaining is split evenly
self.grid[row][col] = Brick.CreateBrick(col, row, rand - (BRICK_RANDOM_CHANCE - MAX_BRICK_POWER))
def handleEvents(self, event):
if event.type == pygame.QUIT:
self.running = False
elif event.type == MOUSEBUTTONDOWN:
self.state = STATES["STARTED"]
self.mouseMode = True
elif event.type == KEYDOWN:
# handle keyboard inputs
if event.key == K_ESCAPE:
# self.state = STATES["MENU"]
self.running = False
elif event.key == K_SPACE:
self.state = STATES["STARTED"]
def handleKeyInput(self):
pressed = pygame.key.get_pressed()
if self.state == STATES["STARTED"] or self.state == STATES["IDLE"]:
if pressed[K_LEFT]:
if self.player.move(-PLAYER_SPEED) and self.state == STATES["IDLE"]:
self.ball.move(-PLAYER_SPEED, 0)
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)
#.........这里部分代码省略.........
示例9: Breakout
# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import update [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()
#.........这里部分代码省略.........
示例10: update
# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import update [as 别名]
def update(self):
Ball.update(self)
self.randomize_color()
示例11: str
# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import update [as 别名]
elif event.key == K_DOWN:
paddle2.change_y += 6
elif event.type == KEYUP:
if event.key == K_w:
paddle1.change_y += 6
elif event.key == K_s:
paddle1.change_y -= 6
elif event.key == K_UP:
paddle2.change_y += 6
elif event.key == K_DOWN:
paddle2.change_y -= 6
# Updates the game objects
for paddle in paddle_list:
paddle.update()
ball.update()
if ball.rect.right >= constants.screen_width or ball.rect.x <= 0:
if ball.change_x >= 0:
paddle1.score += 1
else:
paddle2.score += 1
ball.change_x = 6
ball.change_y = 6
ball.rect.topleft = (random.randint(0, 800), random.randint(0, 600))
if paddle1.score >= 10 or paddle2.score >= 10:
scoreBoard.update(str(paddle1.score) + " | " + str(paddle2.score))
text_functions.showText("Game Over", (constants.screen_width/2, constants.screen_height/2), screen)
pygame.time.wait(500)
pygame.display.update()
terminate()
scoreBoard.update(str(paddle1.score) + " | " + str(paddle2.score))
示例12:
# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import update [as 别名]
#ball - paddle collision detection
if ( rightPaddle.left() < (ball.x + ball.radius) and rightPaddle.right() > (ball.x - ball.radius) ) and ( rightPaddle.top() < (ball.y + ball.radius) and rightPaddle.bottom() > (ball.y - ball.radius) ):
ball.bounce( rightPaddle.top(), rightPaddle.bottom(), rightPaddle.height )
if ( leftPaddle.left() < (ball.x + ball.radius) and leftPaddle.right() > (ball.x - ball.radius) ) and ( leftPaddle.top() < (ball.y + ball.radius) and leftPaddle.bottom() > (ball.y - ball.radius) ):
ball.bounce( leftPaddle.top(), leftPaddle.bottom(), leftPaddle.height )
#render half-field line
pygame.draw.line( SURFACE, WHITE, ( WIDTH/2, 0 ), ( WIDTH/2, HEIGHT ) )
#render the paddles
leftPaddle.render(SURFACE)
rightPaddle.render(SURFACE)
#render the ball
ball.update( ball.xspeed, ball.yspeed )
if scored:
pygame.time.wait(2000)
scored = False
ball.render(SURFACE)
#display players score
rightScoreDisplay = font.render( "{0}".format(leftScore), 1, WHITE )
leftScoreDisplay = font.render( "{0}".format(rightScore), 1, WHITE )
SURFACE.blit( rightScoreDisplay, ( 450, 50 ) )
SURFACE.blit( leftScoreDisplay, ( 780, 50 ) )
clock.tick(FPS)
pygame.display.update()
###########end of game loop#############
示例13: __init__
# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import update [as 别名]
class Pong:
def __init__(self, width=640, height=480, title="Prog Workshop - Pong!"):
pygame.init()
# Sets key repeat to a max of once every 5 ms
#pygame.key.set_repeat(5, 5)
self.screen = pygame.display.set_mode((width, height))
pygame.display.set_caption(title)
self.clock = pygame.time.Clock()
self.screen = pygame.display.get_surface()
self._running = True
self.player1 = Paddle(0,0,20,100,self)
self.player2 = Paddle(width-20,0,20,100,self)
self.ball = Ball(width/2,height/2,20,20,self)
self.ball.setSpeed(random.random()*14-7, random.random()*14-7)
self.balls = []
self.score = Scoreboard(self, 36)
def handle_event(self, event):
if event.type == pygame.QUIT:
self._running = False
if event.type == pygame.MOUSEBUTTONDOWN:
ball = Ball(self.screen.get_width()/2,self.screen.get_height()/2,20,20,self)
ball.setSpeed(random.random()*14-7, random.random()*14-7)
self.balls.append(ball)
def update_game(self):
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_UP]:
self.player2.moveUp()
if keys_pressed[pygame.K_DOWN]:
self.player2.moveDown()
if keys_pressed[pygame.K_w]:
self.player1.moveUp()
if keys_pressed[pygame.K_s]:
self.player1.moveDown()
self.ball.update()
for ball in self.balls:
ball.update()
def render(self):
background = pygame.Surface(self.screen.get_size()).convert()
background.fill((250, 250, 250))
self.screen.blit(background, (0,0))
self.player1.render()
self.player2.render()
self.ball.render()
for ball in self.balls:
ball.render()
self.score.renderScore()
pygame.display.flip()
def start(self):
while self._running:
self.clock.tick(60) # Limit to 60 fps
# Handle events
for event in pygame.event.get():
self.handle_event(event)
# Handle game logic
self.update_game()
# Handle rendering
self.render()
pygame.quit()
示例14: Game
# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import update [as 别名]
class Game():
entities = None
blocks = None
player = None
items = None
sound_factory = None
def __init__(self, window_width, window_height):
self.frame_update = 0
self.second_count_update = time.time()
self.frame_draw = 0
self.second_count_draw = time.time()
#Screen settings
self.screen = pygame.display.set_mode((window_width, window_height), FLAGS, DEPTH)
pygame.display.set_caption("BREAKOUT ULTIMATE")
#Background
self.background = pygame.Surface((pygame.display.Info().current_w, pygame.display.Info().current_h))
self.background.convert()
self.background.fill(pygame.Color("#000000"))
#Font
pygame.font.init()
font_size = 16
self.fontObj = pygame.font.SysFont("courier", font_size)
#Entities list (player, balls, blocks)
self.entities = pygame.sprite.Group()
self.items = pygame.sprite.Group()
self.blocks = pygame.sprite.Group()
self.player = Player()
self.ball = Ball()
self.entities.add(self.player)
self.entities.add(self.ball)
self.sound_factory = Sound()
self.menu_obj = Menu()
#Calculating the space between each block
horizontal_spacing = 50 * (pygame.display.Info().current_w * 1.0 / 800)
vertical_spacing = 40 * (pygame.display.Info().current_h * 1.0 / 640)
for column in range (0, 14):
for row in range (0, 5):
new_block = Block(column * horizontal_spacing + (60 * (pygame.display.Info().current_w * 1.0 / 800)), row * vertical_spacing + 50, pygame.display.Info().current_w, pygame.display.Info().current_h)
self.entities.add(new_block)
self.blocks.add(new_block)
#Game states
self.game_over = False
self.menu = True
self.pause = True
def update_stuff(self):
self.frame_update += 1
if time.time() - self.second_count_update >= 1:
self.second_count_update = time.time()
print self.frame_update, "updates per second"
self.frame_update = 0
if self.menu:
menu_choice = self.menu_obj.update(self.menu, self)
if menu_choice == "Play":
self.menu = False
#if menu_choice == "Options":
# self.option_menu = True
#Keyboard and mouse events
for e in pygame.event.get():
#Clicking the cross to quit
if e.type == pygame.QUIT:
raise SystemExit, "QUIT"
#All the input is sent to the Player object
if (e.type == pygame.KEYDOWN or e.type == pygame.KEYUP) and not self.menu:
self.player.input(e.type, e.key)
if e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE:
raise SystemExit, "ESCAPE"
#Pressing V switch between 2 resolution. We could add a menu to choose the resolution later
if e.type == pygame.KEYDOWN and e.key == pygame.K_v:
if pygame.display.Info().current_w == 1200:
self.__init__(800, 640)
elif pygame.display.Info().current_w == 800:
self.__init__(1200, 960)
#pressing B mute the sound
if e.type == pygame.KEYDOWN and e.key == pygame.K_n:
self.sound_factory.change_volume()
#If player has no life left, he can press SPACE to restart
if self.game_over and e.type == pygame.KEYDOWN and e.key == pygame.K_SPACE:
self.__init__(pygame.display.Info().current_w, pygame.display.Info().current_h)
#.........这里部分代码省略.........
示例15: GameStateImpl
# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import update [as 别名]
#.........这里部分代码省略.........
# Transition to the state that allows the user to enter a new high score. NOTE We may need to keep that in this data scope, rather than switching to a stand-alone state)
engineRef.changeState( game_state_new_high_score.GameStateImpl.Instance(), takeWith=self.vital_stats._newHighScore )
else:
engineRef.changeState( game_state_main_menu.GameStateImpl.Instance() )
def ProcessCommands(self, engineRef):
# TODO maybe put this command extraction logic into a function at the application class level (or base gamestate level). We're reusing the logic in every gamestate instance
msg = self._eventQueue.Dequeue()
while msg:
#print "DEBUG Dequeued message: {}".format(msg)
topic = msg['topic']
for listener_obj_dict in self._eventQueue.RegisteredListeners(topic):
#print "DEBUG Registered Listener {} processing message {}".format(listener_obj_dict['name'], msg['payload'])
# 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