本文整理汇总了Python中hud.Hud.draw方法的典型用法代码示例。如果您正苦于以下问题:Python Hud.draw方法的具体用法?Python Hud.draw怎么用?Python Hud.draw使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类hud.Hud
的用法示例。
在下文中一共展示了Hud.draw方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: range
# 需要导入模块: from hud import Hud [as 别名]
# 或者: from hud.Hud import draw [as 别名]
#.........这里部分代码省略.........
self.state = MonorailGame.STATE_STATS
self.mouse_timeout = MonorailGame.MOUSE_TIMEOUT
self.music_man.stop()
if indev.mouse.has_moved():
self.mouse_timeout = MonorailGame.MOUSE_TIMEOUT
else:
self.mouse_timeout -= 1
elif self.state == MonorailGame.STATE_STATS:
if self.hud.is_ready():
if not self.game_data.is_single_player():
self.game_data.add_total_scores( self.playfield )
self.hud.start_total_screen()
self.state = MonorailGame.STATE_TOTAL
else:
if self.scenario.has_won():
self.state = MonorailGame.STATE_DONE
else:
self.restart( self.game_data )
return
elif self.state == MonorailGame.STATE_TOTAL:
if self.hud.is_ready():
self.state = MonorailGame.STATE_DONE
elif self.state == MonorailGame.STATE_MENU:
pass
self.hud.game_tick( indev )
self.music_man.game_tick()
SingleSwitch.tick( indev, None )
if indev.key.went_down( K_ESCAPE ) or \
self.hud.menu_btn.went_down() or \
SingleSwitch.esc_went_down:
resman.get("gui.paper_sound").play()
self.ingame_menu = IngameMenu(self.game_data.is_single_player(), self.game_data)
elif self.ingame_menu is not None: # Ingame Menu
SingleSwitch.feed_keys( indev )
self.gui_state.update( indev, self.ingame_menu )
self.ingame_menu.tick( indev, self.gui_state )
if self.ingame_menu.is_done():
if self.ingame_menu.to_menu:
self.music_man.stop()
self.state = MonorailGame.STATE_MENU
elif self.ingame_menu.should_quit:
self.music_man.stop()
self.state = MonorailGame.STATE_QUIT
elif self.ingame_menu.to_next_level:
self.music_man.stop()
self.state = MonorailGame.STATE_DONE
self.ingame_menu = None
self.mouse_timeout = MonorailGame.MOUSE_TIMEOUT
# if indev.key.went_down( K_p ):
# self.is_paused = not self.is_paused
event.Event.update()
# for debugging
if self.is_paused:
self.controller.game_tick( indev )
def draw( self, surface, interpol, time_sec ):
#surface.fill( (0,0,0) )
frame = Frame( surface, time_sec, interpol )
if self.ingame_menu is not None or self.is_paused or\
self.state not in [MonorailGame.STATE_BEGIN, MonorailGame.STATE_GAME]:
frame.interpol = 0.0
frame.draw( self.playfield )
frame.draw( self.controller )
self.hud.draw( frame )
if self.ingame_menu is not None:
self.ingame_menu.draw( surface )
frame.draw( event.Event.instance )
def draw_mouse( self, surface, interpol, time_sec ):
if self.mouse_timeout > 0:
x, y = pygame.mouse.get_pos()
resman.get("gui_surf").draw( surface, Vec2D(x, y), (0,0,32,32) )
def mouse_down( self, button ):
pass
def is_done( self ):
return self.state == MonorailGame.STATE_DONE \
or self.state == MonorailGame.STATE_MENU \
or self.state == MonorailGame.STATE_QUIT
示例2: GameScreen
# 需要导入模块: from hud import Hud [as 别名]
# 或者: from hud.Hud import draw [as 别名]
#.........这里部分代码省略.........
else:
self.player.weapons.apply(st, self.player)
self.map.serverupdate(itemid, spawn)
elif typ == proto.chat:
ind, msg = data
if ind == self.player.id:
name = self.player.name
color = self.player.color
elif ind in self.players:
name = self.players[ind].name
color = self.players[ind].color
else:
name = self.specs[ind].name
color = self.specs[ind].color
#chatdata = ' '.join((name + ':', '\t', msg))
chatdata = (name, color, msg)
self.hud.update_prop(chat=chatdata)
def send_to_client(self, dt):
temp_input = proto.Input()
self.time += int(dt * 1000000)
temp_input.CopyFrom(self.player.input)
c_move = move(self.time, temp_input, self.player.state.copy())
try:
self.moves[self.index[0]] = c_move
except IndexError:
self.moves.append(c_move)
self.moves.advance(self.index)
self.send_message('input', (self.player.input, self.time))
def spec_send(self, dt):
self.send_message('input', (proto.Input(), self.time))
def draw(self):
self.on_draw()
def on_connect(self, msg):
ind, mapname, name = msg
self.player.get_id(ind, name)
self.map = Map(mapname)
print 'connected with id: ' + str(self.player.id)
#self.send_message('input', (self.player.input, 1337))
self.gs_view.init_self(ind)
self.trans_to_spec()
def try_join(self):
msg = proto.Message()
msg.type = proto.stateUpdate
plr = proto.Player()
plr.id = self.player.id
msg.player.CopyFrom(plr)
if self.isSpec:
msg.gameState = proto.wantsJoin
else:
msg.gameState = proto.goesSpec
self.send_message('other', msg)
def ready_up(self):
msg = proto.Message()
msg.type = proto.stateUpdate
plr = proto.Player()
plr.id = self.player.id
msg.player.CopyFrom(plr)
msg.gameState = proto.isReady
self.send_message('other', msg)
示例3: run
# 需要导入模块: from hud import Hud [as 别名]
# 或者: from hud.Hud import draw [as 别名]
def run():
pygame.init()
random.seed()
display_size = 800, 600
viewport_size = display_size[0], 600
black = 0, 0, 0
red = 255, 70, 70
green = 70, 255, 70
blue = 70, 70, 255
white = 255, 255, 255
l_green = 50, 255, 0
screen = pygame.display.set_mode(display_size)
screen.fill(black)
clock = Clock(readonly=False)
dbman = DBManager()
dbman.import_db("./db")
gfxman = GfxManager()
gfxman.import_gfx(dbman.get(), "./gfx")
stagemanager = StageManager()
stagemanager.import_stages("./stages")
stages = stagemanager.get()
groupmanager = GroupManager()
g_draw = groupmanager.add("draw", "OrderedUpdates")
g_ship = groupmanager.add("ship")
g_enemies = groupmanager.add("enemies")
g_enemy_projectiles = groupmanager.add("enemy_projectiles")
g_player_projectiles = groupmanager.add("player_projectiles")
g_beams = groupmanager.add("beams")
g_explosions = groupmanager.add("explosions")
g_shields = groupmanager.add("shields")
g_bonuses = groupmanager.add("bonuses")
hud = Hud(viewport_size)
g_enemies.add(Obstacle((60, 30)))
g_enemies.add(MovingObstacle((160, 80)))
g_bonuses.add(RechargeBonus((300, 200)))
g_bonuses.add(SuperShieldBonus((500, 300)))
g_bonuses.add(ShieldUpgradeBonus((500, 500)))
g_bonuses.add(ShieldUpgradeBonus((300, 500)))
ship = ref(PlayerShip((175, viewport_size[1] - 60), g_ship))
hud.setup_connections(ship())
back = SpaceBackground(viewport_size)
for stage_name in sorted(stages.keys()):
stage_clock = 0
while True:
for spawn_time in stages[stage_name]["spawn"]:
if spawn_time <= stage_clock:
while stages[stage_name]["spawn"][spawn_time]:
spawn = stages[stage_name]["spawn"][spawn_time].pop()
pos = spawn["x"], spawn["y"]
object_cls = eval(spawn["object_cls_name"])
if spawn["object_base_cls_name"]:
if spawn["object_base_cls_name"] == "Projectile":
if not spawn.has_key("object_params"):
raise ValueError, "Params for projectile '%s' in stage %s \
not set" % (
spawn["object_cls_name"],
stage_name,
)
if not spawn["object_params"].has_key("dir"):
raise ValueError, "Invalid 'dir' for projectile '%s' in \
stage %s" % (
spawn["object_cls_name"],
stage_name,
)
if not spawn["object_params"].has_key("collision_group"):
raise ValueError, "Invalid 'collision_group' for projectile \
'%s' in stage %s" % (
spawn["object_cls_name"],
stage_name,
)
params = spawn["object_params"]
dir = params["dir"]
g_coll = groupmanager.get(params["collision_group"])
object = object_cls(pos, dir, g_coll)
elif spawn["object_base_cls_name"] == "Bonus":
pass
else:
raise ValueError, "Invalid value '%s' for attrubite \
'object_base_cls_name' in stage %s" % (
#.........这里部分代码省略.........
示例4: Game
# 需要导入模块: from hud import Hud [as 别名]
# 或者: from hud.Hud import draw [as 别名]
#.........这里部分代码省略.........
self.camShakeFactor = self.camShakeFactor - ( self.camShakeFactor * self.camShakeDecayFactor )
if ( self.camShakeFactor < 1 ):
self.camShakeFactor = 0
self.cam.shake(random.random() * self.camShakeFactor, random.random() * self.camShakeFactor)
#Player boost effect
if ( self.player.boosting ):
self.makeLineBurst( self.player.rect.centerx, self.player.rect.centery, -self.player.ang * 180 / math.pi + 180, 30, 3, 30, (255,255,155), 0.1, True )
self.makeLineBurst( self.player.rect.centerx, self.player.rect.centery, -self.player.ang * 180 / math.pi + 180, 30, 3, 30, (255,0,0), 0.1, True )
if ( self.player.thrusting ):
self.makeLineBurst( self.player.rect.centerx, self.player.rect.centery, -self.player.ang * 180 / math.pi + 180, 20, 2, 20, (255,255,255), 0.1, True )
#Update Score in HUD
self.hud.updateScore(self.score.getTotal())
#Death
if self.player.dead and self.player.canMakeDeadEffect:
self.player.canMakeDeadEffect = False
self.shakeScreen( 64 )
self.soundCon.playDeathSound()
self.deathSound.play()
#self.makeExplosion( 500, 500, "Images/Effects/Explosion2Spr.png", 200, 200, 8, 8, True)
self.makeLineBurst( self.player.rect.centerx, self.player.rect.centery, 0, 360, 200, 30, (255,255,0), 0.1, True )
self.makeLineBurst( self.player.rect.centerx, self.player.rect.centery, 0, 360, 200, 30, (255,0,0), 0.1, True )
self.makeLineBurst( self.player.rect.centerx, self.player.rect.centery, 0, 360, 100, 30, (255,155,0), 0.05, True )
self.makeLineBurst( self.player.rect.centerx, self.player.rect.centery, 0, 360, 100, 40, (255,0,0), 0.05, True )
self.makeLineBurst( self.player.rect.centerx, self.player.rect.centery, 0, 360, 100, 50, (255,255,255), 0.05, True )
self.player.numLives -= 1
if ( self.player.numLives <= 0 ):
self.doFade = True
self.player.currentDeadTime = 30
if ( self.player.reformEffect ):
self.player.reformEffect = False;
self.spawnSound.play()
self.makeLineBurst( self.player.rect.centerx, self.player.rect.centery, 0, 360, 150, 15, (255,255,255), 0.1, False )
self.makeLineBurst( self.player.rect.centerx, self.player.rect.centery, 0, 360, 150, 30, (255,255,255), 0.1, False )
self.makeLineBurst( self.player.rect.centerx, self.player.rect.centery, 0, 360, 150, 50, (255,255,255), 0.1, False )
self.timer = pygame.time.get_ticks()
def shakeScreen(self, magnitude):
self.camShakeFactor = magnitude #Magnitude of shake
def makeLineBurst(self, x, y, direction, spread, count, maxSpeed, color, lerpPercent, doRandom):
newBurst = LineBurst( x, y, direction, spread, count, maxSpeed, color, lerpPercent, doRandom )
self.effectInstances.append( newBurst )
def makeExplosion(self, x, y, imagePath, imageWidth, imageHeight, numFrames, imageSpeed, doLoop):
newAnim = EffectAnimation( x, y, imagePath, imageWidth, imageHeight, numFrames, imageSpeed, doLoop )
self.effectInstances.append( newAnim )
def spawnEnemy(self):
if ( len(self.enemyList) == 0 ):
for i in range( self.baseNumEnemies ):
self.enemyList.append(AI(self.player, self.cam, self))
else:
self.enemyList.append(AI(self.player, self.cam, self))
def draw(self):
"""draw the gameworld"""
self.screen.fill((0,0,0))
if self.inMenu:
#calls the menu's draw function
self.menu.draw(self.screen)
else:
#Draw the regular game
backRect = self.backgroundImgRect.move(-self.cam.rect.x + self.camBorder / 2, -self.cam.rect.y + self.camBorder / 2)
self.screen.blit(self.backgroundImg, backRect)
self.player.draw( self.screen, self.cam )
#Enemy draw
for tempEnemy in self.enemyList:
tempEnemy.draw(self.screen, self.cam)
#Effect draw
for effect in self.effectInstances:
effect.draw(self.screen, self.cam)
#HUD draw
self.hud.draw(self.screen)
#Game Over fade
if self.doFade:
self.fadeSurfaceAlpha += self.fadeSurfaceRate
if ( self.fadeSurfaceAlpha >= 255 ):
self.inMenu = True
pygame.mixer.stop()
pygame.mixer.music.stop()
self.restartGame = True
else:
self.fadeSurface.fill((0,0,0,self.fadeSurfaceAlpha))
self.fadeSurface.set_alpha( self.fadeSurfaceAlpha )
#tempRect = self.fadeRect.move(-self.cam.rect.x, -self.cam.rect.y)
self.fadeSurface.blit(self.fadeImage, (0,0))
self.screen.blit(self.fadeSurface,(-self.cam.rect.x + self.cam.rect.left,-self.cam.rect.y + self.cam.rect.top))
示例5: playGame
# 需要导入模块: from hud import Hud [as 别名]
# 或者: from hud.Hud import draw [as 别名]
def playGame(character1, character2):
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load("Sound/07 - The Raising Fighting Spirit.ogg") #Background music "The Rising Fighting Spirit":http://downloads.khinsider.com/game-soundtracks/album/naruto-original-soundtrack-1
pygame.mixer.music.play(-1)
displaysurf = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
player1=Character(PLAYER1_CONTROLS, IMAGES[character1], SOUNDS[character1], PLAYER1_POSITION)
player2=Character(PLAYER2_CONTROLS, IMAGES[character2], SOUNDS[character2], PLAYER2_POSITION)
HUD1_IMAGES=HUD_IMAGES.copy()
HUD1_IMAGES["icon"]=IMAGES[character1]["icon"]
HUD2_IMAGES=HUD_IMAGES.copy()
HUD2_IMAGES["icon"]=IMAGES[character2]["icon"]
player1_hud=Hud(HUD1_IMAGES, LEFT_HUD_POSITION)
player2_hud=Hud(HUD2_IMAGES, RIGHT_HUD_POSITION)
player2_hud.flip()
background=load_image("Background/training_background.png") #http://spritedatabase.net/game/1889
background=pygame.transform.scale(background, (WIDTH, HEIGHT))
player1_wins=load_image("Background/player1wins.png") #Used the folowing website to generate the win signs: http://www.dafont.com/ninja-naruto.font
player2_wins=load_image("Background/player2wins.png")
pygame.display.set_caption('Pybrawl')
game_over=False
while True: # main game loop
displaysurf.blit(background, (0,0))
clock.tick(FPS)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN and event.key == K_RETURN and game_over:
return
if player1.health==0:
game_over=True
pygame.mixer.music.stop()
displaysurf.blit(player2_wins, (172, 200))
if player2.health==0:
game_over=True
pygame.mixer.music.stop()
displaysurf.blit(player1_wins, (172, 200))
keys_status=pygame.key.get_pressed()
if game_over:
keys_status=[False for i in keys_status]
player1.update(keys_status)
player2.update(keys_status)
collide(player1, player2)
keep_inside(player1)
keep_inside(player2)
if player1.rect.centerx < player2.rect.centerx:
player1.direction="right"
player2.direction="left"
else:
player1.direction="left"
player2.direction="right"
player1_hud.update(player1.health/player1.max_health,
player1.mana/player1.max_mana)
player2_hud.update(player2.health/player2.max_health,
player2.mana/player2.max_mana)
player1.draw(displaysurf)
player2.draw(displaysurf)
player1_hud.draw(displaysurf)
player2_hud.draw(displaysurf)
pygame.display.update()
示例6: Main
# 需要导入模块: from hud import Hud [as 别名]
# 或者: from hud.Hud import draw [as 别名]
class Main(object):
def __init__(self):
self.clock = pygame.time.Clock()
pygame.mouse.set_visible(0)
self.surface = main_surface
self.deadline = 120 # for monster :))
self.font = pygame.font.Font(None, 30)
self.background = load_image('background.png')
pygame.mixer.music.load(load_sound('background.ogg'))
self.brushing()
self.level_formula = lambda x: (x + random.randint(5, x + 5))
self.MAIN_LOOP = self.MENU_LOOP = self.OPTIONS_LOOP = False
pygame.mixer.music.play(-1, 0.0)
self.show_menu()
self.start()
def brushing(self):
self.weapons = []
self.spiders = []
self.effects = []
self.dead_spiders = []
self.hud = Hud()
self.player = Player()
self.bonus_time = 0
self.bonus_timmer = 30
self.double_bonus = False
self.tripple_bonus = False
self.level = 0
def check_bonus_time(self):
if self.double_bonus or self.tripple_bonus:
if time.time() - self.bonus_time >= self.bonus_timmer:
self.bonus_time = 0
self.double_bonus = False
self.tripple_bonus = False
def event(self):
for event in pygame.event.get():
if event.type == QUIT:
self.MAIN_LOOP = False
elif event.type == KEYUP:
if event.key == K_LCTRL:
if self.tripple_bonus:
self.weapons.\
append(WhiteSkull(self.player.rect.centerx - 20, self.player.rect.centery + 20, self.player.direction))
self.weapons.\
append(WhiteSkull(self.player.rect.centerx + 20, self.player.rect.centery + 20, self.player.direction))
elif self.double_bonus:
self.weapons.\
append(WhiteSkull(self.player.rect.centerx - 20, self.player.rect.centery + 20, self.player.direction))
self.weapons.\
append(WhiteSkull(self.player.rect.centerx, self.player.rect.centery, self.player.direction))
elif event.key == K_SPACE:
if self.player.black_skulls:
self.weapons.\
append(BlackSkull(self.player.rect.centerx, self.player.rect.centery, self.player.direction))
self.player.black_skulls -= 1
elif event.key == K_ESCAPE:
self.brushing()
self.show_menu()
keys = pygame.key.get_pressed()
self.player.update(keys)
def event_menu(self):
for event in pygame.event.get():
if event.type == QUIT:
self.MAIN_LOOP = self.MENU_LOOP = False
elif event.type == KEYUP:
if event.key == K_UP:
self.catch_pos_menu(-1)
elif event.key == K_DOWN:
self.catch_pos_menu(1)
elif event.key == K_RETURN:
if self.menu_pos == 2: # exit game
self.MAIN_LOOP = self.MENU_LOOP = False
elif self.menu_pos == 1: # options
self.options_menu()
elif self.menu_pos == 0: # start game
self.MAIN_LOOP = True
self.MENU_LOOP = False
def options_menu(self):
self.OPTIONS_LOOP = True
while self.OPTIONS_LOOP:
self.surface.blit(self.background, (0, 0))
text_level = self.font.render("LEVEL {0}".format(self.level + 1), True, SILVER)
text_levelR = text_level.get_rect(centerx=SCREEN_WIDTH / 2, centery=SCREEN_HEIGHT / 2)
self.surface.blit(text_level, text_levelR)
pygame.draw.polygon(self.surface, SILVER, ((text_levelR.centerx - 10, text_levelR.centery - 30),
(text_levelR.centerx + 10, text_levelR.centery - 30),
(text_levelR.centerx, text_levelR.centery - 40)))
pygame.draw.polygon(self.surface, SILVER, ((text_levelR.centerx - 10, text_levelR.centery + 30),
(text_levelR.centerx + 10, text_levelR.centery + 30),
#.........这里部分代码省略.........
示例7: Game
# 需要导入模块: from hud import Hud [as 别名]
# 或者: from hud.Hud import draw [as 别名]
class Game(Div, object):
"""main frame of the game"""
def __init__(self, controller):
# super(game, self).__init__()
self.controller = controller
self.initAttr()
self.initElement()
def setLevel(self, level = 6):
self.boardWidth, self.boardHeight = self.board.setLevel(level)
self.height = self.boardHeight + self.edgeWidth * 2
self.width = self.boardWidth + self.hudWidth
self.initContext()
def initAttr(self):
self.turn = True
self.hudWidth = HUD["HUD_WIDTH"]
self.edgeWidth = GAME["EDGE_WIDTH"]
# 先获取 board 部分的大小,再自适应自己的大小
self.board = Board((self.hudWidth, self.edgeWidth))
Div.__init__(self, (self.board.width + self.hudWidth, self.board.height + self.edgeWidth * 2))
# 根据窗口高度设置 HUD 高度
self.hud = Hud((0, self.height), (0, 0))
self.hud.setMark(self.turn)
self.board.setTurn(self.turn)
self.gameID = 0
self.order = None
def initElement(self):
# 背景
self.background = Background((self.width, self.height))
backgroundColor = GAME["GAME_BACKGROUND_COLOR"]
self.background.setColor(backgroundColor)
# 返回按钮
self.returnButton = TextButton(GAME["RETURN_BUTTON_FONTS"], GAME["RETURN_BUTTON_CONTENT"], (30, 30))
def initContext(self):
self.screen = pygame.display.set_mode((self.width, self.height), DOUBLEBUF)
pygame.display.set_caption("Boxes")
self.clock = pygame.time.Clock();
def leaveServer(self, *args):
self.controller.gameNet.leaveServer(self.gameID)
return STATE.menu
def placeLine(self, data):
if self.hud.started:
self.controller.gameNet.placeLine(data, self.gameID, self.order)
def placeLineAnswer(self, turn, x, y, h, point, order):
self.setTurn(turn)
if order == self.order:
self.board.placeLine(x, y, h, point, True)
else:
self.board.placeLine(x, y, h, point, False)
def setTurn(self, turn):
self.hud.setMark(turn)
self.board.setTurn(turn)
def setHome(self):
self.order = 0
self.board.setHome()
self.background.setColor(GAME["HOME_COLOR"])
def setAway(self):
self.order = 1
self.board.setAway()
self.background.setColor(GAME["AWAY_COLOR"])
def addScore(self):
self.hud.addScore()
def enemyAddScore(self):
self.hud.enemyAddScore()
# 对手玩家进入游戏
def enemyComming(self, turn):
self.setTurn(turn)
self.board.restart()
self.hud.startGame()
def newHost(self):
self.hud.restart()
# 数据清零,重新开始游戏
def restart(self):
self.board.restart()
self.hud.restart()
def draw(self):
# self.screen.set_clip(None)
self.background.draw(self.screen)
ret = self.board.draw(self.screen)
if ret != None:
self.placeLine(ret)
self.hud.draw(self.screen)
self.returnButton.draw(self.screen)
var = self.returnButton.click(self.leaveServer)
#.........这里部分代码省略.........
示例8: World
# 需要导入模块: from hud import Hud [as 别名]
# 或者: from hud.Hud import draw [as 别名]
#.........这里部分代码省略.........
if enemy.typeofenemy == "popup":
if enemy.frame % 20 == 0:
self.score -= 1
# Check bullets offscreen
for bullet in self.bullets:
if bullet.rect.bottom < 0:
bullet.kill()
# Check backgrounds offscreen
for bkg in self.backgrounds:
if bkg.rect.top > SCREEN_HEIGHT:
bkg.kill()
if self.frames % 360 == 0:
self.spawnBkg()
if self.spawnFreq is not 1:
if self.frames % (500) == 0:
if self.spawnFreq <= 1:
self.spawnFreq = 1
elif self.spawnFreq > 1:
self.spawnFreq -= self.difficulty
# Spawn more enemies
baseSpawnRate = (self.spawnFreq * 5 + random.randint(1, 5))
#print self.difficulty, baseSpawnRate, self.spawnFreq
if not self.bossMode:
if self.frames % baseSpawnRate < 1:
seed = random.randint(1, 10)
if(seed < 7):
self.spawnVirus(0)
elif(seed < 10):
self.spawnDoubleVirus(0)
else:
self.spawnTripleVirus()
if self.frames % (baseSpawnRate * random.randint(3, 6)) < 1:
self.spawnWorm()
if self.frames % (baseSpawnRate * random.randint(2, 5)) < 1:
self.spawnPopup()
if self.frames % (baseSpawnRate * random.randint(18, 21)) < 1:
self.player.destroyAllEnemies = True
if self.frames % (baseSpawnRate * random.randint(1, 4)) < 1:
self.spawnCtrl()
if self.frames % (baseSpawnRate * random.randint(5, 8)) < 1:
self.spawnAlt()
if self.frames % (baseSpawnRate * random.randint(9, 12)) < 1:
self.spawnDel()
if self.frames % (baseSpawnRate * random.randint(4, 7)) < 1:
self.spawnSafe()
# Check if main music has ended, and loop music should start
if not pygame.mixer.music.get_busy():
if not self.boss_music:
pygame.mixer.music.load("data/music/Mainloop.mp3")
pygame.mixer.music.play(-1)
elif self.frames == FRAMES_UNTIL_BOSS + MUSIC_LENGTH_BOSS:
pygame.mixer.music.load("data/music/Bossloop.mp3")
pygame.mixer.music.play(-1)
#Check for calling enemy_popcorn
if self.call_popcorn != 0 and self.call_popcorn<self.frames-10:
self.enemy_popcorn()
# Check gameover
if self.player.lives == 0:
self.gameOver = True
pygame.mixer.music.stop()
# Check win screen!
if self.bossMode and self.boss.dead and self.boss.anim.done:
if not self.winScreen:
self.numEnemiesDestroyed += 1
self.winScreen = True
# Scroll level
self.scrollPosition += self.scrollSpeed
self.scrollPosition = min(self.scrollPosition, self.endPosition)
if self.scrollPosition == self.endPosition and not self.bossMode:
self.bossMode = True
self.spawnBoss()
self.frames += 1
def draw(self, screen):
for group in self.spriteGroups:
for sprite in group:
sprite.draw(screen)
self.hud.draw(screen, PLAY_WIDTH)
示例9: Character
# 需要导入模块: from hud import Hud [as 别名]
# 或者: from hud.Hud import draw [as 别名]
#.........这里部分代码省略.........
if self.movements[self.action].done:
self.movements[self.action].reset()
self.lock = False
if self.action in self.skill_names[self.name]:
skill = Skill(self)
self.skills.add(skill)
self.hud.mana.value -= skill.mana_cost
self.sound_effects.stop()
self.sound_effects[self.action].play()
self.hud.update()
def update_action(self, input_list):
"""Update character's action given an input list.
If a skill is to be cast check the mana bar if it holds enought mana
and play the corresponding sound effect.
Character.update_action(input_list): return None
"""
action_taken = False
if not self.lock:
if input_list[self.controls[0]]:
self.action = "move_left"
action_taken = True
if input_list[self.controls[1]]:
self.action = "move_right"
action_taken = True
if input_list[self.controls[2]]:
self.action = "jump"
self.lock = True
action_taken = True
if (input_list[self.controls[3]] and
self.hud.mana.value >= Skill.mana_costs["throw"]):
self.action = "throw"
self.lock = True
action_taken = True
if input_list[self.controls[4]]:
self.action = "normal_attack"
self.lock = True
action_taken = True
if (input_list[self.controls[5]] and
self.hud.mana.value >= Skill.mana_costs["special_1"]):
self.action = "special_1"
self.lock = True
action_taken = True
if (input_list[self.controls[6]] and
self.hud.mana.value >= Skill.mana_costs["special_2"]):
self.action = "special_2"
self.lock = True
action_taken = True
if not action_taken:
self.action = "stance"
def draw(self, surface):
"""Draw the hud and the character image onto the passed surface.
Call the draw methods of Hud and Sprite.
Character.draw(surface): return None
"""
self.hud.draw(surface)
super(Character, self).draw(surface)
def _adjust_position(self):
"""Adjust the character position so the bottom side of its rect is at
FLOOR_HEIGHT position.
Character._adjust_position(): return None
Should not be called manually.
"""
if (self.action != "jump" or
self.movements[self.action].current_frame == 0):
self.position.y = (DEFAULT_SCREEN_SIZE[1] - FLOOR_HEIGHT -
self.rect.height)
if self.position.x < 0:
self.position.x = 0
elif self.position.x > DEFAULT_SCREEN_SIZE[0] - self.rect.width:
self.position.x = DEFAULT_SCREEN_SIZE[0] - self.rect.width
elif (self.position.y > (DEFAULT_SCREEN_SIZE[1] - FLOOR_HEIGHT -
self.rect.height)):
self.position.y = (DEFAULT_SCREEN_SIZE[1] - FLOOR_HEIGHT -
self.rect.height)
def _adjust_direction(self):
"""Adjust the character direction so it faces the opponent. This does
not hold when the character is moving left or right.
Character._adjust_direction(): return None
Should not be called manually.
"""
if (self.direction == "Left" and
self.action not in ["move_left", "move_right"]):
self.image = pygame.transform.flip(self.image, True, False)
示例10: Engine
# 需要导入模块: from hud import Hud [as 别名]
# 或者: from hud.Hud import draw [as 别名]
#.........这里部分代码省略.........
def newgame(self):
self.load('%s/default.save' % config.save_path)
def loadgame(self, f='%s/savegame.save' % config.save_path):
try:
#sf = file(f)
#close(f)
self.load(f)
except:
self.newgame()
def Run(self):
self.title.show()
self.newgame() #only comment out if not showing title
self.hud.resize()
self.automap.update_room()
time = ika.GetTime()
done = False
self.music = ika.Music('%s/00_-_zaril_-_close_to_the_core.xm' %
config.music_path)
self.music.loop = True
self.music.Play()
while not done:
t = ika.GetTime()
while t > time:
# Uncomment for slow motion.
#ika.Delay(2)
self.tick()
time += 1
time = ika.GetTime()
self.update_time()
self.camera.update()
self.draw()
print >> fonts.one(0, 40), 'FPS:', ika.GetFrameRate()
#for i, e in enumerate(self.entities):
# print >> fonts.one(0, 50 + 10*i), 'sprite', e.sprite
ika.Input.Update()
if controls.pause.Pressed():
self.pause.menu()
ika.Input.Unpress()
# Make sure the engine doesn't have to play 'catchup'.
time = ika.GetTime()
#screenshot key
if False: #controls.confirm.Pressed(): #screenshot
#self.text('This is a textbox.')
ika.Input.Unpress()
time = ika.GetTime()
c = ika.Video.GrabCanvas(0, 0, ika.Video.xres, ika.Video.yres)
c2 = ika.Image(c)
c2.Blit(0, 0)
c.Save('blah1.png')
ika.Video.ShowPage()
def draw(self):
for thing in self.background_things:
thing.draw()
#if self.background:
# ika.Video.Blit(self.background, 0, 0)
for i in range(ika.Map.layercount):
ika.Map.Render(i)
for ent in self.entities:
if ent.layer == i and ent.visible:
ent.draw()