def __init__(self): """Initialise the game, and create game resources""" pygame.init( ) #This initialises background settings that Pygame needs to work properly self.settings = Settings() #self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN) These settings are for fullscreen mode #self.settings.screen_width = self.screen.get_rect().width but have been commented out as i prefer #self.settings.screen_height = self.screen.get_rect().height windowed mode self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height )) #This creates a display window for the game pygame.display.set_caption("Alien Invasion") #Create an instance to store game statistics # and create a scoreboard self.stats = GameStats(self) self.sb = Scoreboard(self) self.ship = Ship(self) #Make an instance of ship self.bullets = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self._create_fleet() #This is a group for the fleet of aliens #Make play button self.play_button = Button(self, "Play") #Set the background colour self.bg_colour = ( 230, 230, 230 ) #Colours defined by a mix of RGB this mixes equal of all
def create_buttons(self): self.start_button = Button(rect=(STARTBTN_X, BTN_Y2, 100, 50), color=STARTBTNCOL1, hover_color=STARTBTNCOL2, text='Start', function=self.start_button_function) self.pause_button = Button(rect=(PAUSEBTN_X, BTN_Y2, 100, 50), color=PAUSEBTNCOL1, hover_color=PAUSEBTNCOL2, text='Pause', function=self.pause_button_function) self.next_button = Button(rect=(NEXTBTN_X, BTN_Y2, 100, 50), color=PAUSEBTNCOL1, hover_color=PAUSEBTNCOL2, text='>', function=self.next_button_function) self.reset_button = Button(rect=(NEXTBTN_X + 125, BTN_Y2, 100, 50), color=PAUSEBTNCOL1, hover_color=PAUSEBTNCOL2, text='Reset', function=self.reset_button_function) self.new_array_button = Button(rect=(NEXTBTN_X + 250, BTN_Y2, 100, 50), color=PAUSEBTNCOL1, hover_color=PAUSEBTNCOL2, text='New Array', function=self.new_array_function)
def __init__(self): pygame.init() self.player = Player(settings.screen, self) self.ball = Ball(settings.screen, self.player) self.go_button = Button(settings.screen) self.go = False self.level = settings.get_level()[0]
def __init__(self, score_val, player_name): os.environ['SDL_VIDEO_CENTERED'] = '1' pygame.init() pygame.mouse.set_visible(True) self.running = True self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) self.gameover_buttons = [] self.gameover_buttons.append( Button('Assets/UI/restart.png', 'Assets/UI/restart_1.png', 206, 425, 6)) self.gameover_buttons.append( Button('Assets/UI/home.png', 'Assets/UI/home_1.png', 296, 425, 7)) self.game_over_font = pygame.font.Font('SigmarOne.ttf', 55) self.game_over_tag = self.game_over_font.render( "GAME OVER", True, (255, 255, 255)) self.player_name = player_name self.obtained_score_font = pygame.font.Font('SigmarOne.ttf', 30) self.obtained_score_tag = self.obtained_score_font.render( "SCORE: " + str(score_val), True, (255, 255, 255)) self.score_tag_rect = self.obtained_score_tag.get_rect() self.score_tag_rect.center = (275, 310) self.score_tag_rect.y = 320 # sound effects: MOVE IT TO UTIL FILE LATER self.click_sound = pygame.mixer.Sound('Assets/music/clicked.wav') self.hover_sound = pygame.mixer.Sound('Assets/music/hover.wav') mixer.music.load('Assets/music/game_over_music.wav') mixer.music.play() # save high score to file and then sort the file self.save_score(player_name, score_val) sort_file() self.game_loop()
def __init__(self): self.size = self.width, self.height = 640, 640 self.fill_clr = pygame.Color(0, 97, 100) self.txt_clr = pygame.Color(255, 255, 255) self.watch = True self.b_w, self.b_h = 128, 50 self.back_button = Button('Назад', 24, 24, self.b_w, self.b_h) self.offset, self.ac_hei, self.leng = 60, 80, 500 self.aff_one = 100 ach_cod = [] self.score = 0 self.real_got = [] with open("dostig.txt", encoding="utf-8") as ac: ach_cod = str(ac.read()) # чтение из файла сохранения ach_cod = ach_cod.split(',') for i in range(1, len(ach_cod)): # Вывод достижений if ach_cod[i] == 'T': if i == 1: self.real_got.append('Начало положено. ' '(Запустить игру, +10)') self.score += 10 if i == 2: self.real_got.append('Путь к развитию. ' '(Получена неплохая концовка, +150)') self.score += 150 if i == 3: self.real_got.append('Восход. ' '(Получена лучшая концовка, +300)') self.score += 300 if i == 4: self.real_got.append('Пучина греха. ' '(Получена худшая концовка, +100)') self.score += 100
def __init__(self,name): Screen.__init__(self,name) self.titleImage = pygame.image.load("Media/ChapFCS-title.gif").convert() self.titlePosition = ((self.screen.get_width()-self.titleImage.get_width())/2, (self.screen.get_height()/4)) self.tablePosition = (100,175) self.screen.fill([0,0,0]) # just black, no graphic background image self.ButtonNW = self.buttons(bgcolor = (0,0,255), callback=self.systemOptions, **Button.standardButton("NW",["System","Options"],self.screen)) self.ButtonNE = self.buttons(bgcolor = (0,0,255), callback=self.matchOptions, **Button.standardButton("NE",["Field","Options"],self.screen)) self.ButtonSE = self.buttons(bgcolor = (0,0,255), callback=self.about, **Button.standardButton("SE","About",self.screen)) self.ButtonS = self.buttons(bgcolor = (255,255,255), callback=self.nextMatch, lcolor = (0,0,0), **Button.standardButton("S",["Next","Match"],self.screen)) self.dataTable = self.tables(fontsize=20,font="monospace") self.dataTable.addData("Field Name: ",align="right") self.dataTable.addData(Settings.fieldName, bold=True, name="fieldName",bgcolor=(50,50,50),callback=self.setFieldName) self.dataTable.endRow() self.dataTable.addData("Next Match: ", align="right") self.dataTable.addData(Settings.matchNumber,name="match",callback=self.setMatchNumber,bold=True) self.dataTable.endRow() # put out the title self.screen.blit(self.titleImage,self.titlePosition) self.dataTable.position = self.tablePosition
def __init__(self): """Initialize the game, and create game ressources.""" pygame.init() self.settings = Settings() self.clock = pygame.time.Clock() # # Switch the comments on these blocks for fullscreen or window screen # self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) # self.settings.screen_width = self.screen.get_rect().width # self.settings.screen_height = self.screen.get_rect().height self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption('COVID Invasion') # Create an instance to store game statistics # and create a scoreboard self.stats = GameStats(self) self.scoreboard = Scoreboard(self) self.ship = Ship(self) self.bullets = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self._create_fleet() self.play_button = Button(self, 'Play')
def __init__(self,name,globalName,mode,title,color): Screen.__init__(self,name) self.ButtonS = self.buttons(bgcolor = (0,0,255), callback=self.done, **Button.standardButton("S","Done",self.screen)) self.ButtonNW = self.buttons(bgcolor = (0,0,255), callback=self.cancel, **Button.standardButton("NW","Cancel",self.screen)) self.ButtonNE = self.buttons(bgcolor = (0,0,255), callback=self.up, upCallback=self.release, holdCallback = self.holdCountUp, rotation = 180, **removeKey(Button.standardButton("NE","V",self.screen),'rotation')) self.ButtonSE = self.buttons(bgcolor = (0,0,255), callback=self.down, upCallback=self.release, holdCallback = self.holdCountDown, **Button.standardButton("SE","V",self.screen)) self.ButtonSW = self.buttons(bgcolor = (255,0,0), callback=self.permenance, **Button.standardButton("SW","Permenance",self.screen)) self.globalName = globalName self.mode = mode self.color = color self.title = title self.heldCountUp = False self.heldCountDown = False self.heldLastTime = datetime.datetime.now() self.needsUpdate = True self.PT = True
def _themes_menu(self): screen = self.screen action = None buttons = [] ypos = 100 for theme_name in THEMES: button = Button(theme_name) button.setCords((self.screen.get_width()/2) - (self.start_button.rect.width/2), ypos) buttons.append(button) ypos += 100 while True: for event in pygame.event.get(): if event.type == MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() for button in buttons: if button.is_pressed(mouse_pos): self.theme = button.text.lower() self._set_theme() fname = self._config_file('theme.config') with open(fname, 'w') as theme_config: theme_config.write(self.theme) return if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): return False screen.blit(self.background, (0,0)) for button in buttons: screen.blit(button.image, button.rect) pygame.display.flip() self.clock.tick(TARGET_FPS)
class Game(): def __init__(self): pygame.init() self.player = Player(settings.screen, self) self.ball = Ball(settings.screen, self.player) self.go_button = Button(settings.screen) self.go = False self.level = settings.get_level()[0] def loop(self): functions.check_events(self.player, self.ball, self.go, self) settings.screen.fill(settings.background_color) self.player.update() self.ball.update(self.level, self.player) if self.go: self.go_button.blitme() functions.update_level(self.level) pygame.display.flip() def game_over(self): self.ball.paused = True self.player.paused = True self.go = True def restart(self): self.player = Player(settings.screen, self) self.ball = Ball(settings.screen, self.player) self.go = False self.level = settings.get_level()[0]
def __init__(self, button_pin, event_start, event_stop, white_lamp_controller, semaphore_mode): Thread.__init__(self) self.button = Button(button_pin) self.event_start = event_start self.event_stop = event_stop self.white_lamp_controller = white_lamp_controller self.semaphore_mode = semaphore_mode
def load_buttons(): dummy_file_path = os.path.join(os.getcwd(), "audio", "dummy.wav") for idx in range(64): file_path = os.path.join(os.getcwd(), "audio", samples_list[idx]) try: buttons[idx] = Button(idx, file_path, False) except FileNotFoundError: buttons[idx] = Button(idx, dummy_file_path, False)
def __init__(self): pyxel.init(180, 120, caption="Keymusic Py", scale=4) self.keys = [ Button([11, 3], [20, 100], 4, [0, 1, "A2"], pyxel.KEY_A), Button([10, 9], [40, 100], 4, [1, 2, "B2"], pyxel.KEY_S), Button([12, 5], [60, 100], 4, [2, 3, "C2"], pyxel.KEY_F), Button([15, 14], [80, 100], 4, [3, 4, "D2"], pyxel.KEY_G), ] pyxel.run(self.update, self.draw)
def __init__(self): Screen.__init__(self,"TeamAssign") self.ButtonNW = self.buttons(bgcolor = (100,100,0), callback=self.reboot, **Button.standardButton("NW","Reboot",self.screen)) self.ButtonSW = self.buttons(bgcolor = (0,0,255), callback=self.setup, **Button.standardButton("SW","Yes",self.screen)) self.ButtonNE = self.buttons(bgcolor = (0,0,255), callback=self.matchSetup, **Button.standardButton("NE",["Match","Setup"],self.screen)) self.ButtonSE = self.buttons(bgcolor = (0,0,255), callback=self.quit, **Button.standardButton("SE","Quit",self.screen))
def __init__(self,name): Screen.__init__(self,name) self.ButtonNW = self.buttons(bgcolor = (0,0,255), callback=self.systemOptions, **Button.standardButton("NW",["System","Options"],self.screen)) self.ButtonSW = self.buttons(bgcolor = (0,0,255), callback=self.setup, **Button.standardButton("SW","Setup",self.screen)) self.ButtonNE = self.buttons(bgcolor = (0,0,255), callback=self.matchSetup, **Button.standardButton("NE",["Match","Options"],self.screen)) self.ButtonSE = self.buttons(bgcolor = (0,0,255), callback=self.quit, **Button.standardButton("SE","Quit",self.screen))
def init_buttons(self): self.all_buttons.append( Button('Assets/UI/play.png', 'Assets/UI/play_1.png', 175, 250, 1)) self.all_buttons.append( Button('Assets/UI/options.png', 'Assets/UI/options_1.png', 150, 500, 2)) self.all_buttons.append( Button('Assets/UI/highscore.png', 'Assets/UI/highscore_1.png', 150, 600, 3)) self.all_buttons.append( Button('Assets/UI/exit.png', 'Assets/UI/exit_1.png', 150, 700, 4))
def draw_ui(self): self.buttons = [] astar_button = Button(0, 3, 40, 100, DISPLAY, WHITE, (150, 150, 150), "RUN A*", self.handle_astar, 25) dijkstra_button = Button(WIDTH-153, 3, 40, 150, DISPLAY, WHITE, (150, 150, 150), "RUN DIJKSTRA", self.handle_dijkstra, 25) # self.buttons.append(astar_button, dijkstra_button) self.buttons.extend((astar_button, dijkstra_button)) for button in self.buttons: button.create()
def __init__(self,name,match): Screen.__init__(self,name) self.match = match self.match.fakeTeams() self.tablePosition = (130,10) self.trashcanpic = pygame.image.load("Media/trashCan2.png").convert() self.trashcanpic = pygame.transform.scale(self.trashcanpic, (37,50)) self.refreshpic = pygame.image.load("Media/refresh.png").convert() self.refreshpic = pygame.transform.scale(self.refreshpic, (50,50)) self.cb1 = (150,150,150) self.cb2 = (50,50,50) self.sideBlue = (150,150,255) self.sideRed = (255,150,150) self.roboSel = None # the index into the Table of robots # self.trashList = [] self.AssignButtonPressed = None #This is set to one of NW NE SW SE or NOne self.assignedTeams = { "NW":None, "NE":None, "SW":None, "SE":None } self.screen.fill([0,0,0]) # just black, no graphic background image self.Button = dict() self.Button["NW"] = self.buttons(bgcolor = (0,0,255), callback=self.teamAssign,rock = "NW",fontsize = 25, **Button.standardButton("NW",self.assignedTeams["NW"],self.screen)) self.Button["NE"] = self.buttons(bgcolor = (255,0,0), callback=self.teamAssign,rock = "NE",fontsize = 25, **Button.standardButton("NE",self.assignedTeams["NE"],self.screen)) self.Button["SW"] = self.buttons(bgcolor = (0,0,255), callback=self.teamAssign,rock = "SW",fontsize = 25, **Button.standardButton("SW",self.assignedTeams["SW"],self.screen)) self.Button["SE"] = self.buttons(bgcolor = (255,0,0), callback=self.teamAssign,rock = "SE",fontsize = 25, **Button.standardButton("SE",self.assignedTeams["SE"],self.screen)) self.ButtonS = self.buttons(bgcolor = (255,255,255), callback=self.done, lcolor = (0,0,0), **Button.standardButton("S","Done",self.screen)) self.ButtonDel = self.buttons(graphic = self.trashcanpic, callback = self.trashButton,rock = "DelButton", size=(37,50), position=(130,270), rotation=0,labels=["",""]) self.ButtonRef = self.buttons(graphic = self.refreshpic, callback = self.refresh,rock = "RefreshButton", size=(50,50), position=(300,270), rotation=0,labels=["",""]) self.createSides() self.sWidth = self.screen.get_width() self.sHeight = self.screen.get_height() self.boxHeight = self.sWidth/9 self.boxWidth = self.sHeight/3 self.one = "1" self.two = "2" self.myfont = pygame.font.SysFont("monospace", 30) self.myfont.set_bold(True) self.N1 = self.myfont.render(self.one,1,(255,255,255)) self.N2 = self.myfont.render(self.two,1,(255,255,255)) self.screen.blit(self.N1,(self.boxWidth/2-10,self.boxHeight+10)) self.screen.blit(self.N2,(self.boxWidth/2-10,self.sHeight-(self.boxHeight+40))) self.screen.blit(self.N1,(self.sWidth-(self.boxWidth/2)-10,self.boxHeight+10)) self.screen.blit(self.N2,(self.sWidth-(self.boxWidth/2)-10,self.sHeight-(self.boxHeight+40)))
def __init__(self,name): Screen.__init__(self,name) self.ButtonNW = self.buttons(bgcolor = (255,0,0), callback=self.button1, **Button.standardButton("NW",["Button","1"],self.screen)) self.ButtonSW = self.buttons(bgcolor = (255,0,0), callback=self.button2, **Button.standardButton("SW",["Button","2"],self.screen)) self.ButtonNE = self.buttons(bgcolor = (255,0,0), callback=self.button3, **Button.standardButton("NE",["Button","3"],self.screen)) self.ButtonSE = self.buttons(bgcolor = (255,0,0), callback=self.button4, **Button.standardButton("SE",["Button","4"],self.screen)) self.ButtonS = self.buttons(bgcolor = (255,0,0), callback=self.quit, **Button.standardButton("S","Quit",self.screen))
def get_game_board(self): game_board = [] for y in range(self.board_height): game_board.append([]) for x in range(self.board_length): button = Button(self.length_offset + self.tile_length * x, self.height_offset + self.tile_height * y, self.tile_length, self.tile_height) button.highlight_color = (230, 230, 230) game_board[y].append(Square(None, button)) return game_board
def __init__(self,name): Screen.__init__(self,name) self.ButtonNW = self.buttons(bgcolor = (255,0,0), callback=self.buttontest, **Button.standardButton("NW",["Button","Test"],self.screen)) self.ButtonSW = self.buttons(bgcolor = (255,0,0), callback=self.networktest, **Button.standardButton("SW",["Network","Test"],self.screen)) self.ButtonNE = self.buttons(bgcolor = (255,0,0), callback=self.audiotest, **Button.standardButton("NE",["Audio","Test"],self.screen)) self.ButtonSE = self.buttons(bgcolor = (255,0,0), callback=self.bletests, **Button.standardButton("SE",["Bluetooth","Tests"],self.screen)) self.ButtonS = self.buttons(bgcolor = (255,255,255), callback=self.quit,lcolor=(0,0,0), **Button.standardButton("S","Done",self.screen))
def __init__(self, x, y, identity): self.pieces = 0 self.color = "" self.identity = identity self.x = x self.y = y if 24 > identity > 11: self.button = Button(x, 500, 56, 383) else: if identity == 24 or identity == 25: self.button = Button(x, y, 56, 383) else: self.button = Button(x, y, 900 - x, 900 - y)
def __init__(self,name): Screen.__init__(self,name) self.ButtonNW = self.buttons(bgcolor = (255,0,0), callback=self.mode1broadcast, **Button.standardButton("NW",["Broadcast","Mode 0"],self.screen)) self.ButtonSW = self.buttons(bgcolor = (255,0,0), callback=self.stopbroadcast, **Button.standardButton("SW","STOP",self.screen)) self.ButtonNE = self.buttons(bgcolor = (255,0,0), callback=self.connection, **Button.standardButton("NE",["Connection","Test"],self.screen)) self.ButtonSE = self.buttons(bgcolor = (255,0,0), callback=self.mode2broadcast, **Button.standardButton("SE",["Broadcast","Mode 1"],self.screen)) self.ButtonS = self.buttons(bgcolor = (255,255,255), callback=self.done,lcolor=(0,0,0), **Button.standardButton("S","Done",self.screen))
def end_game(_mouse_x, _mouse_y): if game.look_for_winner() == 3: text_endgame = 'draw' else: text_endgame = 'player {} wins'.format(game.look_for_winner()) czcionka = pygame.font.SysFont("comicsans", 70) text_render_endgame = czcionka.render(text_endgame, True, (0, 0, 0)) screen.fill(bg_green) screen.blit(text_render_endgame, (500, 300)) pygame.display.update close_button = Button((0, 255, 255), 375, 300, 100, 60, 'xkill') while running: if close_button.is_over(_mouse_x, _mouse_y): terminate_game()
def __init__(self,name): Screen.__init__(self,name) self.tablePosition = (20,150) self.screen.fill([0,0,0]) # just black, no graphic background image self.ButtonNW = self.buttons(bgcolor = (0,0,255), callback=self.setTimes, **Button.standardButton("NW",["Times &","Match #"],self.screen)) self.ButtonNE = self.buttons(bgcolor = (0,0,255), callback=self.remoteControl, **Button.standardButton("NE",["Remote","Control"],self.screen)) self.ButtonSW = self.buttons(bgcolor = (0,0,255), callback=self.setFieldName, **Button.standardButton("SW",["Field","Name"],self.screen)) self.ButtonS = self.buttons(bgcolor = (255,255,255), callback=self.done,lcolor = (0,0,0), **Button.standardButton("S","Done",self.screen))
def run_game(): # Initialize pygame, settings, and screen object. pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("almykivasion!!!") play_button = Button(ai_settings, screen, "Play") # Create an instance to store game statistics and create a scoreboard. stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) # Make a ship, a group of bullets, and a group of aliens. ship = Ship(ai_settings, screen) bullets = Group() aliens = Group() gf = GameFunctions(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button) # Create the fleet of aliens. gf.create_fleet() # Start the main loop for the game. while True: gf.check_events() if stats.game_active: ship.update() gf.update_bullets() gf.update_aliens() gf.update_screen()
def __init__(self): Screen.__init__(self,"fieldNumberScreen") self.screen.fill([0,0,0]) # just black, no graphic background image self.buttonHeight = self.height/3 self.buttonPadding = self.width/25 self.matchImage, self.autoImage, self.teleopImage, self.endGameImage = self.numberImages(self.buttonHeight) self.buttonWidth = self.matchImage.get_width() self.matchPos, self.autoPos, self.teleopPos, self.endGamePos = self.numberPositions(self.buttonHeight, self.buttonWidth, self.buttonPadding) self.matchButton = self.buttons((self.buttonWidth,self.buttonHeight),self.matchPos, graphic=self.matchImage, callback=self.editMatchNumber) self.autoButton = self.buttons((self.buttonWidth,self.buttonHeight),self.autoPos, graphic=self.autoImage, callback=self.editAutoNumber) self.teleopButton = self.buttons((self.buttonWidth,self.buttonHeight),self.teleopPos, graphic=self.teleopImage, callback=self.editTeleopNumber) self.endGameButton = self.buttons((self.buttonWidth,self.buttonHeight),self.endGamePos, graphic=self.endGameImage, callback=self.editEndGameNumber) self.ButtonS = self.buttons(bgcolor = (0,0,255), callback=self.done, **Button.standardButton("S","Done",self.screen))
def add_buttons(cls, *button_ids): for button in button_ids: cls.buttons[button] = Button(button, cls.button_blank, (0, 0), button) print(cls.buttons)
def __init__(self, player_name): # declare variables for UI navigation # load UI images and background images os.environ['SDL_VIDEO_CENTERED'] = '1' pygame.init() self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) self.player_name = player_name self.running = True self.start_img = load_image('Assets/background/start.png') self.instructions_img = load_image( 'Assets/background/instructions.png') self.instruction_window = False self.all_buttons = [] self.next_button = [] self.next_button.append( Button('Assets/UI/next.png', 'Assets/UI/next_1.png', 476, 775, 5)) self.init_buttons() # sound effects self.click_sound = pygame.mixer.Sound('Assets/music/clicked.wav') self.hover_sound = pygame.mixer.Sound('Assets/music/hover.wav') # fonts to display player name font = pygame.font.Font('SigmarOne.ttf', 20) self.player_name_tag = font.render(self.player_name, True, (255, 255, 255)) self.game_loop()
def init(self): flags = 0 if not ANDROID: os.environ['SDL_VIDEO_CENTERED'] = '1' WINSIZE = 480, 800 else: WINSIZE = 0, 0 flags |= pygame.FULLSCREEN pygame.init() mixer.init() # Map the back button to the escape key. if ANDROID: android.init() android.map_key(android.KEYCODE_BACK, pygame.K_b) self.clock = pygame.time.Clock() if not ANDROID: self.icon = pygame.image.load(get_resource('android-icon.png')) pygame.display.set_icon(self.icon) screen = self.screen = pygame.display.set_mode(WINSIZE, flags) self.width, self.height = screen.get_width(), screen.get_height() pygame.display.set_caption('Mazenum') self.score_font = pygame.font.Font(get_resource(join("fonts", "FreeSans.ttf")), 25) self.completed_font = pygame.font.Font(get_resource(join("fonts", "FreeSans.ttf")), 40) self.start_button = Button("Start game") self.playboard = PlayBoard(screen, self.COLUMNS, self.ROWS, self.header_height) self._set_background() self.is_game_over = False
class ButtonController(Thread): def __init__(self, button_pin, event_start, event_stop, white_lamp_controller, semaphore_mode): Thread.__init__(self) self.button = Button(button_pin) self.event_start = event_start self.event_stop = event_stop self.white_lamp_controller = white_lamp_controller self.semaphore_mode = semaphore_mode def invert_start_stop_state(self): if self.event_start.isSet(): self.event_start.clear() self.event_stop.set() else: self.event_start.set() self.event_stop.clear() def run(self): while True: duration = self.button.wait_for_pressure() # print("Pressure detected") if duration >= SEMAPHORE_MODE_SWITCH_THRESHOLD: self.semaphore_mode.invert() self.white_lamp_controller.blink_twice() # print("Semaphore mode inverted") else: self.invert_start_stop_state()
def __init__(self,name): Screen.__init__(self,name) self.screen.fill([0,0,0]) # just black, no graphic background image # go ahead and calculate the time display/buttons self.buttonHeight = self.height/3 self.buttonPadding = self.width/25 self.matchImage, self.autoImage, self.teleopImage, self.endGameImage = self.numberImages(self.buttonHeight) self.buttonWidth = self.matchImage.get_width() self.matchPos, self.autoPos, self.teleopPos, self.endGamePos = self.numberPositions(self.buttonHeight, self.buttonWidth, self.buttonPadding) self.matchButton = self.buttons((self.buttonWidth,self.buttonHeight),self.matchPos, graphic=self.matchImage, callback=self.editMatchNumber,gpio=HARDWARE.button.NW) self.autoButton = self.buttons((self.buttonWidth,self.buttonHeight),self.autoPos, graphic=self.autoImage, callback=self.editAutoNumber,gpio=HARDWARE.button.SW) self.teleopButton = self.buttons((self.buttonWidth,self.buttonHeight),self.teleopPos, graphic=self.teleopImage, callback=self.editTeleopNumber,gpio=HARDWARE.button.NE) self.endGameButton = self.buttons((self.buttonWidth,self.buttonHeight),self.endGamePos, graphic=self.endGameImage, callback=self.editEndGameNumber,gpio=HARDWARE.button.SE) self.ButtonS = self.buttons(bgcolor = (0,0,255), callback=self.done, **Button.standardButton("S","Done",self.screen))
def get_search_actions(self, resource, context): search_button = Button(access=True, resource=resource, context=context, css='button-search', title=MSG(u'Search')) return [search_button]
class AcceptInvitation(ConfirmSubscription): title = MSG(u"Invitation") description = MSG( u'By accepting the invitation you will receive an email every time' u' this resource is modified.') actions = [Button(access=True, title=MSG(u'Accept invitation'))]
def __init__(self, screen): self.running = True self.screen = screen self.state = "title screen" self.score = 0 self.cycle_alpha = cycle([*range(0, 256, 2)] + [*range(0, 256, 2)][::-1]) self.player = Player(self) self.clock = pygame.time.Clock() self.banner = pygame.transform.scale2x(pygame.image.load("assets/banner.png")) self.all_monsters = pygame.sprite.Group() self.SpawnMonsterEvent = pygame.USEREVENT + 1 self.play_button = Button("assets/playbutton.png", (300, 280)) self.title_background = pygame.image.load("assets/background.png").convert() self.play_button.image = pygame.transform.scale2x(self.play_button.image).convert_alpha() self.read_lvl(1) self.lvl_background = self.map.screen.convert() self.background = self.title_background
def game_over_state(): # set display caption pygame.display.set_caption("Play Again?") # button position center_x = (window_width - button_width) // 2 center_y = text_padding # restart.display_text_box(game_window, center_x, center_y) restart_button = Button(color="white", x=center_x, y=center_y, text="restart") restart_button.draw_button(game_window) pygame.display.update() # clock tick pygame.time.Clock().tick(1) // 1000 # display update pygame.display.update() while True: # catch different events for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: pygame.display.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONUP: # left click if event.button == 1: x, y = event.dict["pos"] # check for restart if restart_button.get_button_rectangle().collidepoint( x, y): # clear the game window game_window.fill(colors["black"]) # goto bast state base_state()
def __init__(self,name): self.name = name self.screen = pygame.display.get_surface().copy() self.width = self.screen.get_width() self.height = self.screen.get_height() Screen.screenList.append(self) self.buttons = Button.clone(name) # these are the buttons for THIS screen self.tables = Table.clone(name) # these are the tables for THIS screen self.title = None
class StartScreen(GameState): """State to handle update and and render logic when the start screen is active """ bgr = pygame.image.load(os.path.join(constants.ASSETS, 'start_screen_bgr.png')) buttons = {} buttons['play'] = Button('play_button', pygame.image.load(os.path.join(constants.ASSETS, 'play_button.png'))) visibles = [] switch_to_states = [] @classmethod def __init__(cls): cls.buttons['play'].pos = [((constants.screen_width / 2) - (cls.buttons['play'].sprite.get_width() / 2)), (constants.screen_height / 2)] cls.buttons['play'].rect = pygame.Rect(cls.buttons['play'].pos, (cls.buttons['play'].rect.width, cls.buttons['play'].rect.height)) asdf = [cls.buttons['play'].sprite, cls.buttons['play'].pos] cls.visibles.append(asdf) @classmethod def update(cls): cls.switch_to_states = [] for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.display.quit() raise SystemExit # Check if a button has been clicked if event.type == pygame.MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() for button in cls.buttons.values(): if button.rect.collidepoint(pos): print(button.id) if button.id == 'play_button': #cls.switch_to_states.append('roster_edit') return 'roster_edit' else: print("not clicked") @classmethod def draw(cls, game_win): game_win.blit(cls.bgr, (0, 0)) for i in cls.visibles: game_win.blit(i[0], i[1]) @classmethod def on_enter(cls): pass
def set_roster_buttons(cls): """Creates buttons for each creature in the player's roster """ i = 0 for name in player.player1.roster_ids: cls.roster_buttons.append(Button(name, player.player1.get_roster_thumbs(name), pos=cls.thumb_positions[i], text=name)) i += 1
def make(cls, items): cls.buttons = {} i = 0 for item in items: cls.buttons[item] = Button(item, cls.button_blank, pos=(cls.pos[0], cls.pos[1] + (i * cls.button_height)), text=item) i += 1 cls.show = True
def device_choice_screen(_mouse_x, _mouse_y): """Obsługa ekranu z pytaniem czy gra się z urządzeniem do rozdawania kart""" _ard_conn = None button_yes = Button((0, 255, 255), 375, 300, 100, 60, 'Tak') button_no = Button((255, 0, 0), 575, 300, 100, 60, 'Nie') if button_yes.is_over(_mouse_x, _mouse_y): screen.fill(bg_green) # try: # _ard_conn = ArduinoConnection('COM2') # _color_model, _value_model = tensorflow_load_models() # return True, _ard_conn # except SerialException: # add_text(text_no_device, 300, 500) if button_no.is_over(_mouse_x, _mouse_y): screen.fill(bg_green) return False, _ard_conn add_text(text_device_choice, 300, 150) button_yes.draw(screen) button_no.draw(screen) return None, _ard_conn
def __init__(self,name): Screen.__init__(self,name) self.ButtonS = self.buttons(bgcolor = (255,0,0), callback=self.quit, **Button.standardButton("S","Quit",self.screen)) self.str = "The Chap FCS is a project created by Chap Research,\nat Westlake High School, in Austin, Texas. The project was created by Arnhav Iyengar, Jacob Rothfus, Lewis Jones, and Eric Rothfus, in association with FRC Team 2468, Team Appreciate. This system was made to promote fariness and safety in the FTC competition, by creating a consistant, and easy way to start and stop all the robots in a match." self.target = 1 self.str2 = "" self.x = 10 self.y = 75
def __init__(self, name): Screen.__init__(self, name) self.screen.fill([0, 0, 0]) self.redraw = True self._setTitle("Audio Test") self.soundFX = pygame.mixer.Sound(os.path.join("Media", "StartAuto.wav")) self.myfont = pygame.font.SysFont("impact", 50) self.label = self.myfont.render("Playing Sound", 1, (255, 255, 255)) print("This is working") self.ButtonSW = self.buttons( bgcolor=(255, 0, 0), callback=self.play, **Button.standardButton("SW", ["Play", "Sound"], self.screen) ) self.ButtonS = self.buttons( bgcolor=(255, 255, 255), callback=self.done, lcolor=(0, 0, 0), **Button.standardButton("S", "Done", self.screen) )
def __init__(self, screen, stats): """Init a menu""" self.screen = screen self.screen_rect = screen.get_rect() # Set parameters self.width = 800 self.height = 500 self.bg_color = (30, 30, 30) self.text_color = (255, 255, 255) self.font = pygame.font.SysFont(None, 48) self.rect = pygame.Rect(0, 0, self.width, self.height) self.rect.center = self.screen_rect.center self.prep_msg(stats) if stats.game_ended: self.prep_msg(stats) # Create Play button self.play_button = Button(screen, stats) self.controls_button = Button(screen, stats)
def init_buttons(self): button_length = self.surface.get_size()[0] * 0.21 button_height = self.surface.get_size()[1] * 0.35 x_space = self.surface.get_size()[0] * 0.03 y_space = self.surface.get_size()[1] * 0.05 text_mult = 0.17 self.maze_button = Button((button_length * 0 + x_space * 1), y_space, button_length, button_height, text="Generate maze") self.path_button = Button((button_length * 1 + x_space * 2), y_space, button_length, button_height, text="Find path") self.animate_button = Button((button_length * 0 + x_space), button_height + y_space * 2, button_length, button_height, text="Animate") self.buttons = [self.maze_button, self.path_button, self.animate_button] for button in self.buttons: button.main_color = WHITE button.highlight_color = LIGHT_GREY button.set_text(text_size=button_length * text_mult) self.animate_button.main_color = GREEN self.animate_button.highlight_color = DARK_GREEN
class CSV_AddRow(RowForm): title = MSG(u'Add Row') icon = 'new.png' actions = [Button(access=True, css='button-ok', title=MSG(u'Add'))] def action(self, resource, context, form): row = [form[name] for name, title in resource.get_columns()] row = resource.handler.add_row(row) # Ok message = INFO(u'New row added.') goto = ';edit_row?index=%s' % row.number return context.come_back(message, goto=goto)
def init(self): flags = 0 if not ANDROID: os.environ['SDL_VIDEO_CENTERED'] = '1' WINSIZE = 480, 800 else: WINSIZE = 0, 0 flags |= pygame.FULLSCREEN pygame.init() if USE_MIXER: mixer.init() # Map the back button to the escape key. if ANDROID: android.init() android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE) self.clock = pygame.time.Clock() if not (ANDROID or PYTHON4ANDROID): self.icon = pygame.image.load(get_resource('android-icon.png')) pygame.display.set_icon(self.icon) screen = self.screen = pygame.display.set_mode(WINSIZE, flags) self.width, self.height = screen.get_width(), screen.get_height() pygame.display.set_caption('Popzi') if USE_MIXER: self.pop_sound = mixer.Sound(get_resource("sfx/pop.ogg")) self.score_font = pygame.font.Font(get_resource(join("fonts", "FreeSans.ttf")), 25) self.completed_font = pygame.font.Font(get_resource(join("fonts", "FreeSans.ttf")), 40) self.start_button = Button("Start game") self.themes_button = Button("Select theme") self.playboard = PlayBoard(screen, self.COLUMNS, self.ROWS, self.header_height) self._read_theme_config()
def welcome_main(): # x,y represent the size of screen x = 620 y = 1000 pyg.init() screen = pyg.display.set_mode((x, y)) # screen is what is displayed pyg.display.set_caption('Fruit Ninja') # Places background image on screen background_image = pyg.image.load("fruit_ninja.jpeg").convert() screen.blit(background_image, [0, 0]) pyg.display.flip() # Makes a button to play game play_button = Button() play = play_button.create_button(screen,(205,133,63), (x/4),300,(x/2) ,(y/5) , 0, "Play!", (255,255,255)) playpos = play.get_rect() screen.blit(play, playpos) pyg.display.flip() # Make a button to see the rules of game rules_button = Button() rule = rules_button.create_button(screen,(205,133,63), (x/4), (3*y/5), (x/2), (y/5), 0, "Rules", (255,255,255)) rulespos = rule.get_rect() screen.blit(rule, rulespos) pyg.display.flip() # Sets all keys and buttons that need to be pressed while True: pyg.init() for event in pyg.event.get(): if event.type == QUIT: pyg.quit() elif event.type == MOUSEBUTTONDOWN: mouse_pos = pyg.mouse.get_pos() if rules_button.pressed(mouse_pos): rules.rules_main() if play_button.pressed(mouse_pos): pyg.quit() test2.test_main() pyg.quit()
class HelloWorld: def __init__(self): print "init'ing menu" self.init_menu() print "init'ing inputs" self.init_inputs() print "init'ing gui" self.init_gui() self.state = WAITING def init_inputs(self): self.prev_joystick_state = NONE self.prev_button_state = UNPRESSED self.joystick = Joystick() self.button = Button() def init_menu(self): self.conf = Configurator() self.menu = self.conf.build_main_menu() self.curr_choice = 0 def init_gui(self): # create a new window self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) screen = self.window.get_screen() self.width = screen.get_width() self.height= screen.get_height() self.window.resize(self.width, self.height) # This packs the button into the window (a GTK container). self.lay = gtk.Layout() self.lay.set_size(self.width*2, self.height) self.window.add(self.lay) self.vbox = gtk.VBox() self.vbox.set_size_request(self.width, self.height) self.lay.put(self.vbox, 0, 0) self.update_menu() self.update_choice() self.lay.show() self.update_choice() self.window.show() self.pos = 0 gobject.timeout_add(30, self.state_machine_tick) ##def animate_callback(self): ##self.pos = (self.pos + 4) ##self.lay.move(self.vbox, self.pos, 0) ##self.window.queue_draw() ##return self.pos < (self.width/2) def state_machine_tick(self): if self.state == WAITING: button_state = self.button.read() joystick_state = self.joystick.read() self.handle_input(button_state, joystick_state) if self.state == SLIDING: # TODO - slide tick in direction pass return True def handle_input(self, button, joystick): if button == PRESSED: if self.prev_button_state == UNPRESSED: # TODO - do we pour directly from the menu or have some # kind of details page? if self.menu.is_leaf(): print "POURING DRINK!!! %s" % self.menu.key else: # Same as right joystick self.menu = self.menu.choice(self.curr_choice) self.curr_choice = 0 self.update_menu() # ignore joystick if button pressed elif self.prev_joystick_state == NONE: if joystick == UP and not self.menu.is_leaf(): self.curr_choice = max(0, self.curr_choice - 1) elif joystick == DOWN and not self.menu.is_leaf(): self.curr_choice = min(len(self.menu.choices) - 1, self.curr_choice + 1) elif joystick == RIGHT: if not self.menu.is_leaf(): self.menu = self.menu.choice(self.curr_choice) self.curr_choice = 0 self.update_menu() elif joystick == LEFT: self.menu = self.menu.back() self.curr_choice = 0 self.update_menu() if joystick != NONE: self.update_choice() self.prev_joystick_state = joystick self.prev_button_state = button def update_menu(self): self.vbox.hide() for child in self.vbox.get_children(): self.vbox.remove(child) try: choices = self.menu.choices except AttributeError: choices = (self.menu.key,) for choice in choices: b = gtk.Button("<span size='44000'>%s</span>" % gobject.markup_escape_text(str(choice))) b.child.set_use_markup(True) self.vbox.add(b) b.show() self.vbox.show() def update_choice(self): print "self.curr_choice is now", self.curr_choice for i, child in enumerate(self.vbox.get_children()): # TODO - there must be a better way of setting this no? for state in (gtk.STATE_NORMAL, gtk.STATE_PRELIGHT): if i == self.curr_choice: child.modify_fg(state, gtk.gdk.color_parse("#000000")) child.modify_bg(state, gtk.gdk.color_parse("#FCFF3D")) else: child.modify_fg(state, gtk.gdk.color_parse("#555555")) child.modify_bg(state, gtk.gdk.color_parse("#CCCCCC")) self.vbox.queue_draw() def main(self): # All PyGTK applications must have a gtk.main(). Control ends here # and waits for an event to occur (like a key press or mouse event). gtk.main()
class Game: COLUMNS = 8 ROWS = 12 # Top header for score header_height = 60 def __init__(self): random.seed() self.draw_count = 0 def init(self): flags = 0 if not ANDROID: os.environ['SDL_VIDEO_CENTERED'] = '1' WINSIZE = 480, 800 else: WINSIZE = 0, 0 flags |= pygame.FULLSCREEN pygame.init() mixer.init() # Map the back button to the escape key. if ANDROID: android.init() android.map_key(android.KEYCODE_BACK, pygame.K_b) self.clock = pygame.time.Clock() if not ANDROID: self.icon = pygame.image.load(get_resource('android-icon.png')) pygame.display.set_icon(self.icon) screen = self.screen = pygame.display.set_mode(WINSIZE, flags) self.width, self.height = screen.get_width(), screen.get_height() pygame.display.set_caption('Mazenum') self.score_font = pygame.font.Font(get_resource(join("fonts", "FreeSans.ttf")), 25) self.completed_font = pygame.font.Font(get_resource(join("fonts", "FreeSans.ttf")), 40) self.start_button = Button("Start game") self.playboard = PlayBoard(screen, self.COLUMNS, self.ROWS, self.header_height) self._set_background() self.is_game_over = False def start(self, debug=False): self.score = 0 self.is_game_over = False self.level = 1 self._start_level(DEBUG) def _start_level(self, debug=False): self.playboard.start(self.level) self.is_level_complete = False def _config_file(self, fname): """ Return full filename for a config file based on the platform """ if ANDROID: full_fname = fname else: config_dir = os.getenv('XDG_CONFIG_HOME', expanduser('~/.config')) config_dir = join(config_dir, 'mazenum') if not exists(config_dir): os.makedirs(config_dir, 0750) full_fname = join(config_dir, fname) return full_fname def _check_high_scores(self): """ Check if the current score is an high score. Update the highscore if required.""" # Read the higshcore file and check min fields are found high_score_fn = self._config_file('highscore.list') hs_list = self._high_scores = [] if exists(high_score_fn): with open(high_score_fn, 'r') as hs_file: for line in hs_file.readlines(): fields = line.strip('\r\n').split(';') if len(fields) == 3: hs_list.append(fields) # Search our score position score_pos = len(hs_list) for i in range(len(hs_list)): if self.score >= int(hs_list[i][0]): score_pos = i break # If we have a score pos, rebuild the score table and save it if score_pos < 10 : lower_scores = hs_list[score_pos:] higher_scores = hs_list[:score_pos] hs_list = higher_scores+[[str(self.score), str(self.level), str(date.today())]]+lower_scores hs_list = hs_list[:10] self._high_scores = hs_list with open(high_score_fn+'.new', 'w') as hs_file: for score in self._high_scores: hs_file.write(';'.join(score)+"\n") if exists(high_score_fn): os.unlink(high_score_fn) os.rename(high_score_fn+".new", high_score_fn) self.score_pos = score_pos def menu(self): screen = self.screen self.start_button.setCords((screen.get_width()/2) - (self.start_button.rect.width/2), 100) action = None while True: for event in pygame.event.get(): if event.type == MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() if self.start_button.is_pressed(event.pos): self.run() self.start_button.setCords((screen.get_width()/2) - (self.start_button.rect.width/2), 100) if event.type == QUIT or (event.type == KEYDOWN and event.key in [K_ESCAPE, pygame.K_b]): return False screen.blit(self.background, (0, 0)) screen.blit(self.start_button.image, self.start_button.rect) pygame.display.flip() self.clock.tick(TARGET_FPS) def _set_background(self): WINSIZE = self.width, self.height fn = join('gfx', 'background.jpg') background = pygame.image.load(get_resource(fn)) self.background = pygame.transform.scale(background, (WINSIZE)) self.playboard.set_background(self.background) def run(self): # The target frames per second is used to "sleep" the main loop between # screen redraws self.start() # The Main Event Loop while self._check_events(): self._draw() self.clock.tick(TARGET_FPS) def _check_events(self): playboard = self.playboard events = pygame.event.get() # Android-specific: if ANDROID and android.check_pause(): android.wait_for_resume() # Handle events for e in events: if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE): return False elif e.type == KEYDOWN and e.key == pygame.K_b: if self.is_game_over: return False else: self.is_game_over = True self._check_high_scores() elif e.type == MOUSEBUTTONDOWN: if self.is_level_complete: self.level += 1 self._start_level() elif self.is_game_over and e.type == MOUSEBUTTONDOWN: if self.start_button.is_pressed(e.pos): self.start() else: self._on_touch(e.pos) return True def _on_touch(self, pos): """ A position was touched """ touch_pos = self.playboard.get_board_pos(pos) if not touch_pos: # Out of the board return touch_x, touch_y = touch_pos # Revert last played ? if touch_pos == self.playboard.get_last_pos() and \ len(self.playboard._play_path) > 1: self.playboard.remove_last() if touch_pos in self.playboard.touched_goals: self.playboard.touched_goals.remove(touch_pos) return current_x, current_y = self.playboard.get_last_pos() # Ignore touches which are not adjacent if abs(touch_x - current_x) > 1 or abs(touch_y - current_y) > 1: return current_value = self.playboard.get_piece((current_x, current_y)) touch_value = self.playboard.get_piece(touch_pos) diff = touch_value - current_value if touch_value < 10 else touch_value if not diff in (1, -8): # Ignore non consecutive sequence -8=1-9 return self.score += 1 self.playboard.place_at((touch_x, touch_y)) if touch_pos in self.playboard.goals: self.playboard.touched_goals.append(touch_pos) if len(self.playboard.touched_goals) == len(self.playboard.goals): self.is_level_complete = True def _draw(self): screen = self.screen self.draw_count += 1 if self.draw_count == 1: self.first_draw = time.clock() self.playboard.draw(screen) # Header screen.blit(self.background, (0,0), (0, 0, self.width, self.header_height)) # Score text text = self.score_font.render(' Score: %d ' % self.score, True, THECOLORS["white"]) screen.blit(text, (10,0)) # Level text text = self.score_font.render(' Level: %d ' % self.level, True, THECOLORS["white"]) screen.blit(text, (self.width-text.get_width()-5,0)) # Level progress box #rect = pygame.Rect(20, 3+text.get_height(), self.width-40, 20) #rectangle(screen, rect, THECOLORS["white"]) # Level progress indicator (fill) #filled = (float(self.level_score)/self.level_score_goal)*(self.width-40) #white_rect = pygame.Rect(20, 3+text.get_height(), filled, 20) #black_rect = pygame.Rect(20+filled, 3+text.get_height(), self.width-40-filled, 20) #screen.fill(THECOLORS["white"], white_rect) #screen.fill(THECOLORS["black"], black_rect) #rectangle(screen, rect, THECOLORS["white"]) # Game over label when required if self.is_game_over: text = self.score_font.render(' GAME OVER ', True, THECOLORS["yellow"], THECOLORS["red"]) screen.blit(text, ((screen.get_width()/2) - (text.get_width()/2), self.header_height + 20)) #high score table i = 0 ypos = self.header_height + 10 + text.get_height() + 30 for score in self._high_scores: if i == self.score_pos: fg_color = THECOLORS["black"] bg_color = THECOLORS["white"] else: fg_color = THECOLORS["white"] bg_color = THECOLORS["gray"] text = self.score_font.render(' %6s - Level %2s (%s) ' % (score[0], score[1], score[2]), True , fg_color, bg_color) screen.blit(text, ((screen.get_width()/2) - (text.get_width()/2), ypos)) ypos += text.get_height()+10 i += 1 ypos += 20 self.start_button.setCords((screen.get_width()/2) - (self.start_button.rect.width/2), ypos) screen.blit(self.start_button.image, self.start_button.rect) if self.is_level_complete and not self.is_game_over: text = self.completed_font.render(' LEVEL COMPLETED ', True, THECOLORS["blue"], THECOLORS["yellow"]) screen.blit(text, ((screen.get_width()/2) - (text.get_width()/2), self.height/2-text.get_height()/2)) pygame.display.flip() if DEBUG and self.draw_count == 100: print "Playboard draw CPU time=", time.clock()-self.first_draw self.draw_count = 0
class Game: COLUMNS = 10 ROWS = 16 # Top header for score header_height = 60 # List of bubles being poped (count, position, piece_id) theme = "fruits" def __init__(self): random.seed() self.draw_count = 0 def init(self): flags = 0 if not ANDROID: os.environ['SDL_VIDEO_CENTERED'] = '1' WINSIZE = 480, 800 else: WINSIZE = 0, 0 flags |= pygame.FULLSCREEN pygame.init() if USE_MIXER: mixer.init() # Map the back button to the escape key. if ANDROID: android.init() android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE) self.clock = pygame.time.Clock() if not (ANDROID or PYTHON4ANDROID): self.icon = pygame.image.load(get_resource('android-icon.png')) pygame.display.set_icon(self.icon) screen = self.screen = pygame.display.set_mode(WINSIZE, flags) self.width, self.height = screen.get_width(), screen.get_height() pygame.display.set_caption('Popzi') if USE_MIXER: self.pop_sound = mixer.Sound(get_resource("sfx/pop.ogg")) self.score_font = pygame.font.Font(get_resource(join("fonts", "FreeSans.ttf")), 25) self.completed_font = pygame.font.Font(get_resource(join("fonts", "FreeSans.ttf")), 40) self.start_button = Button("Start game") self.themes_button = Button("Select theme") self.playboard = PlayBoard(screen, self.COLUMNS, self.ROWS, self.header_height) self._read_theme_config() def _read_theme_config(self): fname = self._config_file('theme.config') # Set the theme from the config file try: with open(fname, 'r') as theme_config: config_theme = theme_config.read() if config_theme and isdir(join('gfx', 'themes', config_theme)): self.theme = config_theme except IOError: pass self._set_theme() def start(self): self.level = 1 self.score = self.level_score = self.remaining_score = 0 self.is_game_over = False self.drop_row_interval = 10 self.level = 1 self._start_level(DEBUG) self.screen.blit(self.background, (0, 0)) def _start_level(self, debug=False): self.level_score = self.remaining_score # Keep remaining score self.is_level_complete = False level = self.level # Adjust game settings based on the level self.drop_row_interval = 11 - self.level if self.drop_row_interval < 1: self.drop_row_interval = 1 starting_rows = 4+self.level if starting_rows > 10: starting_rows = 10 self.level_score_goal = 100*level # Restart board self.playboard.start() if debug: for c in range(self.COLUMNS): for r in range(self.ROWS): self.playboard.set_piece(c, r, (c % 5)+1) else: for row in range(0, starting_rows): self.playboard.insert_row(row, self.level > 2 ) # Start timers if not debug: pygame.time.set_timer(INSERT_ROW_EVENT, self.drop_row_interval*1000) pygame.time.set_timer(FALLING_MOVE_EVENT, FALLING_INTERVAL) def _config_file(self, fname): """ Return full filename for a config file based on the platform """ if ANDROID: full_fname = fname else: config_dir = os.getenv('XDG_CONFIG_HOME', expanduser('~/.config')) config_dir = join(config_dir, 'popzi') if not exists(config_dir): os.makedirs(config_dir, 0750) full_fname = join(config_dir, fname) return full_fname def _check_high_scores(self): """ Check if the current score is an high score. Update the highscore if required.""" # Read the higshcore file and check min fields are found high_score_fn = self._config_file('highscore.list') hs_list = self._high_scores = [] if exists(high_score_fn): with open(high_score_fn, 'r') as hs_file: for line in hs_file.readlines(): fields = line.strip('\r\n').split(';') if len(fields) == 3: hs_list.append(fields) # Search our score position score_pos = len(hs_list) for i in range(len(hs_list)): if self.score >= int(hs_list[i][0]): score_pos = i break # If we have a score pos, rebuild the score table and save it if score_pos < 10 : lower_scores = hs_list[score_pos:] higher_scores = hs_list[:score_pos] hs_list = higher_scores+[[str(self.score), str(self.level), str(date.today())]]+lower_scores hs_list = hs_list[:10] self._high_scores = hs_list with open(high_score_fn+'.new', 'w') as hs_file: for score in self._high_scores: hs_file.write(';'.join(score)+"\n") if exists(high_score_fn): os.unlink(high_score_fn) os.rename(high_score_fn+".new", high_score_fn) self.score_pos = score_pos def menu(self): screen = self.screen self.start_button.setCords((screen.get_width()/2) - (self.start_button.rect.width/2), 100) self.themes_button.setCords((screen.get_width()/2) - (self.start_button.rect.width/2), 100+(self.start_button.rect.height*2)) action = None while True: for event in pygame.event.get(): if event.type == MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() if self.start_button.is_pressed(mouse_pos): self.run() self.start_button.setCords((screen.get_width()/2) - (self.start_button.rect.width/2), 100) if self.themes_button.is_pressed(mouse_pos): self._themes_menu() if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): return False screen.blit(self.background, (0, 0)) screen.blit(self.start_button.image, self.start_button.rect) screen.blit(self.themes_button.image, self.themes_button.rect) pygame.display.flip() self.clock.tick(TARGET_FPS) def _set_theme(self): WINSIZE = self.width, self.height fn = join('gfx', 'themes', self.theme , 'background.jpg') background = pygame.image.load(get_resource(fn)) self.background = pygame.transform.scale(background, (WINSIZE)) surfaces = self._load_pieces() self.playboard.set_surfaces(surfaces) self.playboard.set_background(self.background) def _themes_menu(self): screen = self.screen action = None buttons = [] ypos = 100 for theme_name in THEMES: button = Button(theme_name) button.setCords((self.screen.get_width()/2) - (self.start_button.rect.width/2), ypos) buttons.append(button) ypos += 100 while True: for event in pygame.event.get(): if event.type == MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() for button in buttons: if button.is_pressed(mouse_pos): self.theme = button.text.lower() self._set_theme() fname = self._config_file('theme.config') with open(fname, 'w') as theme_config: theme_config.write(self.theme) return if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): return False screen.blit(self.background, (0,0)) for button in buttons: screen.blit(button.image, button.rect) pygame.display.flip() self.clock.tick(TARGET_FPS) def run(self): # The target frames per second is used to "sleep" the main loop between # screen redraws self.start() # The Main Event Loop while self._check_events(): self._draw() self.clock.tick(TARGET_FPS) def _check_events(self): playboard = self.playboard events = pygame.event.get() # Android-specific: if ANDROID and android.check_pause(): android.wait_for_resume() # Handle events for e in events: self.playboard.check_event(e) if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE): return False elif e.type == MOUSEBUTTONDOWN: if self.is_game_over: if self.start_button.is_pressed(e.pos): self.start() return True # Level completed only accepts touch after a 2 seconds wait elif self.is_level_complete: if time.time() - self.level_complete_time > 2: self.level += 1 self._start_level() return True x,y = e.pos board_x, board_y = self.playboard.get_board_pos(e.pos) if board_x < 0 or board_y < 0 or \ board_x > self.COLUMNS-1 or board_y > self.ROWS-1 : board_x = board_y = None else: piece_id = self.playboard.get_piece(board_x, board_y) if piece_id == -1: # Zap matching_group = self.playboard.get_zap_group(board_x, board_y, []) else: matching_group = playboard.get_same_adjacent(board_x, board_y) matching_count = len(matching_group) if matching_count > 1: if USE_MIXER: self.pop_sound.play() # Update score score = matching_count if matching_count > 4: score += 10 elif matching_count > 6: score += 20 self.score += score self.level_score += score for x,y in matching_group: piece_id = self.playboard.get_piece(x, y) self.playboard.add_popping([5, (x,y), piece_id]) playboard.remove(matching_group) playboard.remove_vertical_gaps() # Level is complete self.remaining_score = self.level_score - self.level_score_goal if self.remaining_score >= 0: pygame.time.set_timer(INSERT_ROW_EVENT, 0) pygame.time.set_timer(FALLING_MOVE_EVENT, 0) self.level_score = self.level_score_goal self.is_level_complete = True self.level_complete_time = time.time() else: # Penalize massive touchers, drop on touch #candidate_pos = [] #for c in range(self.playboard.columns): # If there is a piece on the first row the game is over # if self.playboard.get_piece(c, 0) == 0: # candidate_pos.append(c) #if candidate_pos: # c = randint(0, len(candidate_pos)-1) if self.playboard.get_piece(board_x, 0) == 0: playboard.add_falling_piece(board_x, 0) elif e.type == INSERT_ROW_EVENT: for c in range(self.playboard.columns): # If there is a piece on the first row the game is over if self.playboard.get_piece(c, 0) != 0: pygame.time.set_timer(INSERT_ROW_EVENT, 0) pygame.time.set_timer(FALLING_MOVE_EVENT, 0) self.is_game_over = True self._check_high_scores() break if not self.is_game_over: self.playboard.insert_row(with_special=self.level > 2) elif e.type == FALLING_MOVE_EVENT: touch_down = self.playboard.falling_move(FALLING_SPEED) # Decrease visible time count for popping pieces return True def _draw(self): screen = self.screen self.draw_count += 1 if self.draw_count == 1: self.first_draw = time.clock() self.playboard.draw(screen) # Score text text = self.score_font.render(' Score: %d ' % self.score, True, THECOLORS["white"], THECOLORS["black"]) screen.blit(text, (10,0)) # Level text text = self.score_font.render(' Level: %d ' % self.level, True, THECOLORS["white"], THECOLORS["black"]) screen.blit(text, (self.width-text.get_width()-5,0)) # Level progress box rect = pygame.Rect(20, 3+text.get_height(), self.width-40, 20) rectangle(screen, rect, THECOLORS["white"]) # Level progress indicator (fill) filled = (float(self.level_score)/self.level_score_goal)*(self.width-40) white_rect = pygame.Rect(20, 3+text.get_height(), filled, 20) black_rect = pygame.Rect(20+filled, 3+text.get_height(), self.width-40-filled, 20) screen.fill(THECOLORS["white"], white_rect) screen.fill(THECOLORS["black"], black_rect) rectangle(screen, rect, THECOLORS["white"]) # Game over label when required if self.is_game_over: text = self.score_font.render(' GAME OVER ', True, THECOLORS["yellow"], THECOLORS["red"]) screen.blit(text, ((screen.get_width()/2) - (text.get_width()/2), self.header_height + 20)) #high score table i = 0 ypos = self.header_height + 10 + text.get_height() + 30 for score in self._high_scores: if i == self.score_pos: fg_color = THECOLORS["black"] bg_color = THECOLORS["white"] else: fg_color = THECOLORS["white"] bg_color = THECOLORS["black"] text = self.score_font.render(' %6s - Level %2s (%s) ' % (score[0], score[1], score[2]), True , fg_color, bg_color) screen.blit(text, ((screen.get_width()/2) - (text.get_width()/2), ypos)) ypos += text.get_height()+10 i += 1 ypos += 20 self.start_button.setCords((screen.get_width()/2) - (self.start_button.rect.width/2), ypos) screen.blit(self.start_button.image, self.start_button.rect) if self.is_level_complete: text = self.completed_font.render(' LEVEL COMPLETED ', True, THECOLORS["blue"], THECOLORS["yellow"]) screen.blit(text, ((screen.get_width()/2) - (text.get_width()/2), self.height/2-text.get_height()/2)) pygame.display.flip() if DEBUG and self.draw_count == 100: print "Playboard draw CPU time=", time.clock()-self.first_draw self.draw_count = 0 def _load_pieces(self): """ Load pieces image files """ pieces = [] for n in range(5): fn = join('gfx', 'themes', self.theme, 'piece-%d.png' % (n+1)) piece = pygame.image.load(get_resource(fn)) pieces.append(piece) return pieces
pygame.mixer.music.load(bg_music_file) started_playing = False def play_music(): global started_playing if not started_playing: pygame.mixer.music.play() started_playing = True else: pygame.mixer.music.unpause() def pause_music(): pygame.mixer.music.pause() plink_btn = Button("click for sound", (screen_rect.centerx, screen_rect.centery), mysound.play, 20, colors["green"], colors["black"], colors["gray"], 5) music_play_btn = Button("play music", (screen_rect.centerx, screen_rect.centery+25), play_music, 20, colors["green"], colors["black"], colors["gray"], 5) music_pause_btn = Button("pause music", (screen_rect.centerx, screen_rect.centery+50), pause_music, 20, colors["green"], colors["black"], colors["gray"], 5) while not game_exit: # handle inputs for evt in pygame.event.get(): if evt.type == pl.QUIT: game_exit = True if evt.type == pl.MOUSEBUTTONUP:
def init_inputs(self): self.prev_joystick_state = NONE self.prev_button_state = UNPRESSED self.joystick = Joystick() self.button = Button()
def setUp(self): self.event = Event() self.button = Button(push=self.event.push, hold=self.event.hold, release=self.event.release)
class TestButton(TestCase): """ Test buttons for each state """ # run before each test def setUp(self): self.event = Event() self.button = Button(push=self.event.push, hold=self.event.hold, release=self.event.release) def tearDown(self): """ Prevents further evaluation in timer thread by setting state to RELEASE (initial state) """ self.button.state = State.RELEASE def test_from_init_to_push(self): """ Check transition from INIT to PUSH. Trigger action for PUSH. """ self.button.set_state_push() self.assertEqual(self.button.state, State.PUSH) self.assertEqual(self.event.action, State.PUSH) def test_from_init_to_hold(self): """ Check transition from INIT to HOLD. No action expected, state shall not be updated. """ self.button.set_state_hold() self.assertNotEqual(self.button.state, State.HOLD) self.assertIsNone(self.event.action) def test_from_init_to_release(self): """ Check transition from INIT to RELEASE. No action expected. """ self.button.set_state_release() self.assertEqual(self.button.state, State.RELEASE) self.assertIsNone(self.event.action) def test_from_push_to_push(self): """ Check transition from PUSH to PUSH. This might happen if signals get lost, etc, hence no action expected? """ self.button.state = State.PUSH self.button.set_state_push() self.assertEqual(self.button.state, State.PUSH) self.assertIsNone(self.event.action) def test_from_push_to_hold(self): """ Check transition from PUSH to HOLD. trigger action for HOLD. """ self.button.state = State.PUSH self.button.set_state_hold() self.assertEqual(self.button.state, State.HOLD) self.assertEqual(self.event.action, State.HOLD) def test_from_push_to_release(self): """ Check transition from PUSH to RELEASE. trigger action for RELEASE. """ self.button.state = State.PUSH self.button.set_state_release() self.assertEqual(self.button.state, State.RELEASE) self.assertEqual(self.event.action, State.RELEASE) def test_from_hold_to_push(self): """ Check transition from HOLD to PUSH. This might happen if signals get lost, etc. State transition is not allowed; hence state is not updated and no action is expected. """ self.button.state = State.HOLD self.button.set_state_push() self.assertEqual(self.button.state, State.HOLD) self.assertIsNone(self.event.action) def test_from_hold_to_hold(self): """ Check transition from HOLD to HOLD. This might happen if a button broadcasting state itself on the IBUS, hence action for HOLD is expected. """ self.button.state = State.HOLD self.button.set_state_hold() self.assertEqual(self.button.state, State.HOLD) self.assertEqual(self.event.action, State.HOLD) def test_from_hold_to_release(self): """ Check transition from HOLD to RELEASE. No action is expected - since we have executed an action for HOLD. """ self.button.state = State.HOLD self.button.set_state_release() self.assertEqual(self.button.state, State.RELEASE) self.assertIsNone(self.event.action) def test_from_release_to_push(self): """ Check transition from RELEASE to PUSH. This is the most common case - execute action for PUSH. """ self.button.state = State.RELEASE self.button.set_state_push() self.assertEqual(self.button.state, State.PUSH) self.assertEqual(self.event.action, State.PUSH) def test_from_release_to_hold(self): """ Check transition from RELEASE to HOLD. This might occur if signal for PUSH is lost, but receiving state HOLD from the IBUS. This is an error-state, state transition is not allowed; hence no action shall be executed and state is not updated. """ self.button.state = State.RELEASE self.button.set_state_hold() self.assertEqual(self.button.state, State.RELEASE) self.assertIsNone(self.event.action) def test_from_release_to_release(self): """ Check transition from RELEASE to RELEASE. This is an error-state, and might occur if signal is lost, etc. no action is expected. """ self.button.state = State.RELEASE self.button.set_state_release() self.assertEqual(self.button.state, State.RELEASE) self.assertIsNone(self.event.action)