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


Python Menu.draw方法代码示例

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


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

示例1: main

# 需要导入模块: from menu import Menu [as 别名]
# 或者: from menu.Menu import draw [as 别名]
def main():
    """Snake main entry point."""

    pygame.init()
    game_display = display.Display('Snake')

    # Create menu buttons
    menu_buttons = [Button("(1) Classic game",
                           (display.WINDOW_WIDTH * 1/3,
                            display.WINDOW_HEIGHT * 3/8),
                           pygl.K_1),
                    Button("(2) Exit",
                           (display.WINDOW_WIDTH * 1/3,
                            display.WINDOW_HEIGHT * 4/8),
                           pygl.K_2)]

    # Create the menu
    game_menu = Menu(game_display, menu_buttons, 'snake/images/menu/snake.png')
    game_menu.draw()

    while True:
        for event in pygame.event.get():
            if (event.type == pygl.QUIT) or \
               (event.type == pygl.KEYDOWN and event.key == pygl.K_ESCAPE):
                sys.exit(pygame.quit)
            for button in menu_buttons:
                if (event.type == pygl.KEYDOWN and
                   button.key_pressed(event.key)):
                    run_game(game_display)

        pygame.display.update()
        game_display.update_clock()
开发者ID:bregman-arie,项目名称:snake,代码行数:34,代码来源:main.py

示例2: Main

# 需要导入模块: from menu import Menu [as 别名]
# 或者: from menu.Menu import draw [as 别名]
class Main():

    def __init__(self, gru_file=None): 
        self.menu = Menu(self, config, game = None)        
        self.library = Library(self, config)
        self.collider = Collider(self.menu, self.library, game=None)
        self.dispatcher = Dispatcher(self.collider, self.library, self.menu, game=None)
        self.clock = pygame.time.Clock()
        self.fps = Fps(self.clock, config)
        if gru_file is not None:
            game = Game(gru_file)
            self.load(game)
        else:
            self.game = None        
        
    def load(self, game):
        self.library.clear()
        self.game = game
        self.collider.game = game
        self.menu.game = game

    def clear(self):
        self.game = None
        self.collider.game = None
        self.menu.game = None

    def draw(self):    
        tick = self.clock.get_time()
        self.menu.draw()    
        if self.game == None:
            self.library.draw()  
        else:           
            self.game.draw(tick)        

                                  
    def start(self):                          
                     
        while 1:      
            self.clock.tick()                   
            mrect = Rect(mouse.get_pos(), (1,1))  
            self.collider.check()          
            self.draw()  
            self.fps.draw()            

            for ev in event.get():
                self.dispatcher.process(ev)               

            display.update()
开发者ID:Teognis,项目名称:GruEngine,代码行数:50,代码来源:GruEngine.py

示例3: menu_loop

# 需要导入模块: from menu import Menu [as 别名]
# 或者: from menu.Menu import draw [as 别名]
	def menu_loop():
		pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
		pygame.mixer.music.load("sound/hearthbeat.wav")
		pygame.mixer.music.play()
		menu_screen = pygame.display.set_mode((854, 480))
		menu_screen.fill((51, 51, 51))
		menu = Menu(['Start', 'Options', 'Quit'], menu_screen)
		menu.draw()
		pygame.key.set_repeat(199, 69)  # (delay,interval)
		pygame.display.update()

		while 1:
			for event in pygame.event.get():
				if event.type == pygame.KEYDOWN:
					if event.key == pygame.K_UP:
						menu.draw(-1)  # here is the Menu class function
					if event.key == pygame.K_DOWN:
						menu.draw(1)  # here is the Menu class function
					if event.key == pygame.K_RETURN:
						if menu.get_position() == 2:  # here is the Menu class function
							pygame.quit()
							sys.exit()
						elif menu.get_position() == 0:
								Main(800, 800, 100)
								pygame.init()
								menu_loop()
					if event.key == pygame.K_ESCAPE:
						pygame.display.quit()
						sys.exit()
					pygame.display.update()
				elif event.type == pygame.QUIT:
					pygame.display.quit()
					sys.exit()
			pygame.time.wait(8)
开发者ID:Pfeter,项目名称:SpaceShooter,代码行数:36,代码来源:game.py

示例4: getPlayer

