def end_game(self, winner, points): ''' Display information about winner and write result to file. Args: winner : string points : int Returns: None ''' print('The winner is: {}, with {} points'.format(winner, points)) highscores = Highscores() highscores.add_highscore([winner, str(points)]) print(highscores) highscores.save_to_file()
def showMenu(self): """Show menu and highscores table.""" self.loadMenuImages() # Menu items when first item is active. menuItems1 = pygame.sprite.OrderedUpdates(self.itemStartOn, self.itemHighscoresOff, self.itemQuitOff) # Menu items when second item is active. menuItems2 = pygame.sprite.OrderedUpdates(self.itemStartOff, self.itemHighscoresOn, self.itemQuitOff) # Menu items when third item is active. menuItems3 = pygame.sprite.OrderedUpdates(self.itemStartOff, self.itemHighscoresOff, self.itemQuitOn) backgroundObjects = pygame.sprite.OrderedUpdates(self.background) scorePath = self.gameConfig['general'].get('highscorePath') highscores = Highscores() highscores.load(scorePath) highscores.render() menuLevel = 1 menuItemActive = 1 showHighScores = False quitApplication = False going = True while going and not quitApplication: self.clock.tick(FRAME_RATE) for event in pygame.event.get(): if event.type == QUIT: quitApplication = True elif event.type == KEYDOWN: if event.key == K_ESCAPE: menuLevel -= 1 showHighScores = False if event.key in (K_RETURN, K_KP_ENTER): if menuItemActive == 3: quitApplication = True elif menuItemActive == 2: menuLevel += 1 showHighScores = True elif menuItemActive == 1: score, quitApplication, pressedEsc = self.play( self.screen, highscores.scores) if quitApplication: print('Quitting application...') pygame.quit() sys.exit(0) # Save score only if user left level by pressing # <enter> key. if score and not pressedEsc: highscores.scores.append(score) highscores.render() highscores.save(scorePath) elif event.key == K_UP: menuItemActive -= 1 if menuItemActive < 1: menuItemActive = 3 elif event.key == K_DOWN: menuItemActive += 1 if menuItemActive > 3: menuItemActive = 1 backgroundObjects.draw(self.screen) if showHighScores: highscores.draw(self.screen) pygame.display.flip() continue if menuLevel == 0: quitApplication = True if menuItemActive == 1: menuItems1.draw(self.screen) elif menuItemActive == 2: menuItems2.draw(self.screen) elif menuItemActive == 3: menuItems3.draw(self.screen) # For debuging purposes if self.debugMenuItems: self.drawRect(self.itemStartOn.rect, 1) self.drawRect(self.itemStartOff.rect, 1) self.drawRect(self.itemHighscoresOn.rect, 1) self.drawRect(self.itemHighscoresOff.rect, 1) self.drawRect(self.itemQuitOn.rect, 1) self.drawRect(self.itemQuitOff.rect, 1) pygame.display.flip() if quitApplication: print('Quitting application...') pygame.quit() sys.exit(0)
def main(self): self.music.play() # Screen base self.screen.fill((0,0,0)) self.screen.blit(self.img_background,self.img_background_rect) highscores = Highscores() # Main instances pavement = Pavement(self.unit) snake = Snake(self.unit) foods = Foods(self.unit) walls = Walls(self.unit) score = Score(self.unit,self.surface_rect) nextgold = random.randint(*Constants.TIMERANGE_GOLD) * Constants.FPS # first gold between 30 & 60 seconds makegold = False nextwall = random.randint(*Constants.TIMERANGE_WALL) * Constants.FPS # first gold between 30 & 60 seconds makewall = False updatestats = True counter = 0 flag_music = True flag_pause = False #MAIN LOOP while self.running: time = pygame.time.get_ticks() for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.running = False elif event.key == pygame.K_m: flag_music = not flag_music if flag_music: self.music.play() else: self.music.stop() elif event.key == pygame.K_1: pygame.image.save(self.screen, "screenshot.jpg") elif event.key == pygame.K_SPACE or event.key == pygame.K_p: flag_pause = True self.print_text("PAUSE") while flag_pause: for event in pygame.event.get(): if event.type==pygame.KEYDOWN: if event.key==pygame.K_p or event.key == pygame.K_SPACE: flag_pause = False else: # Time to change direction action = 0 if event.key == pygame.K_UP or event.key == pygame.K_w: action = 1 elif event.key == pygame.K_DOWN or event.key == pygame.K_s: action = 2 elif event.key == pygame.K_LEFT or event.key == pygame.K_a: action = 3 elif event.key == pygame.K_RIGHT or event.key == pygame.K_d: action = 4 if action: self.sounds.play("move") snake.action(action) # Snake movements and pavement reactions snake.move() pavement.passage(snake.head) pavement.make_regrow(snake.tail) # Snake has eaten? if foods.check(snake.head): updatestats = True snake.grow(Constants.GROW) score.add_score(foods.score) self.sounds.play("eat") # Snake if walls.check(snake.head): snake.alive = False # Snake is dead? if not snake.alive: #blood splash (bin on head, little on body) pavement.bloodsplat(snake.head) [pavement.bloodsplat(x,1) for x in snake.body if random.randint(0,2)==0] #redraw all the snake snake.set_dirty(1) self.sounds.play("splat") self.running = False # Gold generator (After pseudo-random time a golden apple will appear) nextgold-=1 if nextgold<0: makegold = True nextgold = random.randint(*Constants.TIMERANGE_GOLD)*Constants.FPS # Wall generator (After pseudo-random time a wall will appear) nextwall-=1 if nextwall<0: makewall = True nextwall = random.randint(*Constants.TIMERANGE_WALL)*Constants.FPS # Foods request to create an apple # Game has to provide to Foods the list of forbidden blocks if foods.needapple or makegold or makewall: forbidden = [[-1,-1]] forbidden.extend(foods.get_forbidden()) forbidden.extend(snake.get_forbidden()) forbidden.extend(walls.get_forbidden()) # Creates the apples and make the pavement Grass if foods.needapple: newpos = foods.make_apple(forbidden) pavement.make_grass(newpos) forbidden.extend(newpos) if makegold: self.sounds.play('ding') newpos = foods.make_gold(forbidden) pavement.make_grass(newpos) forbidden.extend(newpos) makegold = False if makewall: self.sounds.play('fall') newpos = walls.make_solid(forbidden) pavement.make_none(newpos) forbidden.extend(newpos) makewall = False # Foods request pavement update for pos in foods.refresh: pavement.passage(pos) foods.refresh.remove(pos) del pos # Updates and draws pavement.update() pavement.draw(self.surface) walls.update() walls.draw(self.surface) snake.update() snake.draw(self.surface) foods.update() foods.draw(self.surface) if updatestats or not counter % Constants.FPS: score.set_length(snake.length) score.update() score.draw(self.screen) updatestats = False if not counter % Constants.FPS: score.add_second() counter = 0 # Surface on surface... weeee! self.screen.blit(self.surface,self.surface_rect) pygame.display.update() self.clock.tick(self.tick) counter+=1 #END OF MAIN LOOP if not snake.alive: self.print_text("GAME OVER") if highscores.check(score.score,score.elapse): current_string = '' complete = False inputbox = InputBox(self.unit) inputbox.rect.centerx = self.screen.get_rect().centerx inputbox.rect.centery = self.screen.get_rect().centery inputbox.draw(self.screen) pygame.display.update() pygame.event.clear() redraw = False while not complete: event = pygame.event.wait() if event.type == pygame.QUIT: return if event.type != pygame.KEYDOWN: continue if event.key == pygame.K_BACKSPACE: current_string = current_string[:-1] redraw = True elif event.key == pygame.K_RETURN: if len(current_string) == 0: current_string = 'Mysterious player' complete = True elif event.unicode: if len(current_string) <= 15: c = ord(event.unicode) if c >= 32 and c <= 126 or c==8: current_string += event.unicode redraw = True if redraw: redraw = False inputbox.set_text(current_string) inputbox.update() inputbox.draw(self.screen) pygame.display.update() position = highscores.insert(current_string,score.score,score.elapse) highscores.save() scored = {'index':position,'scored':True} else: counter = Constants.FPS*3 # 3 seconds pygame.display.update() while counter > 0: for event in pygame.event.get(): if event.type == pygame.QUIT or event.type == pygame.KEYDOWN: counter = 0 self.clock.tick(self.tick) pygame.display.update() counter-=1 scored = {'elapse':score.elapse,'score':score.score,'scored':False} ts = TitleScreen(self.screen,self.unit,self.preferences) ts.highscores(scored) del ts self.music.stop() return
def main(): global SCREEN_FULLSCREEN pygame.init() util.load_config() if len(sys.argv) > 1: for arg in sys.argv: if arg == "-np": Variables.particles = False elif arg == "-na": Variables.alpha = False elif arg == "-nm": Variables.music = False elif arg == "-ns": Variables.sound = False elif arg == "-f": SCREEN_FULLSCREEN = True scr_options = 0 if SCREEN_FULLSCREEN: scr_options += FULLSCREEN screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT),scr_options ,32) pygame.display.set_icon(util.load_image("kuvake")) pygame.display.set_caption("Trip on the Funny Boat") init() joy = None if pygame.joystick.get_count() > 0: joy = pygame.joystick.Joystick(0) joy.init() try: util.load_music("JDruid-Trip_on_the_Funny_Boat") if Variables.music: pygame.mixer.music.play(-1) except: # It's not a critical problem if there's no music pass pygame.time.set_timer(NEXTFRAME, 1000 / FPS) # 30 fps Water.global_water = Water() main_selection = 0 while True: main_selection = Menu(screen, ("New Game", "High Scores", "Options", "Quit"), main_selection).run() if main_selection == 0: # New Game selection = Menu(screen, ("Story Mode", "Endless Mode")).run() if selection == 0: # Story score = Game(screen).run() Highscores(screen, score).run() elif selection == 1: # Endless score = Game(screen, True).run() Highscores(screen, score, True).run() elif main_selection == 1: # High Scores selection = 0 while True: selection = Menu(screen, ("Story Mode", "Endless Mode", "Endless Online"), selection).run() if selection == 0: # Story Highscores(screen).run() elif selection == 1: # Endless Highscores(screen, endless = True).run() elif selection == 2: # Online Highscores(screen, endless = True, online = True).run() else: break elif main_selection == 2: # Options selection = Options(screen).run() else: #if main_selection == 3: # Quit return
def main(): pygame.init() noparticles = False usealpha = True if len(sys.argv) > 1: for arg in sys.argv: if arg == "-np": noparticles = True elif arg == "-na": usealpha = False screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_icon(util.load_image("kuvake")) pygame.display.set_caption("Trip on the Funny Boat") init() joy = None if pygame.joystick.get_count() > 0: joy = pygame.joystick.Joystick(0) joy.init() try: util.load_music("JDruid-Trip_on_the_Funny_Boat") pygame.mixer.music.play(-1) except: pass pygame.time.set_timer(NEXTFRAME, 1000 / FPS) # 30 fps Water.global_water = Water(usealpha) while True: selection = Menu(screen).run() if selection == Menu.NEWGAME: #print "New game!" selection = Menu(screen, gametype_select=True).run() if selection == Menu.STORY: score = Game(screen, usealpha, noparticles).run() #print "Final score: " + str(score) Highscores(screen, score).run() elif selection == Menu.ENDLESS: score = Game(screen, usealpha, noparticles, True).run() #print "Final score: " + str(score) Highscores(screen, score, True).run() elif selection == Menu.HIGHSCORES: #print "High scores!" selection = Menu(screen, gametype_select=True).run() if selection == Menu.STORY: Highscores(screen).run() elif selection == Menu.ENDLESS: Highscores(screen, endless=True).run() #elif selection == Menu.OPTIONS: #print "Options!" #elif selection == Menu.QUIT: else: #print "Quit! :-(" return
def main(self): self.music.play() # Screen base self.screen.fill((0, 0, 0)) self.screen.blit(self.img_background, self.img_background_rect) highscores = Highscores() # Main instances pavement = Pavement(self.unit) snake = Snake(self.unit) foods = Foods(self.unit) walls = Walls(self.unit) score = Score(self.unit, self.surface_rect) nextgold = random.randint( *Constants.TIMERANGE_GOLD ) * Constants.FPS # first gold between 30 & 60 seconds makegold = False nextwall = random.randint( *Constants.TIMERANGE_WALL ) * Constants.FPS # first gold between 30 & 60 seconds makewall = False updatestats = True counter = 0 flag_music = True flag_pause = False #MAIN LOOP while self.running: time = pygame.time.get_ticks() for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.running = False elif event.key == pygame.K_m: flag_music = not flag_music if flag_music: self.music.play() else: self.music.stop() elif event.key == pygame.K_1: pygame.image.save(self.screen, "screenshot.jpg") elif event.key == pygame.K_SPACE or event.key == pygame.K_p: flag_pause = True self.print_text("PAUSE") while flag_pause: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_p or event.key == pygame.K_SPACE: flag_pause = False else: # Time to change direction action = 0 if event.key == pygame.K_UP or event.key == pygame.K_w: action = 1 elif event.key == pygame.K_DOWN or event.key == pygame.K_s: action = 2 elif event.key == pygame.K_LEFT or event.key == pygame.K_a: action = 3 elif event.key == pygame.K_RIGHT or event.key == pygame.K_d: action = 4 if action: self.sounds.play("move") snake.action(action) # Snake movements and pavement reactions snake.move() pavement.passage(snake.head) pavement.make_regrow(snake.tail) # Snake has eaten? if foods.check(snake.head): updatestats = True snake.grow(Constants.GROW) score.add_score(foods.score) self.sounds.play("eat") # Snake if walls.check(snake.head): snake.alive = False # Snake is dead? if not snake.alive: #blood splash (bin on head, little on body) pavement.bloodsplat(snake.head) [ pavement.bloodsplat(x, 1) for x in snake.body if random.randint(0, 2) == 0 ] #redraw all the snake snake.set_dirty(1) self.sounds.play("splat") self.running = False # Gold generator (After pseudo-random time a golden apple will appear) nextgold -= 1 if nextgold < 0: makegold = True nextgold = random.randint( *Constants.TIMERANGE_GOLD) * Constants.FPS # Wall generator (After pseudo-random time a wall will appear) nextwall -= 1 if nextwall < 0: makewall = True nextwall = random.randint( *Constants.TIMERANGE_WALL) * Constants.FPS # Foods request to create an apple # Game has to provide to Foods the list of forbidden blocks if foods.needapple or makegold or makewall: forbidden = [[-1, -1]] forbidden.extend(foods.get_forbidden()) forbidden.extend(snake.get_forbidden()) forbidden.extend(walls.get_forbidden()) # Creates the apples and make the pavement Grass if foods.needapple: newpos = foods.make_apple(forbidden) pavement.make_grass(newpos) forbidden.extend(newpos) if makegold: self.sounds.play('ding') newpos = foods.make_gold(forbidden) pavement.make_grass(newpos) forbidden.extend(newpos) makegold = False if makewall: self.sounds.play('fall') newpos = walls.make_solid(forbidden) pavement.make_none(newpos) forbidden.extend(newpos) makewall = False # Foods request pavement update for pos in foods.refresh: pavement.passage(pos) foods.refresh.remove(pos) del pos # Updates and draws pavement.update() pavement.draw(self.surface) walls.update() walls.draw(self.surface) snake.update() snake.draw(self.surface) foods.update() foods.draw(self.surface) if updatestats or not counter % Constants.FPS: score.set_length(snake.length) score.update() score.draw(self.screen) updatestats = False if not counter % Constants.FPS: score.add_second() counter = 0 # Surface on surface... weeee! self.screen.blit(self.surface, self.surface_rect) pygame.display.update() self.clock.tick(self.tick) counter += 1 #END OF MAIN LOOP if not snake.alive: self.print_text("GAME OVER") if highscores.check(score.score, score.elapse): current_string = '' complete = False inputbox = InputBox(self.unit) inputbox.rect.centerx = self.screen.get_rect().centerx inputbox.rect.centery = self.screen.get_rect().centery inputbox.draw(self.screen) pygame.display.update() pygame.event.clear() redraw = False while not complete: event = pygame.event.wait() if event.type == pygame.QUIT: return if event.type != pygame.KEYDOWN: continue if event.key == pygame.K_BACKSPACE: current_string = current_string[:-1] redraw = True elif event.key == pygame.K_RETURN: if len(current_string) == 0: current_string = 'Mysterious player' complete = True elif event.unicode: if len(current_string) <= 15: c = ord(event.unicode) if c >= 32 and c <= 126 or c == 8: current_string += event.unicode redraw = True if redraw: redraw = False inputbox.set_text(current_string) inputbox.update() inputbox.draw(self.screen) pygame.display.update() position = highscores.insert(current_string, score.score, score.elapse) highscores.save() scored = {'index': position, 'scored': True} else: counter = Constants.FPS * 3 # 3 seconds pygame.display.update() while counter > 0: for event in pygame.event.get(): if event.type == pygame.QUIT or event.type == pygame.KEYDOWN: counter = 0 self.clock.tick(self.tick) pygame.display.update() counter -= 1 scored = { 'elapse': score.elapse, 'score': score.score, 'scored': False } ts = TitleScreen(self.screen, self.unit, self.preferences) ts.highscores(scored) del ts self.music.stop() return
def highscores(self, scored=False): #scored = {'elapse':str,'score':int,'index':int,'scored':bool} back = False btn_back = MenuButton("BACK", self.unit, (self.unit * 17, self.unit * 3)) btn_back.rect.centerx = self.screen.get_rect().centerx btn_back.rect.y = self.unit * 45 btn_back.set_status(1) self.draw_background() highscores = Highscores() if scored and not scored['scored']: highscores.insert("Your name", str(scored["score"]), scored["elapse"]) box = pygame.Surface((self.size[1], self.size[1])) box.fill((255, 255, 255)) box.set_alpha(150) box_rect = box.get_rect() box_rect.centerx = self.screen.get_rect().centerx box_rect.y = 0 self.screen.blit(box, box_rect) font_text = pygame.font.Font(data.filepath("font", "abel.ttf"), int(self.unit * 1.6)) font_title = pygame.font.Font(data.filepath("font", "abel.ttf"), int(self.unit * 5)) color_text = (30, 30, 30) color_title = (122, 30, 30) posy = 8 * self.unit advance = int(2.2 * self.unit) btn_back.update() self.screen.blit(btn_back.image, btn_back.rect) title = font_title.render("HIGH SCORES", True, color_title) rect = title.get_rect() rect.centerx = self.screen.get_rect().centerx rect.y = 1 * self.unit self.screen.blit(title, rect) line = pygame.Surface((self.size[1], int(self.unit * 2.2))) line.fill((255, 255, 255)) line.set_alpha(50) line_rect = line.get_rect() line_rect.centerx = self.screen.get_rect().centerx line_me = pygame.Surface((self.size[1], int(self.unit * 2.2))) line_me.fill((30, 200, 30)) line_me.set_alpha(50) ii = 0 for el in highscores.scores: index = font_text.render(str(ii + 1), True, color_title) name = font_text.render(el["name"], True, color_text) elapse = font_text.render(el["elapse"], True, color_text) score = font_text.render(el["score"], True, color_text) line_rect.y = posy if not ii % 2: self.screen.blit(line, line_rect) if scored and scored["scored"] and ii == scored[ "index"] or ii == Constants.MAXSCORE: self.screen.blit(line_me, line_rect) rect = index.get_rect() rect.y = posy rect.x = self.screen.get_rect().centerx - self.unit * 13 if ii < Constants.MAXSCORE: self.screen.blit(index, rect) rect.x += self.unit * 3 self.screen.blit(name, rect) rect.x += self.unit * 16 self.screen.blit(elapse, rect) rect.x += self.unit * 5 self.screen.blit(score, rect) posy += advance ii += 1 while not back: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE or event.key == pygame.K_RETURN or event.key == pygame.K_SPACE: return elif event.key == pygame.K_1: pygame.image.save(self.screen, "screenshot.jpg") elif event.type == pygame.QUIT: self.running = False return btn_back.update() btn_back.draw(self.screen) pygame.display.flip() self.clock.tick(30)
def highscores(self,scored=False): #scored = {'elapse':str,'score':int,'index':int,'scored':bool} back = False btn_back = MenuButton("BACK",self.unit,(self.unit*17, self.unit*3)) btn_back.rect.centerx = self.screen.get_rect().centerx btn_back.rect.y = self.unit*45 btn_back.set_status(1) self.draw_background() highscores = Highscores() if scored and not scored['scored']: highscores.insert("Your name",str(scored["score"]),scored["elapse"]) box = pygame.Surface((self.size[1],self.size[1])) box.fill((255,255,255)) box.set_alpha(150) box_rect = box.get_rect() box_rect.centerx = self.screen.get_rect().centerx box_rect.y = 0 self.screen.blit(box,box_rect) font_text = pygame.font.Font(data.filepath("font", "abel.ttf"), int(self.unit * 1.6)) font_title = pygame.font.Font(data.filepath("font", "abel.ttf"), int(self.unit * 5)) color_text = (30,30,30) color_title = (122,30,30) posy = 8*self.unit advance = int(2.2*self.unit) btn_back.update() self.screen.blit(btn_back.image, btn_back.rect) title = font_title.render("HIGH SCORES",True,color_title) rect = title.get_rect() rect.centerx = self.screen.get_rect().centerx rect.y = 1*self.unit self.screen.blit(title,rect) line = pygame.Surface((self.size[1],int(self.unit*2.2))) line.fill((255,255,255)) line.set_alpha(50) line_rect = line.get_rect() line_rect.centerx = self.screen.get_rect().centerx line_me = pygame.Surface((self.size[1],int(self.unit*2.2))) line_me.fill((30,200,30)) line_me.set_alpha(50) ii=0 for el in highscores.scores: index = font_text.render(str(ii+1),True,color_title) name = font_text.render(el["name"],True,color_text) elapse = font_text.render(el["elapse"],True,color_text) score = font_text.render(el["score"],True,color_text) line_rect.y = posy if not ii % 2: self.screen.blit(line,line_rect) if scored and scored["scored"] and ii==scored["index"] or ii==Constants.MAXSCORE: self.screen.blit(line_me,line_rect) rect = index.get_rect() rect.y = posy rect.x = self.screen.get_rect().centerx-self.unit*13 if ii < Constants.MAXSCORE: self.screen.blit(index, rect) rect.x+= self.unit*3 self.screen.blit(name, rect) rect.x+= self.unit*16 self.screen.blit(elapse, rect) rect.x+= self.unit*5 self.screen.blit(score, rect) posy += advance ii+=1 while not back: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE or event.key == pygame.K_RETURN or event.key == pygame.K_SPACE: return elif event.key == pygame.K_1: pygame.image.save(self.screen, "screenshot.jpg") elif event.type == pygame.QUIT: self.running = False return btn_back.update() btn_back.draw(self.screen) pygame.display.flip() self.clock.tick(30)