# 需要导入模块: from menu import Menu [as 别名]
# 或者: from menu.Menu import draw [as 别名]
    def getPlayer(self):

        rtnObject = self.returnObject()
        # Starting screen text
        title = self.titleFont.render("Chocotaco Othello",True,DULLYELLOW)
        self.display.blit(title,(int(self.boardWidth/4),50))
        info = [pygame.Surface]*4
        info[0] = self.font.render("Select playing option using the UP & DOWN arrow keys.", True, WHITE)
        info[1] = self.font.render("Set computer timeout using the LEFT & RIGHT arrow keys",True, WHITE)
        info[2] = self.font.render("Make a selection using the ENTER key", True,WHITE)
        info[3] = self.font.render("Press SPACE to set layout for configuration", True, WHITE)
        for n, blurb in enumerate(info):
            self.display.blit(blurb, (75, self.boardWidth/4+32*n))
        #Time out information
        timeOut = 5
        timeOutLabel = self.font.render("Timeout", True, WHITE)
        self.display.blit(timeOutLabel,(int(3*self.windowSize/4)+16, int(self.boardWidth/2)+32))
        self.showTimeout(timeOut)
        #Actual Menu
        menu = Menu()
        menu.init(['Go First (Black)', 'Go Second (White)','Comp V Comp','Quit'], self.display)
        menu.draw()
        pygame.key.set_repeat(199,69)
        pygame.display.update()
        while 1:
            for event in pygame.event.get():
                if event.type == KEYDOWN:
                    if event.key == K_LEFT:
                        if timeOut >2:
                            timeOut -= 1
                            self.showTimeout(timeOut)
                    elif event.key == K_RIGHT:
                        if timeOut < 15:
                            timeOut += 1
                            self.showTimeout(timeOut)
                    elif event.key == K_UP:
                        menu.draw(-1) #here is the Menu class function
                    elif event.key == K_DOWN:
                        menu.draw(1) #here is the Menu class function
                    elif event.key == K_RETURN or event.key == K_SPACE:
                        if menu.get_position() == 0:
                            # rtnObject.players = ["h", "c"]
                            return ["h", "c"], timeOut, (event.key == K_SPACE)
                        elif menu.get_position() == 1:
                            # rtnObject.players =["c", "h"]
                            return ["c", "h"], timeOut, (event.key == K_SPACE)
                        elif menu.get_position() == 2:
                            # rtnObject.players =["c", "c"]
                            return ["c", "c"], timeOut, (event.key == K_SPACE)
                        elif menu.get_position() == 4:
                            pygame.display.quit()
                            sys.exit()
                    if event.key == K_ESCAPE:
                        pygame.display.quit()
                        sys.exit()
                    pygame.display.update()
                elif event.type == QUIT:
                    pygame.display.quit()
                    sys.exit()
开发者ID:schauhan19,项目名称:Othello-AI,代码行数:61,代码来源:gui.py

示例5: PauseState

# 需要导入模块: from menu import Menu [as 别名]
# 或者: from menu.Menu import draw [as 别名]
class PauseState(AppState):
    def setup(self):
        AppState.setup(self)

        self.menu = Menu()
        self.menu.add("Resume", None)
        self.menu.add("Restart", None)
        self.menu.add("Main Menu", None)
        self.menu.add("Exit", None)
        self.menu.build()

        # save app state
        self.game = self.app.state

        # render the screen background
        self.background = pygame.display.get_surface().convert()
        overlay = pygame.Surface(self.background.get_size())
        overlay.set_alpha(200)
        overlay.fill((0, 0, 0))

        self.background.blit(overlay, (0, 0))

    def resume(self):
        pygame.mixer.music.pause()

    def resume_game(self):
        pygame.mixer.music.unpause()
        self.app.set_state(self.game)

    def handle_event(self, event):
        if event.type == KEYDOWN and event.key == K_ESCAPE:
            self.resume_game()

    def draw(self):
        self.screen.blit(self.background, (0, 0))
        self.menu.draw(self.screen)
        pygame.display.flip()
开发者ID:HampshireCS,项目名称:cs143-Spring2012,代码行数:39,代码来源:menustates.py

示例6: main

# 需要导入模块: from menu import Menu [as 别名]
# 或者: from menu.Menu import draw [as 别名]
def main():

    WIDTH = 800
    HEIGHT = 800
    FULLSCREEN = True
    ode = '../resources/song.ogg'
    overture = '../resources/song1.ogg'
    moonlight = '../resources/song2.ogg'

    if (FULLSCREEN):
        screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.FULLSCREEN)
    else:
        screen = pygame.display.set_mode((WIDTH, HEIGHT))
    screen.fill((51,51,51))




    menu = Menu()
    menu.init(['Start', 'Quit'], screen)
    menu.draw(0)
    pygame.display.update()

    pygame.mixer.init()
    pygame.mixer.music.load('../resources/tuning_warmup.mp3')
    pygame.mixer.music.set_volume(2)
    pygame.mixer.music.play()

    pick = menu.run()

    while 1:
        if (pick == 1):
            menu = Menu()
            menu.init(['Start', 'Quit'], screen)
            menu.draw(0)
            pygame.display.update()
            pick = menu.run()
            if (pick == 1):
                menu = Menu()
                menu.init(['Ode To Joy','The Creatures of Prometheus','Moonlight Sonata mov 3','Quit'], screen)
                menu.draw(0)
                pygame.display.update()
                pick2 = menu.run()
                if (pick2 == 1):
                    game = Game(WIDTH, HEIGHT, FULLSCREEN, ode)
                    game.run()
                elif (pick2 == 2):
                    game = Game(WIDTH, HEIGHT, FULLSCREEN, overture)
                    game.run()
                elif (pick2 == 3):
                    game = Game(WIDTH, HEIGHT, FULLSCREEN, moonlight)
                    game.run()
            elif (pick == 2):
                break
开发者ID:manna422,项目名称:beethovens_final,代码行数:56,代码来源:main.py

示例7: Game

# 需要导入模块: from menu import Menu [as 别名]
# 或者: from menu.Menu import draw [as 别名]
class Game(Enableable, Completable, Inputable):
    def __init__(self, levels):
        super().__init__()

        # --- Inits
        os.environ["SDL_VIDEO_CENTERED"] = "1"
        pygame.mixer.pre_init(44100, 16, 2, 4096)
        pygame.init()
        pygame.font.init()

        pygame.display.set_caption(const.gameName)
        self._surface = pygame.display.set_mode((const.screenSize[0] * const.res,
                                                 const.screenSize[1] * const.res))
        self._clock = pygame.time.Clock()
        self._levAttr = levels
        self._world = None
        self._paused = False

        self._menu = Menu(surface=self._surface,
                          pos=(const.screenSize[0] * const.res / 2 - 50,
                               const.screenSize[1] * const.res / 2 - 100),
                          inputStream=self.getInputStream())
        self._menu.addItem("resume", (0, 0, 100, 48), MColor((255, 0, 0), (0, 0, 255)),
                           MText("Resume", (0, 255, 0)), MAction(self._resume))
        self._menu.addItem("start", (0, 50, 100, 48), MColor((255, 0, 0), (0, 0, 255)),
                           MText("Start", (0, 255, 0)), MAction(self.start))
        self._menu.addItem("editor", (0, 100, 100, 48), MColor((255, 0, 0), (0, 0, 255)),
                           MText("Editor", (0, 255, 0)), MAction(self._editor))
        self._menu.addItem("exit", (0, 150, 100, 48), MColor((255, 0, 0), (0, 0, 255)),
                           MText("Exit", (0, 255, 0)), MAction(self.setFinished))

        self._input = Input(inputStream=self.getInputStream())
        self._input.set(pygame.KEYDOWN, self._menuToggle, pygame.K_m)
        self._input.set(pygame.KEYDOWN, self._pause, pygame.K_p)

    def start(self):
        self.enable()
        self._world = World(self._surface, self._levAttr, inputStream=self.getInputStream())
        self._world.nextLevel()
        self._menu.disable()

    def _pause(self):
        self._paused = not self._paused

    def _resume(self):
        if self._world is not None and not self._world.isComplete():
            self.enable()
        else:
            self.start()
        self._menu.disable()

    def _editor(self):
        if self._world:
            self._world.level.editor.enabled()
            self._menu.disable()

    def _menuToggle(self):
        self._menu.toggleEnabled()
        self.toggleEnabled()

    def tick(self):
        self.getEvents()
        self._input()

        if self._menu.enabled():
            self._menu.tick()
            self._menu.draw()
        elif self.enabled:
            if self._world.isComplete():
                if self._world.isFinished():
                    self._win()
                elif self._world.isLost():
                    self._gameOver()
            else:
                if not self._paused:
                    self._world.tick()
        self.clearInputStream()

        self._clock.tick(const.FPS)
        pygame.display.flip()

    def _win(self):
        self._endGame("YOU WIN!")

    def _gameOver(self):
        self._endGame("GAME OVER!")

    def _endGame(self, text):
        try:
            self.__gameOverCount += 1
        except AttributeError:
            self.__gameOverCount = 1
            self.__goText = pygame.font.Font(None, 100).render(text, 1, (255, 0, 0))
            self.__gameOverX = int(self._surface.get_width() / 2 - self.__goText.get_width() / 2)
            self.__gameOverY = int(self._surface.get_height() / 2 - self.__goText.get_height() / 2)

        if self.__gameOverCount < (const.FPS * 5):
            self._surface.fill((0, 0, 0))
            self._surface.blit(self.__goText, (self.__gameOverX, self.__gameOverY))
        else:
#.........这里部分代码省略.........
开发者ID:DanCardin,项目名称:PyPlatformer,代码行数:103,代码来源:game.py

示例8: draw

# 需要导入模块: from menu import Menu [as 别名]
# 或者: from menu.Menu import draw [as 别名]
	def draw(__):
		Menu.draw(__)
		__.label.blit()
开发者ID:weyzohorth,项目名称:BombWar,代码行数:5,代码来源:menu_but.py

示例9: main

# 需要导入模块: from menu import Menu [as 别名]
# 或者: from menu.Menu import draw [as 别名]
def main():
    screendimensions = (1000,600)
    griddimensions = (720,450)
    os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (50,50)
    pygame.init()
    screen = pygame.display.set_mode(screendimensions)
    font = pygame.font.SysFont("quartzms",50)
    loading = pygame.sprite.Sprite()
    loading.image = font.render('- LOADING-',True,white)
    loading.rect = loading.image.get_rect()
    loading.rect.centerx = screendimensions[0]/2
    loading.rect.centery = screendimensions[1]/2
    screen.blit(loading.image,loading.rect)
    pygame.display.flip()
    clock = pygame.time.Clock()
    mousevisible = False
    pygame.mouse.set_visible(mousevisible)    
    color1 = red
    color2 = white
    manager = blocks.BlockManager(color1,color2,125,1.5,
                                  (screendimensions[0]-griddimensions[0])/2,
                                  screendimensions[1]-griddimensions[1]-20)
    inf = info.Info(screendimensions[0],screendimensions[1])
    menu = Menu(screendimensions)
    songs = glob('*.ogg')
    shuffle(songs)
    print(songs)
    if songs:
        pygame.mixer.music.load(songs[0])
        pygame.mixer.music.play()
        currentsong = 0
        songlengths = []
        for song in songs:
            songlengths.append(pygame.mixer.Sound(song).get_length())

    while 1:
        time = clock.tick(60)/1000
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.mixer.music.stop()
                return
            elif event.type == MOUSEBUTTONDOWN:
                if menu.enabled:
                    if menu.option == -2:
                        pygame.mixer.music.stop()
                        return
                    elif menu.option == 0:
                        mousevisible = False
                        pygame.mouse.set_visible(mousevisible)
                        menu.HideMenu()
                    elif menu.option == 1:
                        manager.NewGame()
                        inf.reset()
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    mousevisible = not mousevisible
                    pygame.mouse.set_visible(mousevisible)
                    menu.ToggleMenu()
                # Send keyboard input to manager to be handled
                if not menu.enabled and not inf.IsGameOver():
                    manager.KeydownHandler(event.key)
            elif event.type == KEYUP and not inf.IsGameOver():
                if not menu.enabled:
                    manager.KeyupHandler(event.key)

        if songs and pygame.mixer.music.get_pos()/1000+1 > songlengths[currentsong]:
            currentsong = (currentsong+1)%len(songs)
            pygame.mixer.music.load(songs[currentsong])
            pygame.mixer.music.play()
        if menu.enabled:
            choice = menu.update(pygame.mouse.get_pos())
        else:
            if not inf.IsGameOver():
                if manager.score == -1:
                    print('main gameover')
                    inf.GameOver()
                else:
                    manager.update(time)
                    inf.update(manager.score)
            
        screen.fill(charcoal)
        manager.draw(screen)
        inf.draw(screen)
        menu.draw(screen)
        pygame.display.flip()
开发者ID:andyquint,项目名称:Metroblocks,代码行数:87,代码来源:main.py

示例10: PixFiz

# 需要导入模块: from menu import Menu [as 别名]
# 或者: from menu.Menu import draw [as 别名]
class PixFiz(object):

	def __init__(self):
		pg.init()
		self.set_cursor()
		self.background = self.tile_bg()
		self.screen = pg.display.set_mode((600,400))
		self.clock = pg.time.Clock()
		self.menu = Menu()
		self.grid = Grid()
		self.drop = DropDown()	
		self.network = Network()

	def input(self):
		#key events
		pixinput.update_input()

		if pixinput.keys["LEFT_CLICK_PRESSED"] == True:
			
			if max(pg.mouse.get_pos()) < 28:
				self.drop.clicked_on()
			else:
				if (self.drop.open == False):
					self.grid.mouse_click(pg.mouse.get_pos())
					self.network.pass_message(str(pg.mouse.get_pos()))
		if pixinput.keys["WHEEL_UP"] == True:
			self.grid.zoom_in(pg.mouse.get_pos())
		if pixinput.keys["WHEEL_DOWN"] == True:
			self.grid.zoom_out(pg.mouse.get_pos())

		if (pixinput.keys["MOUSE_MOVED"] & (pixinput.keys["LEFT_CLICK_ALT"] | pixinput.keys["MIDDLE_CLICK"]) == True):
			rel = pixinput.m_rel
			self.grid.pan(rel)

		return pixinput.keys["QUIT"] | pixinput.keys["ESCAPE"]

	def main_loop(self):
		quit = False
		while not quit:
			quit = self.input()

			# draw events
			self.screen.blit(self.background, (0,0))
			self.menu.draw(self.screen)
			self.grid.draw(self.screen)
			self.drop.draw(self.screen)
			self.network.listen()
			

			# FPS stuff
			pg.display.flip()
			milliseconds = self.clock.tick(FPS)
			pg.display.set_caption("FPS: " + str(self.clock.get_fps()))

	def set_cursor(self):
		pg.mouse.set_cursor(*pg.cursors.arrow)

	def tile_bg(self): #makes the transparent image to use as a bg.
		bg = pg.image.load("back.png")
		trans_back = pg.Surface((600,400))
	
		for i in xrange(0, 600, 32):
			for j in xrange(0, 400, 32):
				trans_back.blit(bg,(i, j))
		return trans_back
开发者ID:alanxoc3,项目名称:pix-fiz,代码行数:67,代码来源:pix-fiz.py

示例11: Game

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

#.........这里部分代码省略.........
                                                      pygame.sprite.collide_mask)
                
                # if there was a collision
                if userHit:
                    self.aiSprites.remove(enemy) # remove object
                    self.userShip.shield -= 25
                    self.score = self.score + enemy.score # add to score
                    self.explodeSnd.play()
                    
            # check for collisions between powerUps and the user
            for powerUp in self.powerUpSprites:
                userHit = pygame.sprite.spritecollide(powerUp,self.userSprites,False)
                
                # if there was a collision
                if userHit:
                    self.powerUpSprites.remove(powerUp) # remove object
                    powerUp.pickUp(self.userShip)
                    self.powerUpSnd.play()                # no sound yet!!
            # =============================================================
                    
            # if user is dead
            if self.userShip.shield <= 0:
                self.userShip.shield = 0        # round shield to 0
                self.gameState = "gameOver"     # change state to gameOver            
        # ====================================================================
        
        # Game Over ==========================================================
        elif self.gameState == "gameOver":            
            pass
        # ====================================================================
        else:
            pass # throw exception!
            
    def draw(self,screen):
    
        # Menu ===============================================================
        if self.gameState == "menu":
            self.menu.draw(screen)
        # ====================================================================

        # Pause ==============================================================
        if self.gameState == "pause":
            self.pause.draw(screen)
        # ====================================================================
        
        # Volume =============================================================
        if self.gameState == "volume":
            self.volume.draw(screen)
        # ====================================================================
        
        # Credits ============================================================
        if self.gameState == "credits":           
            self.credits.draw(screen)
        # ====================================================================
        
        # Game ===============================================================
        elif self.gameState == "game":
            # erase screen
            screen.fill(BLACK)

            # draw background - since the background is scrolling
            # we shall draw two side by side to prevent the background from ending
            # this way it repeats itself
            screen.blit(self.backg.image,(self.backg.x,self.backg.y))
            screen.blit(self.backg.image,(self.backg.x + self.backg.width,self.backg.y))
                           
开发者ID:aalopes,项目名称:cometZ,代码行数:69,代码来源:core.py

示例12: main

# 需要导入模块: from menu import Menu [as 别名]
# 或者: from menu.Menu import draw [as 别名]
def main():
  pygame.init()
  pygame.mixer.music.load("rematch.mp3")
  pygame.mixer.music.play(-1)
  screen = pygame.display.set_mode((1000, 1000))
  clock = pygame.time.Clock()
  
  game_map = Map(0)
  player = Character( game_map, 23, 1 )
  
  prevKeys = {}
  
  menu = Menu()
  while True:
    for e in pygame.event.get():
      if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
        pygame.quit()
        return
    key = pygame.key.get_pressed()
    
    if key[K_DOWN] and not prevKeys[K_DOWN]:
      menu.move(1)
    if key[K_UP] and not prevKeys[K_UP]:
      menu.move(-1)
    if key[K_RETURN] and not prevKeys[K_RETURN]:
      r = menu.select()
      if r == -1:
        pygame.quit()
        return
      elif r == 1:
        break
        
    prevKeys = key
    
    menu.draw(screen)
    pygame.display.flip()
    
  
  while True:
    
    clock.tick(30)
    for e in pygame.event.get():
      if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
        pygame.quit()
        return
    key = pygame.key.get_pressed()
    
    if key[K_LSHIFT]:
      if key[K_UP] and not prevKeys[K_UP]:
        player.attack_up()
      elif key[K_DOWN] and not prevKeys[K_DOWN]:
        player.attack_down()
      elif key[K_LEFT] and not prevKeys[K_LEFT]:
        player.attack_left()
      elif key[K_RIGHT] and not prevKeys[K_RIGHT]:
        player.attack_right()
    else:
      if key[K_UP] and not prevKeys[K_UP]:
        player.move_up()
      elif key[K_DOWN] and not prevKeys[K_DOWN]:
        player.move_down()
      elif key[K_LEFT] and not prevKeys[K_LEFT]:
        player.move_left()
      elif key[K_RIGHT] and not prevKeys[K_RIGHT]:
        player.move_right()
    
    while game_map.isWin(player.position.real, player.position.imag):
      screen.blit(winScreen,(0,0))
      pygame.display.flip()
      for e in pygame.event.get():
        if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
          pygame.quit()
          return
    
    prevKeys = key
    game_map.draw(screen)
    player.draw(screen)
    
    
    
    pygame.display.flip()
开发者ID:origamize,项目名称:GameJamFall2011,代码行数:83,代码来源:main.py

示例13: Main

# 需要导入模块: from menu import Menu [as 别名]
# 或者: from menu.Menu import draw [as 别名]
class Main(object):
    """main loop of the game"""
    def __init__(self):
        pygame.init()
        # 包括读取设置文件,设置游戏基本属性
        self.initAttr()
        # 传递所需的参数,实例化所包含的各个类
        self.initObj()
        self.initContext()

    def initAttr(self):
        self.width, self.height = WINDOW_WIDTH, WINDOW_HEIGHT
        self.state = STATE.menu
        self.running = True
        self.level = SETLEVEL["DEFAULT_LEVEL"]
        self.channelID = None

    def initObj(self):
        # 设置大小,用于背景图片的缩放
        self.gameNet = GameNet(self)
        self.gameNet.connectToServer()
        self.menu = Menu((self.width, self.height), self)
        self.rules = Rules(self.width, self.height)
        self.setLevel = SetLevel(self.width, self.height)
        self.matching = Matching((self.width, self.height), self)
        self.game = Game(self)
        # finish 界面的大小和游戏界面一样
        self.finish = Finish((self.game.width, self.game.height))

    # 绘制游戏主窗体
    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 linkSuccess(self):
        print "link success"
        print self.channelID

    def enterMatching(self):
        self.matching.getRooms()

    def enemyComming(self, turn, gameID):
        self.gameID = gameID
        self.game.enemyComming(turn)
        self.game.setHome()

    def joinGame(self, level, gameID, turn):
        self.game = Game(self)
        self.game.gameID = gameID
        self.state = STATE.game
        self.game.setLevel(level)
        self.game.enemyComming(turn)
        self.game.setAway()

    def enterMenu(self):
        self.state = STATE.menu

    # 进入游戏界面事件
    def enterGame(self, level):
        self.game.setLevel(level)
        self.game.initContext()
        self.state = STATE.game

    def startedNewGame(self, level):
        print "open room", level
        self.gameNet.openRoom(level)

    def leaveServer(self, gameID):
        self.gameNet.leaveServer(self.gameID)
        self.state = STATE.menu

    def backToMenu(self):
        self.initContext()
        self.state = STATE.menu

    def addScore(self):
        self.game.addScore()

    def enemyAddScore(self):
        self.game.enemyAddScore()

    def getRooms(self, matching, page, num):
        self.gameNet.getRooms(matching, page, num)

    def update(self):
        self.clock.tick(60)
        self.screen.fill(0)
        self.gameNet.pump()

        if STATE.exit == self.state:
            exit()

        elif STATE.setLevel == self.state:
            var = self.setLevel.draw(self.screen)
            if (var in STATE):
                self.state = var
            else:
                self.startedNewGame(var)
#.........这里部分代码省略.........
开发者ID:piratf,项目名称:Game_Boxes,代码行数:103,代码来源:main.py

示例14: Game

# 需要导入模块: from menu import Menu [as 别名]
# 或者: from menu.Menu 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))
开发者ID:BrettMcNeff,项目名称:TBA,代码行数:104,代码来源:game.py

示例15: __init__

# 需要导入模块: from menu import Menu [as 别名]
# 或者: from menu.Menu import draw [as 别名]
class LD26Main:
    def __init__(self, width=800,height=600):
        pygame.init()
        self.width = width
        self.height = height
        self.screen = pygame.display.set_mode((self.width, self.height))
        self.state = "menu"
        pygame.display.set_caption("Shoot Guys")

    def load_sprites(self):
        self.player_group = CameraSpriteGroup()
        self.player_bullet_group = CameraSpriteGroup()
        self.player_max_hp = 20
        self.player_healthbar = HealthBar(self.player_max_hp, self.player_max_hp, "res/player_healthbar.png", (128, 16))
        self.player_healthbar.rect.x = -55
        self.player_healthbar.rect.y = 10
        self.player_hb_group = CameraSpriteGroup()
        self.player_hb_group.add(self.player_healthbar)

        self.enemy_group = CameraSpriteGroup()
        self.enemy_bullet_group = CameraSpriteGroup()
        self.health_bar_sprites = CameraSpriteGroup()
        self.max_badguys = 0
        self.guys_killed = 0

        self.levels = [{"img":"res/levels/level1.png", "badguys":2, "goal":6}, {"img":"res/levels/level2.png", "badguys":5, "goal":10}]
        self.cur_level = 0

        self.load_level(0)
        self.menu = Menu()
        self.win = Win()
        self.die = Die()

    def load_level(self, levelnum):
        if levelnum >= len(self.levels):
            self.state = "win"
        else:
            leveldict = self.levels[levelnum]
            self.player = Player((self.width, self.height))
            self.player_group.add(self.player)
            self.level = Level((self.width, self.height), leveldict["img"])
            self.bdrop1 = Backdrop(self.level.dims, 1)
            self.bdrop2 = Backdrop(self.level.dims, 2)
            self.max_badguys = leveldict["badguys"]
            self.guys_killed = 0
            self.kill_goal = leveldict["goal"]
            self.player_healthbar.set_hp(self.player_max_hp)

    def go(self):
        self.load_sprites()
        self.clock = pygame.time.Clock()
        while 1:
            self.clock.tick(60)
            self.screen.fill((0, 0, 0))

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == K_ESCAPE:
                        if self.state == "game":
                            self.state = "menu"
                        else:
                            sys.exit()

                    elif event.key == K_RETURN:
                        if self.state == "menu":
                            self.state = "game"
                        elif self.state == "win" or self.state == "die":
                            self.load_level(0)
                            self.state = "game"

            if self.state == "menu":
                self.do_menu()
            elif self.state == "game":
                self.do_main_game()
            elif self.state == "win":
                self.do_win()
            else:
                self.do_die()

            pygame.display.flip()

    def do_die(self):
        self.die.update()
        self.die.draw(self.screen)

    def do_win(self):
        self.win.update()
        self.win.draw(self.screen)

    def do_menu(self):
        self.menu.update()
        self.menu.draw(self.screen)

    def do_main_game(self):
        if self.guys_killed > self.kill_goal:
            self.cur_level += 1
            self.player.kill()
            self.load_level(self.cur_level)
#.........这里部分代码省略.........
开发者ID:larsendt,项目名称:ld26,代码行数:103,代码来源:main.py


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