コード例 #1
0
ファイル: tagedit.py プロジェクト: Occuliner/LD27Project
 def __init__( self, parentState=None, text="", pos=(0,0) ):
     Button.__init__( self, None, None, parentState )
     self.text = text
     self.rect = pygame.Rect( 0, 0, 0, 0 ).move( pos[0], pos[1] )
     #print text
     self.selected = False
     self.createText()
コード例 #2
0
def window():
    
    pointA = Point(125,75)
    pointB = Point(125,175)
    pointC = Point(125,275)
    pointD = Point(350,150)
    pointE = Point(500,150)
    pointF = Point(450,275)
    pointG = Point(475,50)
    pointX = Point(575,25)
    
    win = GraphWin("Crap Heaven",600,350)
    win.setBackground("purple")

    pt = win.getMouse()
    bA = Button(win,pointA,150,50,"Bet 1000!")
    bB = Button(win,pointB,150,50,"Bet 100!")
    bC = Button(win,pointC,150,50,"Bet 10!")
    bD = DieView(win,pointD,100)
    bE = DieView(win,pointE,100)
    bF = Button(win,pointF,200,50,"Bank Account")
    button2 = Button(win,pointG,150,50,"Win!")
    button1 = Button(win,pointX,25,25,"X")  
    button2.activate
    button2.active
    while not button2.clicked(pt):
        if button2.clicked(pt):
            win.close()
    pt = win.getMouse()
コード例 #3
0
ファイル: dialog.py プロジェクト: netphi/deepin-ui
 def __init__(self, 
              title, 
              init_text, 
              default_width=330,
              default_height=145,
              confirm_callback=None, 
              cancel_callback=None):
     '''Init confirm dialog.'''
     # Init.
     DialogBox.__init__(self, title, default_width, default_height, DIALOG_MASK_SINGLE_PAGE)
     self.confirm_callback = confirm_callback
     self.cancel_callback = cancel_callback
     
     self.entry_align = gtk.Alignment()
     self.entry_align.set(0.5, 0.5, 0, 0)
     self.entry_align.set_padding(0, 0, 8, 8)
     self.entry = InputEntry(init_text)
     self.entry.set_size(default_width - 20, 25)
     
     self.confirm_button = Button(_("OK"))
     self.cancel_button = Button(_("Cancel"))
     
     self.confirm_button.connect("clicked", lambda w: self.click_confirm_button())
     self.cancel_button.connect("clicked", lambda w: self.click_cancel_button())
     
     self.entry_align.add(self.entry)
     self.body_box.pack_start(self.entry_align, True, True)
     
     self.right_button_box.set_buttons([self.confirm_button, self.cancel_button])
     
     self.connect("show", self.focus_input)
コード例 #4
0
ファイル: dialog.py プロジェクト: netphi/deepin-ui
 def __init__(self, 
              title, 
              message, 
              default_width=330,
              default_height=145,
              confirm_callback=None, 
              cancel_callback=None):
     '''Init confirm dialog.'''
     # Init.
     DialogBox.__init__(self, title, default_width, default_height, DIALOG_MASK_SINGLE_PAGE)
     self.confirm_callback = confirm_callback
     self.cancel_callback = cancel_callback
     
     self.label_align = gtk.Alignment()
     self.label_align.set(0.5, 0.5, 0, 0)
     self.label_align.set_padding(0, 0, 8, 8)
     self.label = Label(message, text_x_align=ALIGN_MIDDLE, text_size=11)
     
     self.confirm_button = Button(_("OK"))
     self.cancel_button = Button(_("Cancel"))
     
     self.confirm_button.connect("clicked", lambda w: self.click_confirm_button())
     self.cancel_button.connect("clicked", lambda w: self.click_cancel_button())
     
     # Connect widgets.
     self.body_box.pack_start(self.label_align, True, True)
     self.label_align.add(self.label)
     
     self.right_button_box.set_buttons([self.confirm_button, self.cancel_button])
コード例 #5
0
    def help(self):
        helpWin = GraphWin("Help", 600, 400)
        helpWin.setBackground("blue1")

        banner = Text(Point(275, 75), "The Game of Craps:")
        banner.setSize(24)
        banner.setStyle("bold")
        banner.draw(helpWin)

        explanation = [Text(Point(305, 140), "Both dice are always rolled at the same time."),
                       Text(Point(305, 180), "A player places a bet, and then rolls the dice."),
                       Text(Point(355, 220), "A 7 or 11 on the first roll is a win, while a 2, 3, or 12 is a loss."),
                       Text(Point(285, 260), "Otherwise, the player keeps rolling until:"),
                       Text(Point(285, 300), "They re-roll their initial roll (this is a win)"),
                       Text(Point(165, 340), "Or"),
                       Text(Point(245, 380), "They roll a 7 (this is a loss)")]
        for sentence in explanation:
            sentence.draw(helpWin)
            sentence.setSize(16)
            
        closeButton = Button(helpWin, Point(60, 40), 80, 40, "Close Window")
        closeButton.activate()
        p = helpWin.getMouse()
        if closeButton.clicked(p):
            helpWin.close()
コード例 #6
0
 def _createButton(self, button_id, message, rect):
     button = Button(button_id, self, message, Consts.LIGHT_GOLD_COLOR, rect)
     self.inputManager.attach(button)
     button.font_object = self.font_object
     button._setColors(Consts.LIGHT_GOLD_COLOR, Consts.HOVER_GOLD_COLOR, Consts.PRESSED_GOLD_COLOR)
     
     return button
コード例 #7
0
ファイル: example.py プロジェクト: Mekire/pygame-button
class Control(object):
    def __init__(self):
        self.screen = pg.display.set_mode((500,500))
        self.screen_rect = self.screen.get_rect()
        self.clock = pg.time.Clock()
        self.done = False
        self.fps = 60.0
        self.color = WHITE
        message = "Change the screen color."
        self.button = Button((0,0,200,50),RED, self.change_color,
                             text=message, **BUTTON_STYLE)
        self.button.rect.center = (self.screen_rect.centerx,100)

    def change_color(self):
        self.color = [random.randint(0,255) for _ in range(3)]

    def event_loop(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.done = True
            self.button.check_event(event)

    def main_loop(self):
        while not self.done:
            self.event_loop()
            self.screen.fill(self.color)
            self.button.update(self.screen)
            pg.display.update()
            self.clock.tick(self.fps)
コード例 #8
0
ファイル: input_box.py プロジェクト: mtnkdev/toaruos
    def __init__(self, decorator, title, icon, text="", text_changed=None, callback=None,window=None,cancel_callback=None):
        super(TextInputWindow, self).__init__(self.base_width + decorator.width(), self.base_height + decorator.height(), title=title, icon=icon, doublebuffer=True)
        if window:
            # Center window
            self.move(window.x+int((window.width-self.width)/2),window.y+int((window.height-self.height)/2))
        else:
            # Center screen
            self.move(int((yutani.yutani_ctx._ptr.contents.display_width-self.width)/2),int((yutani.yutani_ctx._ptr.contents.display_height-self.height)/2))
        self.decorator = decorator
        self.font = toaru_fonts.Font(toaru_fonts.FONT_SANS_SERIF, 13, 0xFF000000)

        # Initialize here
        self.input = InputBox(text=text)
        self.input.text_changed = text_changed
        self.input.submit = self.ok_click
        self.input.is_focused = True

        self.text_changed = text_changed
        self.callback = callback
        self.cancel_callback = cancel_callback

        self.button_ok = Button(self.okay_label,self.ok_click)
        self.button_cancel = Button(self.cancel_label,self.cancel_click)
        self.buttons = [self.button_ok, self.button_cancel]

        self.hover_widget = None
        self.down_button = None

        # For backwards compatibility with old API
        self.tr = lambda: None
コード例 #9
0
ファイル: dialog.py プロジェクト: klange/ponyos
    def __init__(self, decorator, title, text, icon='help', buttons=DialogButtons.OKAY_CANCEL, callback=None, cancel_callback=None,window=None,cancel_label=True,close_is_cancel=True):
        super(DialogWindow, self).__init__(self.base_width + decorator.width(), self.base_height + decorator.height(), title=title, icon=icon, doublebuffer=True)

        if window:
            # Center window
            self.move(window.x+int((window.width-self.width)/2),window.y+int((window.height-self.height)/2))
        else:
            # Center screen
            self.move(int((yutani.yutani_ctx._ptr.contents.display_width-self.width)/2),int((yutani.yutani_ctx._ptr.contents.display_height-self.height)/2))
        self.decorator = decorator
        self.logo = get_icon(icon,48,'help')
        self.font = toaru_fonts.Font(toaru_fonts.FONT_SANS_SERIF, 13, 0xFF000000)
        self.tr = text_region.TextRegion(0,0,self.base_width-60,self.base_height-self.text_offset,font=self.font)
        self.tr.set_richtext(text)

        if cancel_label is not True:
            self.cancel_label = cancel_label

        self.button_ok = Button(self.okay_label,self.ok_click)
        self.button_cancel = Button(self.cancel_label,self.cancel_click)
        self.buttons = [self.button_ok]
        if self.cancel_label:
            self.buttons.append(self.button_cancel)

        self.close_is_cancel = close_is_cancel

        self.hover_widget = None
        self.down_button = None

        self.callback = callback
        self.cancel_callback = cancel_callback
        self.draw()
コード例 #10
0
 def _createButton(self, button_id, message, rect):
     button = Button(button_id, self, message, Consts.GRAY_COLOR, rect)
     self.inputManager.attach(button)
     button.border_color = Consts.WHITE_COLOR
     button._setColors(Consts.GRAY_COLOR, Consts.HOVER_GRAY_COLOR, Consts.PRESSED_GRAY_COLOR)
     
     return button
コード例 #11
0
    def __init__(self):
        self.win = GraphWin ("Craps Game", 600, 400)
        self.win.setBackground('green3')

        banner = Text(Point(300,30), "Craps Table")
        banner.setSize(24)
        banner.setFill("yellow2")
        banner.setStyle("bold")
        banner.draw(self.win)

        self.createDice(Point(300, 100), 75)

        self.msg = Text(Point(300,275), "Welcome to the Craps Table")
        self.msg.setSize(18)
        self.msg.draw(self.win)
        moneyMsg = Text(Point(280, 380), "You have:")
        moneyMsg.setSize(18)
        moneyMsg.draw(self.win)
        self.money = Text(Point(350, 380), "$100")
        self.money.setSize(18)
        self.money.draw(self.win)
        betText = Text(Point(340, 100), 'Place a Bet:  $')
        betText.setSize(16)
        betText.draw(self.win)
        self.input = Entry(Point(460, 100), 20)
        self.input.draw(self.win)

        self.rollDiceButton = Button(self.win, Point(125, 200), 200, 40, "Roll Dice")
        self.rollDiceButton.activate()
        self.quitButton = Button(self.win, Point(570, 375), 40, 30, "Quit")
        self.quitButton.activate()
        self.helpButton = Button(self.win, Point(30, 375), 40, 30, "Help")
        self.helpButton.activate()
コード例 #12
0
ファイル: team.py プロジェクト: macartur-UNB/BS
 def _create_team(self):
     self.buttons = []
     for position in self.team_position:
         button = Button(self.team_color, self.turn)
         button.pos = position
         button.init_pos = position
         self.buttons.append(button)
コード例 #13
0
ファイル: toggle_button.py プロジェクト: Merfie/Space-Train
    def __init__(self, text='Label', active=False, on_click=None):
        ''' Create toggle button. '''

        self._active = active
        Button.__init__(self, text, on_click)
        if self._active:
            self._state = state.activated
コード例 #14
0
    def __init__(self, shippo):
        self.shippo = shippo
        self.size = shippo.W, shippo.H

        # init view control buttons
        thick = 40
        w, h = self.size
        visible = 0
        self.buttons = []
        self.buttons.append(Button(Rect((0, 0), (w, thick)), 'up', visible))
        self.buttons.append(Button(Rect((w - 3*thick, 0), (3*thick, h)), 'right', visible))
        self.buttons.append(Button(Rect((0, h - thick), (w, thick)), 'down', visible))
        self.buttons.append(Button(Rect((0, 0), (thick, h)), 'left', visible))

        self.buttons.append(Button(Rect((0, 0), (w, h)), 'scroll', 0))

        for button in self.buttons:
            self.shippo.UISprites.append(button)

        # bind event
        self.speed = speed = 10 # scroll speed
        self.buttons[0].bind(Button.Over, self.mover((0, -speed)))
        self.buttons[1].bind(Button.Over, self.mover((speed, 0)))
        self.buttons[2].bind(Button.Over, self.mover((0, speed)))
        self.buttons[3].bind(Button.Over, self.mover((-speed, 0)))
        def scroll(event):
            ds = 0.05
            if event.button == 4: 
                # scroll up, zoom in
                ds = ds
            elif event.button == 5:
                ds = -ds
            self.shippo.viewBox.zoom(event.pos, ds)
        self.buttons[4].bind(Button.Scroll, scroll)
        # self.buttons[4].bind(Button.Press, lambda event:self.shippo.viewBox.zoom(event.pos, 0))

        hidedash = Button(Rect(self.shippo.dashBoard.rect), 'hidedash', 0)
        self.buttons.append(hidedash)
        hidedash.bind(Button.Over, self.hide_dash)
        def start_show(event):
            self.showingDash = 1
            self.shippo.dashBoard.hided = 0
        hidedash.bind(Button.Out, start_show)
        self.showingDash = 0

        # bind events for every ship
        def shower(obj):
            def show_detail(event):
                shippo.detailBoard.update_target(obj)
            return show_detail

        for ship in self.shippo.ships:
            ship.button.bind(Button.Over, shower(ship))
            ship.button.bind(Button.Out, shower(None))

        for res in self.shippo.resources:
            res.button.bind(Button.Over, shower(res))
            res.button.bind(Button.Out, shower(None))

        self.vim_bindings = {K_h: self.mover((-speed, 0)), K_j: self.mover((0, speed)), K_k: self.mover((0, -speed)), K_l: self.mover((speed, 0))}
コード例 #15
0
ファイル: tab_window.py プロジェクト: netphi/deepin-ui
 def __init__(self, title, items, 
              confirm_callback=None, 
              cancel_callback=None,
              window_width=458,
              window_height=472):
     '''Init tab window.'''
     DialogBox.__init__(self, title, window_width, window_height, mask_type=DIALOG_MASK_TAB_PAGE)
     self.confirm_callback = confirm_callback
     self.cancel_callback = cancel_callback
     
     self.window_box = gtk.VBox()
     
     self.tab_window_width = window_width
     self.tab_window_height = window_height
     self.tab_box = TabBox()
     self.tab_box.add_items(items)
     self.tab_align = gtk.Alignment()
     self.tab_align.set(0.5, 0.5, 1.0, 1.0)
     self.tab_align.set_padding(8, 0, 0, 0)
     self.tab_align.add(self.tab_box)
     
     self.confirm_button = Button("确认")
     self.cancel_button = Button("取消")
     
     self.window_box.pack_start(self.tab_align, True, True)
     
     self.confirm_button.connect("clicked", lambda w: self.click_confirm_button())
     self.cancel_button.connect("clicked", lambda w: self.click_cancel_button())
     self.connect("destroy", lambda w: self.destroy())
     
     self.body_box.pack_start(self.window_box, True, True)
     self.right_button_box.set_buttons([self.confirm_button, self.cancel_button])
コード例 #16
0
ファイル: start_screen.py プロジェクト: wukat/Tetris
 def __init__(self, surface):
     self.surface = surface
     self.position = (screen_size[0] // 2 - 70, screen_size[1] - 0.8 * NROWS * size)
     self.start = Button(self.surface, "START", screen_size[0] // 2, screen_size[1] * 6/8, 30, True)
     self.quit = Button(self.surface, "QUIT", screen_size[0] // 2, screen_size[1] * 7/8, 30, True)
     self.starttext = Text(self.surface, "TETRIS", True, 50, WHITE, backgroundcolor, screen_size[0] // 2, screen_size[1] * 2/8)
     self.show()
コード例 #17
0
 def __init__(self,win):
     self.w = win
     self.level = 3
     self.len = 10
     self.wid = 14
     self.time = 150
     self.help_num = 24
     self.real_time = time.time()
     self.box = Box(win,self.len,self.wid)
     self.box.init_flag()
     self.box.init_block()
     self.box.draw()
     self.hButton = Button(win,Point(8.5,4.5),1,0.3, "High Level")
     #self.hButton.activate()
     self.lButton = Button(win,Point(8.5,4.0),1,0.3, "Low Level")
     self.lButton.activate()
     self.rButton = Button(win,Point(8.5,3.5),1,0.3, "Restart")
     self.rButton.activate()
     self.qButton = Button(win,Point(8.5,2.5),1,0.3, "Quit")
     self.qButton.activate()
     self.tButton = Button(win,Point(8.5,3.0),1,0.3, "Help")
     self.tButton.activate()
     self.tip = Text(Point(8.5,1.0),"Gaming")
     self.help_info = Text(Point(8.5,1.5),"Remain: 24")
     self.winning_info = Text(Point(4.0,3.0),"")
     self.winning_info.draw(win)
     self.timing = Text(Point(8.5,2.0),"150 second")
     self.help_info.draw(win)
     self.tip.draw(win)
     self.timing.draw(win)
コード例 #18
0
ファイル: dialog.py プロジェクト: ZhanruiLiang/servoflash
 def __init__(self, msg, options, callback, emergency=0, **dargs):
     root = Root.instance
     itemsize = (80, 20)
     margin = 5
     self.emergency = emergency
     size = ((itemsize[0] + margin) * len(options) + margin, 200 + 3 * margin + itemsize[1])
     super(OptionDialog, self).__init__(
         root,
         size=size,
         pos=((root.size[0] - size[0]) / 2, (root.size[1] - size[1]) / 2),
         bgcolor=(0x9F, 0xAF, 0xFF, 0xFF),
         level=Root.DIALOG_LEVEL,
         **dargs
     )
     TextBox(
         self,
         text=msg,
         pos=(margin, margin),
         size=(size[0] - 2 * margin, 200),
         bgcolor=(0, 0, 0, 0x88),
         color=(0xFF, 0xFF, 0xFF),
         fontsize=14,
     )
     self.callback = callback
     for i, opt in enumerate(options):
         btn = Button(self, pos=(margin + i * (itemsize[0] + margin), 200 + 2 * margin), caption=opt, size=itemsize)
         btn.bind_command(lambda i=i: self.choose(i))
コード例 #19
0
    def help(self):
        helpWin = GraphWin("Help", 600, 400)
        helpWin.setBackground("blue")
        rulesText = Text(Point(300, 30), "Rules of the Game:")
        rulesText.setSize(24)
        rulesText.draw(helpWin)
        rules = [Text(Point(290, 100), "A player starts with $100. Each round costs $10 to play."),
                 Text(Point(230, 140), "A player initially roles a random hand."),
                 Text(Point(300, 180), "Dice can be re-rolled up to two times (any number of dice)."),
                 Text(Point(165, 240), "Payout Schedule:")]
        for rule in rules:
            rule.draw(helpWin)
            rule.setSize(16)
        payouts = [Text(Point(165, 280), "Two Pairs, $5"),
                   Text(Point(170, 300), "Three of a Kind, $8"),
                   Text(Point(165, 320), "Full House, $12"),
                   Text(Point(170, 340), "Four of a Kind, $15"),
                   Text(Point(165, 360), "Straight, $20"),
                   Text(Point(170, 380), "Five of a Kind, $30")]
        for item in payouts:
            item.draw(helpWin)
            item.setSize(16)

        closeButton = Button(helpWin, Point(60, 40), 80, 40, "Close Window")
        closeButton.activate()
        p = helpWin.getMouse()
        if closeButton.clicked(p):
            helpWin.close()
コード例 #20
0
    def __init__(self):
        self.win = GraphWin("Dice Poker", 600, 500)
        self.win.setBackground("white")
        banner = Text(Point(300, 30), "Python  Poker  Parlor")
        banner.setSize(24)
        banner.setFill("black")
        banner.setStyle("bold")
        banner.draw(self.win)
        info = Text(Point(300, 60), "This program allows a user to play video poker using dice")
        info.setFill("black")
        info.draw(self.win)
        self.letsplaybutton = Button(self.win, Point(200, 100), 180, 40, "Let's Play")
        self.letsplaybutton.activate()
        self.exitbutton = Button(self.win, Point(400, 100), 180, 40, "Exit")
        self.exitbutton.activate()

        highscorebanner = Text(Point(300, 150), "High Scores")
        highscorebanner.setSize(24)
        highscorebanner.setFill("black")
        highscorebanner.setStyle("bold")
        highscorebanner.draw(self.win)
        highscores = HighScores()
        scores = highscores.getHighScores()

        if scores == -1:
            Text(Point(300, 180), "No High Scores Available").draw(self.win)
        else:
            for i in range(0, len(scores)):

                Text(Point(300, 200 + (20 * i)), scores[i][1].strip() + ": " + str(scores[i][0]).strip()).draw(self.win)
コード例 #21
0
ファイル: filebrowserscene.py プロジェクト: dnlkng/zplayer
    def build_menu(self):
        self.buttons = []

        back_button = Button((0, 0, 42, 42), cb=self.go_to_main_menu)
        back_button.iconFg = pygame.image.load("./resources/images/chevron.png")
        self.buttons.append(back_button)

        book_icon_name = "icon.png"
        #path = "./audiobooks/*/"
        path = "./"
        path += self.folder
        path += "/*/"
        folders = glob.glob(path)
        icons = []

        for i, folder in enumerate(folders):
            icons.append(folder + book_icon_name)

        # 240 Breite: 240 / 3 = 80 > 80 > 10 links + 10 rechts > 60 pixel
        # 320 - 240 = 80 > links 40 rechts 40 rand

        screen_margin = 40
        x = screen_margin
        y = 10

        for i, folder in enumerate(folders):
            button = Button((x, y, 80, 80), value=folder, cb=self.on_button_clicked)
            button.iconFg = pygame.image.load(icons[i])
            if x < 200:
                x += 80
            else:
                x = 40
                y += 80

            self.buttons.append(button)
コード例 #22
0
    def __init__(self):
        # initilising the starting windows
        self.win = GraphWin("21 Black Jack", 900, 600)
        self.win.setBackground("green3")

        # create a  greeting banner
        banner = Text(Point(450,50), "Welcome to Python  Poker  BlackJack")
        banner.setSize(36)
        banner.setFill("yellow2")
        banner.setStyle("bold")
        banner.draw(self.win)
        
        #create a explantory message
        self.message = Text(Point(450,550),"3 for a Win,1 for a Tie, 0 for a lose")
        self.message.draw(self.win)
        self.message.setSize(30)
        self.message.setStyle("bold")

        # create a round counter
        self.roundmess = Text(Point(420,150),"Round")
        self.roundmess.setSize(27)
        self.roundmess.setStyle("bold")
        self.roundmess.draw(self.win)

        #create a score board 
        side1 = Text(Point(200,150),"Player")
        self.mpscore = Text(Point(200,200),"Score:")
        side1.setSize(24)
        side1.setStyle("italic")
        side1.draw(self.win)
        self.mpscore.draw(self.win)
        
        side2 = Text(Point(700,150),"Computer")
        self.mcscore  = Text(Point(700,200),"Score:")
        side2.setSize(24)
        side2.setStyle("italic")
        side2.draw(self.win)
        self.mcscore.draw(self.win)
        
        self.dealbutton = Button(self.win,Point(450,300),90,40,"Deal")
        self.hitmebutton = Button(self.win,Point(450,350),90,40,"Hit Me")
        self.untapbutton = Button(self.win,Point(450,400),90,40,"Untap")
        self.quitbutton = Button(self.win,Point(450,450),90,40,"Quit")
        self.dealbutton.activate()
        self.quitbutton.activate()

        
        self.slot1 = Point(100,300)
        self.slot2 = Point(200,300)
        self.slot3 = Point(300,300)
        self.slot4 = Point(100,400)
        self.slot5 = Point(600,300)
        self.slot6 = Point(700,300)
        self.slot7 = Point(800,300)
        self.slot8 = Point(800,400)

        self.PMC = 0   # the more cards that player get
        self.CMC = 0   # the more cards that computer get
        self.round = 0
コード例 #23
0
ファイル: menu.py プロジェクト: sharat87/lights-poof
    def new_button(self, label, event_name):
        button = Button(self.surface, label,
                centerx=self.display.get_width() / 2)

        button.listen('click',
                lambda event: self.emit(event_name, **event.props))

        self.buttons.append(button)
コード例 #24
0
ファイル: itemlist.py プロジェクト: Etrnls/distributed-risk
 def addItem(self, id, name, clickable = True):
         if clickable:
                 button = Button(name, True, False, False, self)
         else:
                 button = Button(name, False, True, True, self)
         button.id = id
         self.items[id] = button
         return button
コード例 #25
0
ファイル: controller.py プロジェクト: ddtabakova/Tamagotchi
 def __setup_buttons(self, buttons):
     """set up control buttons"""
     for i in range(0, 5):
         name = "images/button-{0}.png".format(i)
         button = Button(23 + i*75, 410, 75, 75, name,
                         self.__button_pressed)
         button.display(self.__screen)
         buttons.append(button)
コード例 #26
0
ファイル: mainmenu.py プロジェクト: dnlkng/zplayer
    def build_menu(self):
        music_button = Button((60, 80, 80, 80), value="music", cb=self.on_button_clicked)
        music_button.iconFg = pygame.image.load("./resources/images/note.png")
        book_button = Button((180, 80, 80, 80), value="audiobooks", cb=self.on_button_clicked)
        book_button.iconFg = pygame.image.load("./resources/images/book.png")

        self.buttons.append(music_button)
        self.buttons.append(book_button)
コード例 #27
0
ファイル: game.py プロジェクト: Huangtang31/Blackjack-1P
def rulesWindow():

    #Create a window that displays the rules of Blackjack.
    rules = GraphWin("Rules", 540, 400)
    rules.setCoords(0, 0, 540, 400)
    rules.setBackground('White')

    #Print the title of the window.
    title = Text(Point(270, 380), 'Basic Rules of Blackjack')
    title.setStyle('bold')
    title.setTextColor('red')
    title.setSize(16)
    title.draw(rules)

    #Print the main text of the window.
    body = Text(Point(270, 350), '  Blackjack is played with the dealer being dealt two cards and the player being')
    body.draw(rules)
    body = Text(Point(270, 330), 'dealt two cards with the goal to get as close to or equal 21 without going over.')
    body.draw(rules)
    body = Text(Point(270, 310), '  If the dealer or the player get what is called a \'blackjack\', which is a')
    body.draw(rules)
    body = Text(Point(270, 290), 'combination of an ace and a 10-card(10, J, Q, K), he or she wins on the first')
    body.draw(rules)
    body = Text(Point(270, 270), 'turn. If both the dealer and the player get blackjack, a \'push\' or a tie occurs.')
    body.draw(rules)
    body = Text(Point(270, 250), '  If neither the dealer or the player get blackjack, play continues. The player')
    body.draw(rules)
    body = Text(Point(270, 230), 'is given a chance to hit to get closer or equal 21 or stand to maintain their')
    body.draw(rules)
    body = Text(Point(270, 210), 'hand in hopes of beating the dealer. If the player\'s hand total exceeds 21, he')
    body.draw(rules)
    body = Text(Point(270, 190), 'or she \'busts\' and loses to the dealer. If the player has 5 cards and is 21')
    body.draw(rules)
    body = Text(Point(270, 170), 'or less, they win with a 5-card charlie. The same applies to the dealer. Once')
    body.draw(rules)
    body = Text(Point(270, 150), 'the player chooses to stand, play switches to the dealer.')
    body.draw(rules)
    body = Text(Point(270, 130), '  The dealer must also follow the same rules as the player. Once both')
    body.draw(rules)
    body = Text(Point(270, 110), 'sides stand, the dealer and the player compare cards and whoever has the ')
    body.draw(rules)
    body = Text(Point(270, 90), 'highest total wins! If both players have the same total, they \'push\' or tie.')
    body.draw(rules)

    #Create a button that when clicked closes the rules window.
    closeButton = Button(rules, Point(270, 40), 70, 40, 'Got it!')
    closeButton.activate()

    #Get where the user clicked the mouse.
    mouseClick = rules.getMouse()

    #If the user did not click the button, wait on another click.
    while not closeButton.clicked(mouseClick):
        mouseClick = rules.getMouse()

    #Close the rules window.
    rules.close()
コード例 #28
0
ファイル: tkplus.py プロジェクト: todd-x86/tkplus
 def cool():
     global f
     messagebox.show('hello world')
     f1 = Form(caption="New Form", left=320, top=200)
     btn1 = Button(f1, caption='Hello', left=5, top=5, width=200, height=100)
     btn1.on_click = cool2
     btn1.background = 'blue'
     f1.show_modal()
     print "I'm a cool app"
コード例 #29
0
    def test_button(self):
        button = Button((0, 0), (50, 50), "TEST", (0, 0, 0), (0, 0, 0))

        class EVT:
            def __init__(self, event, key):
                self.type = event
                self.key = key
        self.assertEqual(button.is_pressed((10, 10), [EVT(6, 0)]), True)
        self.assertEqual(button.is_pressed((400, 10), [EVT(6, 0)]), False)
コード例 #30
0
ファイル: textBox.py プロジェクト: habahut/GrocerySpy
class TextBox(Sprite):
    def __init__(self, ID, wh, loc, font, imgFolder):
        Sprite.__init__(self)
        self.theFont = font
        self.width, self.height = wh
        self.identity = ID
        self.text = "++++"

        self.image = pygame.Surface(wh)
        self.image.fill((255,255,255))
        self.rect = self.image.get_rect()

        self.doneButton = Button(imgFolder, "textButton", (self.rect.left, self.rect.bottom - 166),
                                 "done", -1)
        self.doneButton.addText("Add Entry")
    
        self.image.blit(self.doneButton.getImage(), self.doneButton.getRect())

        x,y = loc
        self.rect.top += y
        self.rect.left += x

    def setLocation(self, loc):
        x,y = loc
        self.rect.top += y
        self.rect.left += x

    def getIdentity(self):
        return self.identity

    def isClicked(self, xy):
        # need to scale the xy value to be relative to the textBox window
        x,y = xy
        x -= self.rect.left
        y -= self.rect.top
        xy = x,y
        
        if self.doneButton.getRect().collidepoint(xy):
             return self.text
        else:
            return None
        

    def addText(self, string):
        self.text = string
        textBox = TextBlock("doesntMatter", string, self.theFont, 15,60, self.height - 200)
        self.image.blit(textBox.getImage(), textBox.getRect())

    def getRect(self):
        return self.rect

    def getImage(self):
        return self.image

    def scroll(self, dy):
        pass
コード例 #31
0
class AlienInvasion:
    """管理游戏资源和行为的美"""

    def __init__(self):
        """初始化游戏并创建游戏资源"""
        pygame.init()
        self.settings = Settings()
        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
        pygame.display.set_caption("Alien Invasion")

        # 创建一个用于存储游戏统计信息的实例
        self.stats = GameStats(self)
        # 创建存储游戏统计信息的实例
        # 并创建计分牌
        self.sb = Scoreboard(self)
        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()
        self._create_fleet()
        # 创建play按钮
        self.play_button = Button(self, 'Play')

    def _create_fleet(self):
        """创建外星人群"""
        # 创建一个外星人并计算一行可容纳多少个外星人
        # 外星人的间距为外星人宽度
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)
        # 计算屏幕可容纳多少行外星人
        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height -
                             (3 * alien_height) - ship_height)
        number_rows = available_space_y // (2 * alien_height)
        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                self._create_alien(alien_number, row_number)

    def _create_alien(self, alien_number, row_number):
        """创建一个外星人并将其放在当前行"""
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        self.aliens.add(alien)

    def _check_keydown_events(self, event):
        if event.key == pygame.K_RIGHT:
            # 向右移动飞船
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()

    def _check_keyup_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False

    def _fire_bullet(self):
        """创建一颗子弹,并将其加入编组bullets中"""
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _check_play_button(self, mouse_pos):
        """在玩家单击Play按钮时开始游戏"""
        button_checked = self.play_button.rect.collidepoint(mouse_pos)
        if button_checked and not self.stats.game_active:
            # 重置游戏统计信息
            self.stats.restart_stats()
            self.stats.game_active = True
            self.sb.prep_score()
            self.sb.prep_level()
            self.sb.prep_ships()
            # 清空余下的外星人和子弹
            self.aliens.empty()
            self.bullets.empty()
            # 创建一群新的外星人,并将飞船放置屏幕底端的中央
            self._create_fleet()
            self.ship.center_ship()
            # 隐藏鼠标光标
            pygame.mouse.set_visible(False)
            # 重置游戏设置
            self.settings.initialize_dynamic_settings()

    def _check_event(self):
        # 监视键盘和鼠标事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_bullet_alien_collisions(self):
        # 检查是否有子弹击中了外星人。
        # 如果是,就删除相应的子弹和外星人
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)
        if collisions:
            for aliens in collisions.values():
                self.stats.score += self.settings.alien_points * len(aliens)
            self.sb.prep_score()
            self.sb.check_high_score()
        if not self.aliens:
            # 删除现有的子弹并新建一群外星人
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()
            # 提高等级
            self.stats.level += 1
            self.sb.prep_level()

    def _update_bullets(self):
        """更新子弹的位置并删除消失的子弹"""
        # 更新子弹的位置
        self.bullets.update()
        # 删除消失的子弹
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)

        self._check_bullet_alien_collisions()

    def _check_fleet_edges(self):
        """有外星人到达边缘时采取相应的措施"""
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        """将整行外星人下移,并改变它们的方向"""
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _ship_hit(self):
        """响应飞船被外星人撞到"""
        if self.stats.ships_left > 0:
            # 将ships_left减1并更新记分牌
            self.stats.ships_left -= 1
            self.sb.prep_ships()
            # 清空余下的外星人和子弹
            self.aliens.empty()
            self.bullets.empty()
            # 创建一群新的外星人,并将飞船放置屏幕底端的中央
            self._create_fleet()
            self.ship.center_ship()

            # 暂停
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _check_aliens_bottom(self):
        """检查是否有外星人到达了屏幕底端"""
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                # 像飞船被撞一样处理
                self._ship_hit()
                break

    def _update_aliens(self):
        """
            检查是否有外星人位于屏幕边缘,
            并更新整群外星人的位置
        """
        self._check_fleet_edges()
        self.aliens.update()
        # 检测外星人和飞船之间的碰撞
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()
        # 检测是否有外星人到达了屏幕底端
        self._check_aliens_bottom()

    def _update_screen(self):
        # 每次循环时都重绘屏幕
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.aliens.draw(self.screen)
        # 显示得分
        self.sb.show_score()
        # 如果游戏处于非活跃状态,就绘制Play按钮
        if not self.stats.game_active:
            self.play_button.draw_button()
        # 让最近描绘的屏幕可见
        pygame.display.flip()

    def run_game(self):
        """开始游戏的主循环"""
        while True:
            self._check_event()
            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()
            self._update_screen()
コード例 #32
0
ファイル: alien_invasion.py プロジェクト: gitr-hub/alienINV
class AlienInvasion:
    """
    Overall class to manage game assets and behavior.
    """
    def __init__(self):
        """
        Initialize the game, and create class variables.
        :type self: class function accessable across class
        :param self: class namespace
        """
        pygame.init()
        """
        Class dependancy = pygame
        """
        self.settings = Settings()
        # self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        # self.screen = pygame.display.set_mode((self.settings.screen_width,
        #                                       self.settings.screen_height))
        self.screen = pygame.display.set_mode((1200, 800))
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height

        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)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()
        self._create_fleet()
        """
        Make the Play button.
        """
        self.play_button = Button(self, "Play")
        """
        Set the background color.
        """
        self.bg_color = (230, 230, 230)
        self.ship.blitme()

    def run_game(self):
        """
        Start the main loop for the game.
        """
        while True:
            self._check_events()
            # print(f"self._check_events() = {self._check_events()}")
            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()
            else:
                self._check_events()
#                pass
#                print("Ships Depleted ---- End Game")
#                sys.exit()
            self._update_screen()

    def _check_events(self):
        """
        EVENT LOOP: Watch for keypresses and mouse events.
        :meta public:
        """
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_play_button(self, mouse_pos):
        """
        Start a new game when the player clicks Play.
        :type mouse_pos: 'int'
        :param mouse_pos: the position of the mouse
        :meta public:
        """

        # 3456789012345678901234567890123456789012345678901234567890123456789012345678
        # -------v---------v---------v---------v---------v---------v---------v-------|

        if self.play_button.rect.collidepoint(mouse_pos):
            #            self.stats.game_active = True
            button_clicked = self.play_button.rect.collidepoint(mouse_pos)
            print(f"Button Clicked: {button_clicked}")
            print(f"In condition: if self.play_button.rect.collidepoint \
                                                                (mouse_pos)")
            print(f"Check Play Button State: {self.stats.game_active}")
            if button_clicked and not self.stats.game_active:
                # Reset the game settings.
                self.settings.initialize_dynamic_settings()
                print(f"In condition: if button_clicked and not \
                                                     self.stats.game_active")
                print(f"Check Play Button State: {self.stats.game_active}")
                """
                Reset the game statistics.
                """
                self.stats.reset_stats()
                self.stats.game_active = True
                self.sb.prep_score()
                self.sb.prep_level()
                self.sb.prep_ships()
                """
                Get rid of any remaining aliens and bullets.
                """
                self.bullets.empty()
                """
                Create a new fleet and center the ship.
                """
                self._create_fleet()
                self.ship.center_ship()
                """
                Hide the mouse cursor.
                """
            pygame.mouse.set_visible(False)

    def _check_keydown_events(self, event):
        # print("Entered _check_keydown_events")
        """
        Respond to keypresses.
        :meta public:
        """
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_q:
            print("User quit game!!")
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()

    def _check_keyup_events(self, event):
        # print("Entered _check_keyup_events")
        """
        Respond to key releases.
        :meta public:
        """
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False

    def _fire_bullet(self):
        # print("Entered _fire_bullet")
        """
        Create a new bullet and add it to the bullets group.
        :meta public:
        """
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _update_bullets(self):
        # print("Entered _update_bullets")
        """
        Update position of bullets and get rid of old bullets.
        :meta public:

        Update bullet positions.
        """
        self.bullets.update()
        """
        Get rid of bullets that have disappeared.
        """
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)
        self._check_bullet_alien_collisions()
        # print(len(self.bullets))  # REVIEW CHECK BULLET REMOVAL AT TOP

    def _check_bullet_alien_collisions(self):
        # print("Entered _check_bullet_alien_collisions")
        """
        Respond to bullet-alien collisions.
        :meta public:

        Remove any bullets and aliens that have collided.
        Check for any bullets that have hit aliens.
        If so, get rid of the bullet and the alien.
        """
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens,
                                                True, True)
        if collisions:
            for aliens in collisions.values():
                self.stats.score += self.settings.alien_points * len(aliens)
            self.sb.prep_score()
            self.sb.check_high_score()
        if not self.aliens:
            """
            Destroy existing bullets and create new fleet.
            """
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()
            """
            Increase level
            """
            self.stats.level += 1
            self.sb.prep_level()

    def _update_aliens(self):
        """
        Check if the fleet is at an edge,
        then update the positions of all aliens in the fleet.
        :meta public:
        """
        self._check_fleet_edges()
        self.aliens.update()
        """
        Look for alien-ship collisions.
        """
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()
            # print("Ship Hit")
        """
        Look for aliens hitting the bottom of the screen.
        """
        self._check_aliens_bottom()

    def _create_fleet(self):
        # print("Entered _create_fleet")
        """
        Create the fleet of aliens.
        :meta public:

        Create an alien and find the number of aliens in a row.
        Spacing between each alien is equal to one alien width.

        Make an alien.
        """
        alien = Alien(self)
        self.aliens.add(alien)  #REVIEW
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)
        """
        Determine the number of rows of aliens that fit on the screen.
        """
        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height - \
                             (3 * alien_height) - ship_height)
        number_rows = available_space_y // (2 * alien_height)
        """
        Create the full fleet of aliens.
        """
        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                self._create_alien(alien_number, row_number)

    def _create_alien(self, alien_number, row_number):
        # print("Entered _create_alien")
        """
        Create an alien and place it in the row.
        :meta public:
        """
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        self.aliens.add(alien)

    def _check_fleet_edges(self):
        # print("Entered _check_fleet_edges")
        """
        Respond appropriately if any aliens have reached an edge.
        :meta public:
        """
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        # print("Entered _change_fleet_direction")
        """
        Drop the entire fleet and change the fleet's direction.
        :meta public:
        """
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
            self.settings.fleet_direction *= -1

    def _ship_hit(self):
        # print("Entered _ship_hit")
        """
        Respond to the ship being hit by an alien.
        :meta public:
        """
        if self.stats.ships_left > 0:
            """
            Decrement ships_left and update scoreboard.
            """
            self.stats.ships_left -= 1
            self.sb.prep_ships()
            """
            Get rid of any remaining aliens and bullets.
            """
            self.aliens.empty()
            self.bullets.empty()
            """
            Create a new fleet and center the ship.
            """
            self._create_fleet()
            self.ship.center_ship()
            """
            Pause.
            """
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)
            self.settings.increase_speed()

    def _check_aliens_bottom(self):
        # print("Entered _check_aliens_bottom")
        """
        Check if any aliens have reached the bottom of the screen.
        :meta public:
        """
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                """
                Treat this the same as if the ship got hit.
                """
                self._ship_hit()
                break

    def _update_screen(self):
        # print("Entered _update_screen")
        """
        Update images on the screen, and flip to the new screen.
        :meta public:

        Redraw the screen during each pass through the loop.
        """
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.aliens.draw(self.screen)
        """
        Draw the score information.
        """
        self.sb.show_score()
        """
        Draw the play button if the game is inactive.
        """
        # print(f"Game State: {self.stats.game_active}")
        if not self.stats.game_active:
            self.play_button.draw_button()

        pygame.display.flip()
コード例 #33
0
class AlienInvasion:
    '''Overall class to manage game assets and behavior'''

    def __init__(self):
        '''Initialize the game, and create game resources'''
        pygame.init()
        self.settings = Settings()

        self.screen = pygame.display.set_mode((self.settings.screen_width,self.settings.screen_height))
        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)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()

        self._create_fleet()

        self.play_button = Button(self,"Play")

    def run_game(self):
        '''Start the main loop for the game'''
        while True:
            self._check_events()

            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()

            self._update_screen()
    
    def _check_events(self):
        """Respond to keypresses and mouse events"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)                
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)

    
    def _check_play_button(self, mouse_pos):
        """start a new game when the player clicks play"""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:

            #reset the game settings
            self.settings.initialize_dynamic_settings()

            # reset the game statistics
            self.stats.reset_stats()
            self.stats.game_active = True
            self.sb.prep_score()
            self.sb.prep_level()
            self.sb.prep_ships()

            #get rid of any remaining aliens and bullets
            self.aliens.empty()
            self.bullets.empty()

            #create a new fleet and center the ship
            self._create_fleet()
            self.ship.center_ship()

            #hide the mouse cursor
            pygame.mouse.set_visible(False)

    
    def _check_keydown_events(self,event):
        """Respond to keypresses"""
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()

    
    def _check_keyup_events(self,event):
        """Respond to key releases"""
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False
                    
    
    def _create_fleet(self):
        """Create the fleet of aliens"""
        # make an alien
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)

        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height)
        number_rows = available_space_y // (2 * alien_height)

        # create the first row of aliens
        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                self._create_alien(alien_number, row_number)
            


    def _create_alien(self, alien_number, row_number):
        """Create an alien and place it in the row"""
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        self.aliens.add(alien)

    def _check_fleet_edges(self):
        """respond appropriately if any aliens have reached an edge"""
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        """drop the entire fleet and change the fleet's direction"""
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    
    def _ship_hit(self):
        """respond to the ship being hit by an alien"""
        if self.stats.ships_left > 0:
            #decrement ships left and update scoreboard
            self.stats.ships_left -= 1
            self.sb.prep_ships()

            #get rid of any remaining aliens and bullets
            self.aliens.empty()
            self.bullets.empty()

            #create a new fleet and center the ship
            self._create_fleet()
            self.ship.center_ship()

            #pause
            sleep(0.5)
        
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)
        

    def _update_aliens(self):
        """update the positions of all aliens in the fleet"""
        self._check_fleet_edges()
        self.aliens.update()

        # look for alien - ship collisions
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()

        # look for aliens hitting the bottom of the screen
        self._check_aliens_bottom()

    def _fire_bullet(self):
        """Create new bullet and add it to the bullets group"""
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    
    def _update_bullets(self):
        """Update the positions of bullets and get rid of old bullets"""
        #Update bullet positions
        self.bullets.update()

            #Get rid of bullets that have dissapeared
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)

        self._check_bullet_alien_collisions()

    def _check_bullet_alien_collisions(self):
        """Respond to bullet alien collisions"""
        #check for bullets that have hit aliens
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)

        if collisions:
            for aliens in collisions.values():
                self.stats.score += self.settings.alien_points * len(aliens)
            self.sb.prep_score()
            self.sb.check_high_score
        
        if not self.aliens:
            #destroy existing bullets and create new fleet
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()

            # increase level
            self.stats.level += 1
            self.sb.prep_level()

    
    def _check_aliens_bottom(self):
        """check if any aliens have reached the bottom of the screen"""
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                #treat this the  same as if the ship was hit
                self._ship_hit()
                break


    def _update_screen(self):
        """Update on images on the screen, and flip to next screen"""
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.aliens.draw(self.screen)

        #draw the score information
        self.sb.show_score()

        if not self.stats.game_active:
            self.play_button.draw_button()

         # make the most recently drawn screen visible
        pygame.display.flip()
コード例 #34
0
ファイル: main.py プロジェクト: Galtron-OpenSource/Galtron-1
def runGame():
    #Initialize game and create a window
    pg.init()
    #create a new object using the settings class
    setting = Settings()
    #creaete a new object from pygame display
    screen = pg.display.set_mode((setting.screenWidth, setting.screenHeight))
    #set window caption using settings obj
    pg.display.set_caption(setting.windowCaption)

    playBtn = Button(setting, screen, "PLAY", 200)
    menuBtn = Button(setting, screen, "MENU", 250)
    twoPlayBtn = Button(setting, screen, "2PVS", 250)
    setBtnbtn = Button(setting, screen, "SETTING", 400)
    aboutBtn = Button(setting, screen, "ABOUT", 300)
    quitBtn = Button(setting, screen, "QUIT", 350)
    #make slector for buttons
    sel = Selector(setting, screen)
    sel.rect.x = playBtn.rect.x + playBtn.width + 10
    sel.rect.centery = playBtn.rect.centery

    #Create an instance to stor game stats
    stats = GameStats(setting)
    sb = Scoreboard(setting, screen, stats)

    #Make a ship
    ship = Ship(setting, screen)
    #Ships for two player
    ship1 = Ship(setting, screen)
    ship2 = Ship(setting, screen)

    #make a group of bullets to store
    bullets = Group()
    eBullets = Group()

    #Make an alien
    aliens = Group()
    gf.createFleet(setting, screen, ship, aliens)
    pg.display.set_icon(pg.transform.scale(ship.image, (32, 32)))

    runGame = True

    #Set the two while loops to start mainMenu first
    while runGame:
        #Set to true to run main game loop
        while stats.mainMenu:
            mm.checkEvents(setting, screen, stats, sb, playBtn, twoPlayBtn,
                           aboutBtn, quitBtn, menuBtn, sel, ship, aliens,
                           bullets, eBullets)
            mm.drawMenu(setting, screen, sb, playBtn, menuBtn, twoPlayBtn,
                        aboutBtn, quitBtn, sel)

        while stats.mainGame:
            #Game functions
            gf.checkEvents(setting, screen, stats, sb, playBtn, quitBtn, sel,
                           ship, aliens, bullets, eBullets)  #Check for events
            if stats.gameActive:
                gf.updateAliens(setting, stats, sb, screen, ship, aliens,
                                bullets, eBullets)  #Update aliens
                gf.updateBullets(setting, screen, stats, sb, ship, aliens,
                                 bullets, eBullets)  #Update collisions
                ship.update()  #update the ship
            gf.updateScreen(setting, screen, stats, sb, ship, aliens, bullets,
                            eBullets, playBtn, menuBtn, quitBtn,
                            sel)  #Update the screen

        while stats.mainAbout:
            About.checkEvents(setting, screen, stats, sb, playBtn, quitBtn,
                              menuBtn, sel, ship, aliens, bullets, eBullets)
            About.drawMenu(setting, screen, sb, menuBtn, quitBtn, sel)

        while stats.twoPlayer:
            """
			tp.checkEvents(setting, screen, stats, playBtn, quitBtn, sel, bullets, eBullets, ship1, ship2)
			if stats.gameActive:
				ship1.update()
				tp.updateBullets(setting, screen, stats, ship1, ship2, bullets, eBullets)
			tp.updateScreen(setting, screen, stats, bullets, eBullets, playBtn, menuBtn, quitBtn, sel, ship1, ship2)
			"""
        while stats.mainGame:
            if runGame == True:
                print("test")
コード例 #35
0
    pygame.init()  #初始化
    pygame.mixer.init()

    global is_start  #判断开始没
    is_start = 0
    screen = pygame.display.set_mode((400, 500))
    pygame.display.set_caption('爆敲猫头')
    window_image = pygame.image.load('./cat_head.png')
    pygame.display.set_icon(window_image)
    #写两个开始的介绍
    titleObj = pygame.font.SysFont('方正兰亭超细黑简体', 50)
    titleObj.set_bold(True)  # 加粗
    textObj = titleObj.render('爆敲猫头', True, bright_green)
    textRectObj = textObj.get_rect()
    textRectObj.center = (200, 100)
    startBtn = Button(screen)  #开始按钮
    #文本框

    #开始时中间图片
    cat_image = pygame.image.load('./cat_head.png')
    cat_rect = cat_image.get_rect()
    cat_rect.center = screen.get_rect().center
    # 刚开始的下文字框
    beatObj = pygame.font.SysFont('方正兰亭超细黑简体', 20)
    beatObj.set_bold(True)
    beatText = beatObj.render('狂点鼠标!爆敲猫头!!!', True, blue)
    beat_rect = beatText.get_rect()
    beat_rect.centerx = cat_rect.centerx
    beat_rect.top = 500 - 60
    #开始隐藏的猫图
    catBeatImg = pygame.image.load(cat_beat[0])
コード例 #36
0
class AlienInvasion:
    """管理游戏资源和行为的类"""
    def __init__(self):
        """初始化游戏并创建游戏资源"""
        pygame.init()
        self.settings = Settings()

        # self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
        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
        pygame.display.set_caption('Alien Invasion')

        # 统计信息,创建计分板
        self.game_stats = GameStats(self)
        self.scoreboard = Scoreboard(self)

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()

        self._create_fleet()

        # 创建play按钮
        self.play_button = Button(self, 'Play')
        # 隐藏光标
        pygame.mouse.set_visible(False)

    def run_game(self):
        """开始游戏的主循环"""
        while True:
            # 监视键盘和鼠标事件
            self._check_events()

            # 游戏处于活动状态,就继续游戏
            if self.game_stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()
            else:
                # 游戏结束
                pass

            # 每次循环时都重绘屏幕
            self._update_screen()

    def _check_events(self):
        """相应按键和鼠标事件"""
        for even in pygame.event.get():
            if even.type == pygame.QUIT:
                sys.exit()
            elif even.type == pygame.KEYDOWN:
                if even.key == pygame.K_RIGHT:
                    self.ship.moving_right = True
                elif even.key == pygame.K_LEFT:
                    self.ship.moving_left = True
                elif even.key == pygame.K_q:
                    sys.exit()
                elif even.key == pygame.K_SPACE:
                    self._fire_bullet()
            elif even.type == pygame.KEYUP:
                if even.key == pygame.K_RIGHT:
                    self.ship.moving_right = False
                elif even.key == pygame.K_LEFT:
                    self.ship.moving_left = False
            elif even.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _update_bullets(self):
        """更新子弹的位置并删除消失的子弹"""
        # 更新子弹位置
        self.bullets.update()
        # 删除消失的子弹
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)

        self._check_bullet_alien_collisions()

    def _update_screen(self):
        """更新屏幕上的图像,并切换到新屏幕"""
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.aliens.draw(self.screen)
        self.scoreboard.show_score()

        # 如果游戏处于非活动状态,绘制play按钮
        if not self.game_stats.game_active:
            self.play_button.draw_button()
            # 显示鼠标
            pygame.mouse.set_visible(True)

        # 让最近绘制的屏幕可见
        pygame.display.flip()

    def _fire_bullet(self):
        """创建一颗子弹,并将其加入到bullets中"""
        if len(self.bullets) < self.settings.bullet_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _create_fleet(self):
        """创建外星人群"""
        # 创建一个外星人并计算一行可容纳多少外星人
        alien = Alien(self)
        alien_width = alien.rect.width
        alien_height = alien.rect.height
        available_space_x = self.settings.screen_width - 2 * alien_width
        number_aliens_x = available_space_x // (2 * alien_width)
        available_space_y = self.settings.screen_height - 5 * alien_height - self.ship.rect.height
        number_aliens_y = available_space_y // (2 * alien_height)

        # 创建外星人
        for row_number in range(number_aliens_y):
            # 隔一行创建一队外星人
            if row_number % 2 == 0:
                selected_number = choices(range(number_aliens_x), k=3)
                for alien_number in selected_number:
                    self._create_alien(row_number, alien_number)

    def _create_alien(self, row_number, alien_number):
        """创建单个外星人,加入到aliens中"""
        alien = Alien(self)
        alien_width = alien.rect.width
        alien_height = alien.rect.height
        alien_x = alien_width + 2 * alien_number * alien_width
        alien_y = alien_height + 2 * row_number * alien_height
        alien.x = alien_x
        alien.rect.x = alien_x
        alien.rect.y = alien_y
        self.aliens.add(alien)

    def _update_aliens(self):
        """更新所有外星人的位置"""
        self._check_fleet_edges()
        self.aliens.update()

        # 检测飞船和外星人的碰撞
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()

        # 外星人突破了防线
        self._check_fleet_break_through()

    def _check_fleet_edges(self):
        """有外星人到达边缘时采取相应措施"""
        for alien in self.aliens.sprites():
            alien.check_edges()

    def _check_fleet_break_through(self):
        """检测外星人是否突破防线"""
        for alien in self.aliens.copy():
            if alien.check_break_through():
                self._ship_hit()
                # 消去这个外星人
                self.aliens.remove(alien)

    def _check_bullet_alien_collisions(self):
        """检查子弹和外星人碰撞"""
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens,
                                                True, True)
        if collisions:
            for aliens in collisions.values():
                self.game_stats.score += int(
                    round(self.settings.alien_points * len(aliens)))
            self.scoreboard.prep_score()
        if not self.aliens:
            # 删除现有的所有子弹,并创建新的外星人
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()
            # 等级提高
            self.game_stats.level += 1
            self.scoreboard.prep_level()

    def _ship_hit(self):
        """相应飞船被外星人撞到"""

        # 将ship_left减一
        self.game_stats.ship_left -= 1
        self.scoreboard.prep_red_heart()

        if self.game_stats.ship_left <= 0:
            self.game_stats.game_active = False
            # 检查是否诞生了最高分
            self.scoreboard.check_high_score()

        # 暂停
        sleep(0.5)

    def _check_play_button(self, mouse_pos):
        """在玩家单击play按钮时开始新游戏"""
        if self.play_button.rect.collidepoint(
                mouse_pos) and not self.game_stats.game_active:
            # 重置难度
            self.settings.init_dynamic_settings()
            # 重置统计信息
            self.game_stats.reset_stats()
            self.game_stats.game_active = True
            self.scoreboard.prep_score()
            self.scoreboard.prep_level()
            self.scoreboard.prep_red_heart()

            # 清空余下的外星人和子弹
            self.aliens.empty()
            self.bullets.empty()

            # 创建一群新的外星人并让飞船居中
            self._create_fleet()
            self.ship.center_ship()

            # 隐藏光标
            pygame.mouse.set_visible(False)
コード例 #37
0
class GameInterface():
    """
        Manages the display and management of events in the game window page
    """

    BOARD_SIZE = 550
    #Size of the game board as it should be displayed on the interface and not of the original image
    BOARD_PADDING = 6

    #Initialization functions
    def __init__(self, interface, game):

        print("Constructor GameInterface")

        self.l_button_to_draw_by_page = [[], []]
        self.l_easel_case_rectangle = []
        self.l_img_letter = []
        self.l_message = []

        #Movement of letters
        self.letter_moving_mode = False
        #True if the player is moving a letter on the game interface
        self.letter_moving_index = -1
        #Index in the alphabet of the moving letter

        #Joker
        self.joker_choice_mode = False
        #True if the window for choosing the letter of the joker is displayed
        self.l_joker_letter_choice_rect = []
        #Dimensions and positions of the letters "buttons" which allow to choose the joker

        self.exit_after_save_window = False

        self.interface = interface
        self.game = game

        self.page = Page.Game

        #Initialisation of the graphic elements
        self.init_game_page()
        self.init_save_page()

        self.load_images()

    def init_game_page(self):
        """
            Initialize the game page, create widgets like buttons that you put in a list
            so you can manage their event and draw them later
        """

        interface_width = self.interface.GAME_WINDOW_WIDTH
        interface_height = self.interface.GAME_WINDOW_HEIGHT

        self.bttn_pick_new_letters = Button()
        self.bttn_pick_new_letters.set_text("Piocher de nouvelles lettres")
        self.bttn_pick_new_letters.set_text_size(24)
        self.bttn_pick_new_letters.set_color((255, 255, 255))
        self.bttn_pick_new_letters.set_pos((interface_width / 2, 670))
        self.bttn_pick_new_letters.set_underline(True)

        self.bttn_next_round = Button()

        if (self.game.get_game_taken_up()):
            self.bttn_next_round.set_text("Reprendre la partie")
        else:
            self.bttn_next_round.set_text("Commencer la partie")

        self.bttn_next_round.set_text_size(25)
        self.bttn_next_round.set_color((255, 255, 255))
        self.bttn_next_round.set_pos((970, 650))
        self.bttn_next_round.set_padding(10)
        self.bttn_next_round.set_border(True)
        self.bttn_next_round.set_border_thickness(3)

        self.bttn_pause = Button()
        self.bttn_pause.set_text("Mettre en pause")
        self.bttn_pause.set_text_size(26)
        self.bttn_pause.set_color((255, 255, 255))
        self.bttn_pause.set_pos((127, 300))
        self.bttn_pause.set_padding(8)

        bttn_display_help = Button()
        bttn_display_help.set_text("Afficher l'aide")
        bttn_display_help.set_text_size(26)
        bttn_display_help.set_color((255, 255, 255))
        bttn_display_help.set_pos((127, 330))
        bttn_display_help.set_padding(8)

        bttn_return_to_menu = Button()
        bttn_return_to_menu.set_text("Retour au menu principal")
        bttn_return_to_menu.set_text_size(24)
        bttn_return_to_menu.set_color((255, 255, 255))
        bttn_return_to_menu.set_pos((127, 380))
        bttn_return_to_menu.set_padding(8)

        page = Page.Game
        self.l_button_to_draw_by_page[page].append(self.bttn_pick_new_letters)
        self.l_button_to_draw_by_page[page].append(self.bttn_next_round)
        self.l_button_to_draw_by_page[page].append(self.bttn_pause)
        self.l_button_to_draw_by_page[page].append(bttn_display_help)
        self.l_button_to_draw_by_page[page].append(bttn_return_to_menu)

        self.message_placed_word = Message()
        self.message_scrabble = Message()
        self.message_pick_stack = Message()
        self.message_end_game = Message()

        self.l_message.append(self.message_placed_word)
        self.l_message.append(self.message_scrabble)
        self.l_message.append(self.message_pick_stack)
        self.l_message.append(self.message_end_game)

    def init_save_page(self):
        """
            Initialize the save page, create widgets like buttons that you put in a list
            so you can manage their event and draw them later
        """

        interface_width = self.interface.GAME_WINDOW_WIDTH
        interface_height = self.interface.GAME_WINDOW_HEIGHT

        bttn_save = Button("Sauvegarder la partie")
        bttn_save.set_color((0, 0, 0))
        bttn_save.set_background_color((255, 255, 255))
        bttn_save.set_pos((interface_width / 2, 330))
        bttn_save.set_padding(10)
        bttn_save.set_text_size(24)
        bttn_save.set_border(True)
        bttn_save.set_border_color((0, 224, 73))
        bttn_save.set_border_thickness(3)

        bttn_dont_save = Button("Quitter sans sauvegarder")
        bttn_dont_save.set_color((0, 0, 0))
        bttn_dont_save.set_background_color((255, 255, 255))
        bttn_dont_save.set_pos((interface_width / 2, 440))
        bttn_dont_save.set_padding(10)
        bttn_dont_save.set_text_size(24)
        bttn_dont_save.set_border(True)
        bttn_dont_save.set_border_color((0, 224, 73))
        bttn_dont_save.set_border_thickness(3)

        bttn_cancel = Button("Retour au jeu")
        bttn_cancel.set_color((0, 0, 0))
        bttn_cancel.set_background_color((255, 255, 255))
        bttn_cancel.set_pos((interface_width / 2, 500))
        bttn_cancel.set_padding(10)
        bttn_cancel.set_text_size(24)
        bttn_cancel.set_border(True)
        bttn_cancel.set_border_color((0, 224, 73))
        bttn_cancel.set_border_thickness(3)

        page = Page.Save
        self.l_button_to_draw_by_page[page].append(bttn_save)
        self.l_button_to_draw_by_page[page].append(bttn_cancel)
        self.l_button_to_draw_by_page[page].append(bttn_dont_save)

    def load_images(self):
        """
            Loads all images to avoid wasting time loading them later
        """

        self.scrabble_board = pygame.image.load(
            os.path.join("Images", "scrabble_board.png"))
        self.scrabble_board = pygame.transform.scale(
            self.scrabble_board, (self.BOARD_SIZE, self.BOARD_SIZE))

        for i in range(26):
            img_letter_name = "letter_" + chr(65 + i) + ".png"
            img_letter_path = os.path.join("Images", "Letters",
                                           img_letter_name)

            img_letter = pygame.image.load(img_letter_path)

            case_size = int((self.BOARD_SIZE - self.BOARD_PADDING * 2) / 15)

            self.l_img_letter.append(img_letter)

        img_joker_path = os.path.join("Images", "Letters", "joker.png")
        img_joker = pygame.image.load(img_joker_path)

        self.l_img_letter.append(img_joker)

        self.img_loop = pygame.image.load(os.path.join("Images", "loop.png"))
        self.img_background_save = pygame.image.load(
            os.path.join("Images", "background_save.png"))

    #Draw functions
    def draw(self, window):
        """
            Draws the game or save interface according to the current page
            and refreshes the window.
        """

        if (self.page == Page.Game):
            self.draw_game_page(window)
        elif (self.page == Page.Save):
            self.draw_save_page(window)

        pygame.display.flip()

    def draw_game_page(self, window):

        case_size = (self.BOARD_SIZE - self.BOARD_PADDING * 2) / 15

        interface_width = self.interface.GAME_WINDOW_WIDTH
        interface_height = self.interface.GAME_WINDOW_HEIGHT

        background_rect = (0, 0, interface_width, interface_height)
        pygame.draw.rect(window, (46, 40, 42), background_rect)

        #DRAW BOARD

        board_x = interface_width / 2 - self.BOARD_SIZE / 2
        board_y = 21

        window.blit(self.scrabble_board, (board_x, board_y))

        game_board = self.game.get_game_board()

        for case_x in range(15):
            for case_y in range(15):

                letter_index = game_board[case_x][case_y]
                if (letter_index != -1):
                    img_letter = self.l_img_letter[letter_index]

                    img_letter_size = int(case_size)
                    img_letter = pygame.transform.scale(
                        img_letter, (img_letter_size, img_letter_size))

                    img_letter_x = board_x + self.BOARD_PADDING + case_x * case_size + 1
                    img_letter_y = board_y + self.BOARD_PADDING + case_y * case_size + 2

                    window.blit(img_letter, (img_letter_x, img_letter_y))

        #DRAW EASEL

        del self.l_easel_case_rectangle[:]

        easel_width = self.BOARD_SIZE / 1.3
        easel_height = easel_width / 7

        letter_case_size = int(easel_width / 7)

        font = pygame.font.SysFont("", size=20)
        for i in range(7):
            x = interface_width / 2 - easel_width / 2 + (
                i * letter_case_size) + (i / 1.88) * 2
            y = 585

            letter_case_rect = (x, y, letter_case_size, letter_case_size)

            letter_case_rectangle = Shape()
            letter_case_rectangle.new_rectangle(window, (255, 255, 255),
                                                letter_case_rect, 2)
            letter_case_rectangle.draw()

            self.l_easel_case_rectangle.append(letter_case_rectangle)
            #Pour avoir rapidement la dimension et la position de chaque case du chevalet au moment de gérer les évênements

            image_index_letter = font.render(str(i + 1), True, (255, 255, 255))

            img_index_letter_size = font.size(str(i + 1))
            img_x = x + letter_case_size / 2 - img_index_letter_size[0] / 2
            img_y = y + letter_case_size / 2 - img_index_letter_size[1] / 2

            window.blit(image_index_letter, (img_x, img_y))

            #On affiche les lettres dans les cases
            player_turn = self.game.get_player_turn()
            if (player_turn != None):
                player_easel = player_turn.get_easel()
                letter_index = player_easel.get_l_letter()[i]

                if (letter_index != -1):
                    img_letter = self.l_img_letter[letter_index]
                    img_letter = pygame.transform.scale(
                        img_letter,
                        (letter_case_size - 2, letter_case_size - 2))

                    pygame.draw.rect(window, (0, 0, 0), letter_case_rect, 3)

                    #On réduit légèrement la taille des lettres pour qu'elles rentrent dans les cases sans effacer les contours
                    letter_case_rect = (x + 1, y + 1, letter_case_size - 2,
                                        letter_case_size - 2)
                    window.blit(img_letter, letter_case_rect)

            #Si il y a des lettres qui ont été désigné pour être échangé alors on marque ces lettres avec un signe
            l_easel_case_to_renew = self.game.get_l_easel_case_to_renew()
            if (i in l_easel_case_to_renew):

                img_loop_size = int(case_size / 1.8)
                img_loop = pygame.transform.scale(
                    self.img_loop, (img_loop_size, img_loop_size))

                img_loop_x = letter_case_rect[0] + letter_case_rect[
                    3] - img_loop_size - 4
                img_loop_y = letter_case_rect[1] + 3

                window.blit(img_loop, (img_loop_x, img_loop_y))

        #DRAW SCORE

        font = pygame.font.SysFont("", size=30)
        img_text_score = font.render("Score", True, (255, 255, 255))

        window.blit(img_text_score, (865, 150))

        font = pygame.font.SysFont("", size=25)

        l_player = self.game.get_l_player()
        y = 178
        for player in l_player:
            player_name = player.get_name()
            player_score = player.get_score()

            txt_score_player = player_name + ": " + str(
                player_score) + " points"
            img_text_score_player = font.render(txt_score_player, True,
                                                (255, 255, 255))

            window.blit(img_text_score_player, (865, y))
            y += 25

        #DRAW BUTTONS

        for button in self.l_button_to_draw_by_page[self.page]:
            button.draw(window)

        #DRAW GRID MARKS

        img_y = 5
        x_min = interface_width / 2 - (
            self.BOARD_SIZE) / 2 + self.BOARD_PADDING + case_size / 2
        for x_i in range(0, 15):
            letter = chr(65 + x_i)

            font = pygame.font.SysFont("", size=20)
            img_grid_mark = font.render(letter, True, (255, 255, 255))

            image_size = font.size(letter)
            img_x = x_min + x_i * case_size - image_size[0] / 2

            window.blit(img_grid_mark, (img_x, img_y))

        img_x = x_min - case_size / 2 - 26
        y_min = board_y + self.BOARD_PADDING + case_size / 2
        for y_i in range(0, 15):
            number = str(y_i + 1)

            font = pygame.font.SysFont("", size=20)
            img_grid_mark = font.render(number, True, (255, 255, 255))

            image_size = font.size(number)
            img_y = y_min + y_i * case_size - image_size[1] / 2

            window.blit(img_grid_mark, (img_x, img_y))

        #DRAW TIME

        font = pygame.font.SysFont("", size=25)

        played_time = self.game.get_played_time()
        text_time_played = get_played_time_formatted(played_time)

        img_text_time_played = font.render(text_time_played, True,
                                           (255, 255, 255))
        window.blit(img_text_time_played, (10, 10))

        #DRAW MENU

        font = pygame.font.SysFont("", size=26)
        img_text_menu = font.render("Menu de jeu", True, (255, 255, 255))

        img_text_menu_size = img_text_menu.get_size()
        img_text_menu_x = 127 - img_text_menu_size[0] / 2
        img_text_menu_y = 258 - img_text_menu_size[1] / 2

        window.blit(img_text_menu, (img_text_menu_x, img_text_menu_y))

        line_start_pos = (127 - img_text_menu_size[0] / 2, 279)
        line_end_pos = (127 + img_text_menu_size[0] / 2, 279)
        pygame.draw.line(window, (255, 255, 255), line_start_pos, line_end_pos)

        line_start_pos = (127 - img_text_menu_size[0] / 2, 355)
        line_end_pos = (127 + img_text_menu_size[0] / 2, 355)
        pygame.draw.line(window, (255, 255, 255), line_start_pos, line_end_pos)

        menu_outline_rect = (15, 223, 222, 186)
        pygame.draw.rect(window, (255, 255, 255), menu_outline_rect, 2)

        #DRAW MOVING LETTER

        if (self.letter_moving_index != -1):
            img_letter_moving = self.l_img_letter[self.letter_moving_index]
            img_letter_moving_size = int(case_size)

            img_letter_moving = pygame.transform.scale(
                img_letter_moving,
                (img_letter_moving_size, img_letter_moving_size))

            mouse_pos = pygame.mouse.get_pos()
            img_letter_moving_x = mouse_pos[0] - img_letter_moving_size / 2
            img_letter_moving_y = mouse_pos[1] - img_letter_moving_size / 2

            window.blit(img_letter_moving,
                        (img_letter_moving_x, img_letter_moving_y))

        #DRAW JOKER CHOICE

        if (self.joker_choice_mode):

            space_between_letter = 18
            img_letter_size = 35

            background_width = img_letter_size * 10 + space_between_letter * 8 + 60
            background_x = interface_width / 2 - background_width / 2

            pygame.draw.rect(window, (255, 255, 255),
                             (background_x, 160, background_width, 300))
            pygame.draw.rect(window, (0, 0, 0),
                             (background_x, 160, background_width, 300), 3)

            font = pygame.font.SysFont("", size=40)
            img_text_choice_joker = font.render("*** Choix du joker ***", True,
                                                (0, 0, 0))

            img_text_choice_joker_size = img_text_choice_joker.get_size()
            img_text_choice_joker_x = interface_width / 2 - img_text_choice_joker_size[
                0] / 2

            window.blit(img_text_choice_joker, (img_text_choice_joker_x, 200))

            self.l_joker_letter_choice_rect.clear()

            y_min = 250
            for y_i in range(3):

                if (y_i < 2):
                    line_width = img_letter_size * 10 + space_between_letter * 9
                else:
                    line_width = img_letter_size * 7 + space_between_letter * 6

                img_letter_y = y_min + y_i * 60
                x_min = interface_width / 2 - line_width / 2
                for x_i in range(10):

                    img_index = y_i * 10 + x_i
                    if (img_index == 26):
                        break

                    img_letter = self.l_img_letter[img_index]
                    img_letter = pygame.transform.scale(
                        img_letter, (img_letter_size, img_letter_size))

                    img_letter_x = x_min + x_i * (space_between_letter +
                                                  img_letter_size)
                    if (y_i == 2):
                        img_letter_x += img_letter_size

                    letter_frame_rect = (img_letter_x - 2, img_letter_y - 2,
                                         img_letter_size + 4,
                                         img_letter_size + 4)

                    letter_frame_srect = Shape()
                    letter_frame_srect.new_rectangle(window, (0, 0, 0),
                                                     letter_frame_rect, 2)

                    letter_frame_srect.draw()

                    self.l_joker_letter_choice_rect.append(letter_frame_srect)

                    window.blit(img_letter, (img_letter_x, img_letter_y))

        #DRAW PART PLAYER TURN

        player_turn = self.game.get_player_turn()
        if (player_turn != None):
            font = pygame.font.SysFont("", size=25)

            txt_player_turn = "C'est à " + player_turn.get_name(
            ) + " de jouer !"
            img_txt_player_turn = font.render(txt_player_turn, True,
                                              (255, 255, 255))

            image_size = img_txt_player_turn.get_size()
            window.blit(img_txt_player_turn, (970 - image_size[0] / 2, 600))

        for message in self.l_message:
            message.draw(window)

        #Pour le debug
        '''for x in range(0, 15):
            for y in range(0, 15):
                board_rect = (self.BOARD_PADDING+x*case_size, self.BOARD_PADDING+y*case_size, case_size, case_size);
                pygame.draw.rect(window, (255, 255, 255), board_rect);'''

    def draw_save_page(self, window):

        interface_width = self.interface.GAME_WINDOW_WIDTH
        interface_height = self.interface.GAME_WINDOW_HEIGHT

        img_background_save = pygame.transform.scale(
            self.img_background_save, (interface_width, interface_height))
        window.blit(img_background_save, (0, 0))

        font = pygame.font.SysFont("", size=38)
        img_save_title = font.render(
            "Voulez vous sauvegarder avant de quitter ?", True,
            (255, 255, 255))

        img_save_title_size = img_save_title.get_size()
        img_save_title_x = interface_width / 2 - img_save_title_size[0] / 2

        window.blit(img_save_title, (img_save_title_x, 200))

        for button in self.l_button_to_draw_by_page[self.page]:
            button.draw(window)

    def set_pause(self, pause):
        """
            Pauses the game in progress or restarts it according to the parameter received
        """

        game_status = self.game.get_game_status()
        if (game_status == GameStatus.NotStarted
                or game_status == GameStatus.Finished):
            return

        if (pause == True):
            self.game.set_game_status(GameStatus.Paused)
            self.bttn_pause.set_text("Reprendre la partie")

            self.game.stop_timer()

        elif (pause == False):
            self.game.set_game_status(GameStatus.InProgress)
            self.bttn_pause.set_text("Mettre en pause")

            self.game.start_timer()

    def show_message_placed_word(self, word, value, player_name):
        """
            Displays a message in the middle of the screen with the word placed,
            if it is valid and if so the number of points won
        """

        interface_width = self.interface.GAME_WINDOW_WIDTH
        interface_height = self.interface.GAME_WINDOW_HEIGHT

        if (value != 0):
            title_text = "Le joueur " + player_name + " a posé le mot " + word
            subtitle_text = "Il remporte " + str(value) + " points !"
        else:
            title_text = "Le joueur " + player_name + " a posé le mot " + word
            subtitle_text = "Ce mot n'est pas valable, il ne remporte aucun point"

        self.message_placed_word.set_text_title(title_text)
        self.message_placed_word.set_text_subtitle(subtitle_text)
        self.message_placed_word.set_horizontal_alignment(Alignment.Center)
        self.message_placed_word.set_text_title_size(40)
        self.message_placed_word.set_text_subtitle_size(32)
        self.message_placed_word.set_space_between_titles(20)
        self.message_placed_word.set_color_title((0, 0, 0))
        self.message_placed_word.set_color_subtitle((0, 0, 0))
        self.message_placed_word.set_border_color((0, 0, 0))
        self.message_placed_word.set_border_thickness(4)

        self.message_placed_word.set_pos((interface_width / 2, 200))

        self.message_placed_word.show(3)

    def show_message_scrabble(self, player_name):
        """
            Displays a message in the middle of the screen indicating that the
            player has played scrabble and the bonus points he has won
        """

        interface_width = self.interface.GAME_WINDOW_WIDTH
        interface_height = self.interface.GAME_WINDOW_HEIGHT

        title_text = "Le joueur " + player_name + " a fait un scrabble !!!"
        subtitle_text = "Il remporte 50 points bonus !"

        self.message_scrabble.set_text_title(title_text)
        self.message_scrabble.set_text_subtitle(subtitle_text)
        self.message_scrabble.set_horizontal_alignment(Alignment.Center)
        self.message_scrabble.set_text_title_size(40)
        self.message_scrabble.set_text_subtitle_size(32)
        self.message_scrabble.set_space_between_titles(20)
        self.message_scrabble.set_color_title((0, 0, 0))
        self.message_scrabble.set_color_subtitle((0, 0, 0))
        self.message_scrabble.set_border_color((0, 0, 0))
        self.message_scrabble.set_border_thickness(4)

        self.message_scrabble.set_pos((interface_width / 2, 200))

        self.message_placed_word.add_queued_message(self.message_scrabble, 3)

    def show_message_pick_stack(self, player_name, l_letter_picked,
                                n_letter_remained):
        """
            Displays a message in the middle of the screen with the picked letters
            and the number of letters remaining in the stack
        """

        interface_width = self.interface.GAME_WINDOW_WIDTH
        interface_height = self.interface.GAME_WINDOW_HEIGHT

        title_text = "Le joueur " + player_name + " a pioché les lettres " + "".join(
            l_letter_picked)
        print(title_text)
        subtitle_text = "Il reste " + str(
            n_letter_remained) + " lettres dans la pioche"

        self.message_pick_stack.set_text_title(title_text)
        self.message_pick_stack.set_text_subtitle(subtitle_text)
        self.message_pick_stack.set_horizontal_alignment(Alignment.Center)
        self.message_pick_stack.set_text_title_size(40)
        self.message_pick_stack.set_text_subtitle_size(32)
        self.message_pick_stack.set_space_between_titles(20)
        self.message_pick_stack.set_color_title((0, 0, 0))
        self.message_pick_stack.set_color_subtitle((0, 0, 0))
        self.message_pick_stack.set_border_color((0, 0, 0))
        self.message_pick_stack.set_border_thickness(4)

        self.message_pick_stack.set_pos((interface_width / 2, 200))

        self.message_pick_stack.show(3)

    def show_message_save_loaded(self):
        """
            Displays a message in the middle of the screen indicating that
            the saved game has been loaded.
        """

        interface_width = self.interface.GAME_WINDOW_WIDTH
        interface_height = self.interface.GAME_WINDOW_HEIGHT

        title_text = "Partie chargée avec succès !"

        self.message_pick_stack.set_text_title(title_text)
        self.message_pick_stack.set_horizontal_alignment(Alignment.Center)
        self.message_pick_stack.set_text_title_size(40)
        self.message_pick_stack.set_color_title((0, 0, 0))
        self.message_pick_stack.set_border_color((0, 0, 0))
        self.message_pick_stack.set_border_thickness(4)
        self.message_pick_stack.set_padding(14)

        self.message_pick_stack.set_pos((interface_width / 2, 200))

        self.message_pick_stack.show(3)

    def show_message_end_game(self, winner_name, winner_score):
        """
            Displays an end-of-game message in the middle of the screen
            indicating either a tie with the score or the winner and his score.
        """

        interface_width = self.interface.GAME_WINDOW_WIDTH
        interface_height = self.interface.GAME_WINDOW_HEIGHT

        if (winner_name != ""):
            title_text = "Victoire de " + winner_name + " !!!"
            subtitle_text = "Il remporte la partie avec " + str(
                winner_score) + " points"
        else:
            title_text = "Egalité !"
            subtitle_text = "Les deux joueurs égalisent avec " + str(
                winner_score) + " points"

        self.message_end_game.set_text_title(title_text)
        self.message_end_game.set_text_subtitle(subtitle_text)
        self.message_end_game.set_horizontal_alignment(Alignment.Center)
        self.message_end_game.set_text_title_size(40)
        self.message_end_game.set_text_subtitle_size(32)
        self.message_end_game.set_space_between_titles(20)
        self.message_end_game.set_color_title((0, 0, 0))
        self.message_end_game.set_color_subtitle((0, 0, 0))
        self.message_end_game.set_border_color((0, 0, 0))
        self.message_end_game.set_border_thickness(4)
        self.message_end_game.set_padding(17)

        self.message_end_game.set_pos((interface_width / 2, 200))

        self.message_placed_word.add_queued_message(self.message_end_game, 12)

    def event(self, e):
        """
            Manages keyboard, mouse, ... events
        """

        interface_width = self.interface.GAME_WINDOW_WIDTH
        interface_height = self.interface.GAME_WINDOW_HEIGHT

        #If the user clicks the cross to close the game window, the save window will open asking if he wish to save before exiting
        if (e.type == pygame.QUIT):
            self.page = Page.Save
            self.exit_after_save_window = True

        elif (e.type == pygame.MOUSEBUTTONUP):

            mouse_x = e.pos[0]
            mouse_y = e.pos[1]

            for button in self.l_button_to_draw_by_page[self.page]:

                #Button click management
                if (button.in_bounds(mouse_x, mouse_y)):

                    if (self.page == Page.Game):

                        if (button.get_text() == "Commencer la partie"
                                or button.get_text() == "Reprendre la partie"):

                            game_status = self.game.get_game_status()
                            if (game_status == GameStatus.Paused):
                                self.set_pause(False)
                            else:
                                self.game.start_game()
                                self.bttn_next_round.set_text(
                                    "Passer au tour suivant")

                        elif (button.get_text() == "Retour au menu principal"):
                            self.page = Page.Save

                        elif (button.get_text() == "Mettre en pause"):
                            self.set_pause(True)

                        elif (button.get_text() ==
                              "Piocher de nouvelles lettres"):

                            game_status = self.game.get_game_status()
                            if (game_status == GameStatus.InProgress):

                                self.bttn_next_round.set_text(
                                    "Valider et piocher")
                                self.bttn_pick_new_letters.set_text("Annuler")

                                self.game.set_picking_mode(True)

                        elif (button.get_text() == "Valider et piocher"):

                            self.bttn_next_round.set_text(
                                "Passer au tour suivant")
                            self.bttn_pick_new_letters.set_text(
                                "Piocher de nouvelles lettres")

                            self.game.next_round()

                        elif (button.get_text() == "Annuler"):

                            self.bttn_next_round.set_text(
                                "Passer au tour suivant")
                            self.bttn_pick_new_letters.set_text(
                                "Piocher de nouvelles lettres")

                            self.game.set_picking_mode(False)

                            l_easel_case_to_renew = self.game.get_l_easel_case_to_renew(
                            )
                            l_easel_case_to_renew.clear()

                        elif (button.get_text() == "Passer au tour suivant"):
                            self.game.next_round()

                            game_status = self.game.get_game_status()
                            if (game_status == GameStatus.Finished):
                                self.bttn_next_round.set_text(
                                    "Refaire une partie ?")

                        elif (button.get_text() == "Refaire une partie ?"):

                            menu_interface = self.interface.get_menu_interface(
                            )

                            #Players are recreated from their usernames, useless to create a "reset" function.
                            l_player_to_reset = self.game.get_l_player()

                            l_player = []
                            for player in l_player_to_reset:

                                player_name = player.get_name()
                                player = Player(player_name)
                                l_player.append(player)

                            menu_interface.replay_game(l_player)

                    elif (self.page == Page.Save):

                        if (button.get_text() == "Retour au jeu"):
                            self.page = Page.Game
                            self.exit_after_save_window = False

                        elif (button.get_text() == "Quitter sans sauvegarder"):

                            menu_interface = self.interface.get_menu_interface(
                            )
                            menu_interface.change_page(0)

                        elif (button.get_text() == "Sauvegarder la partie"):
                            self.game.save_game()

                            menu_interface = self.interface.get_menu_interface(
                            )
                            menu_interface.change_page(0)

                    if (button.get_text() == "Sauvegarder la partie" or
                            button.get_text() == "Quitter sans sauvegarder"):

                        if (self.exit_after_save_window):
                            controller = self.interface.get_controller()
                            controller.quit()
                        else:
                            self.interface.change_page(0)

                #Easel click management
                for i in range(len(self.l_easel_case_rectangle)):

                    easel_case_rectangle = self.l_easel_case_rectangle[i]

                    if (easel_case_rectangle.in_bounds(mouse_x, mouse_y)):

                        if (self.game.get_picking_mode()):

                            l_easel_case_to_renew = self.game.get_l_easel_case_to_renew(
                            )

                            if (not (i in l_easel_case_to_renew)):
                                l_easel_case_to_renew.append(i)
                            else:
                                l_easel_case_to_renew.remove(i)

                        else:

                            if (self.letter_moving_mode != True):

                                self.letter_moving_mode = True

                                player = self.game.get_player_turn()

                                easel = player.get_easel()
                                easel_l_letter = easel.get_l_letter()

                                self.letter_moving_index = easel_l_letter[i]
                                self.easel_start_case_index = i
                                easel_l_letter[i] = -1

                            else:

                                self.letter_moving_mode = False

                                player = self.game.get_player_turn()

                                easel = player.get_easel()
                                easel_l_letter = easel.get_l_letter()

                                easel_l_letter[
                                    self.
                                    easel_start_case_index] = easel_l_letter[i]
                                easel_l_letter[i] = self.letter_moving_index
                                self.letter_moving_index = -1

                #Game board click management
                case_size = (self.BOARD_SIZE - self.BOARD_PADDING * 2) / 15
                for x_i in range(15):
                    for y_i in range(15):

                        board_x = interface_width / 2 - self.BOARD_SIZE / 2
                        board_y = 21

                        case_x = board_x + self.BOARD_PADDING + x_i * case_size + 1
                        case_y = board_y + self.BOARD_PADDING + y_i * case_size + 2

                        letter_case_rectangle = Shape()
                        letter_case_rectangle.new_rectangle(
                            None, (255, 255, 255),
                            (case_x, case_y, case_size, case_size))

                        if (letter_case_rectangle.in_bounds(mouse_x, mouse_y)):

                            if (self.letter_moving_index != -1):

                                letter_placed = self.game.add_letter_to_game_board(
                                    x_i, y_i, self.letter_moving_index)
                                if (letter_placed):

                                    if (self.letter_moving_index == 26):
                                        self.joker_choice_mode = True

                                        l_joker_pos = self.game.get_l_joker_pos(
                                        )
                                        l_joker_pos.append((x_i, y_i))

                                    self.letter_moving_mode = False
                                    self.letter_moving_index = -1

                            elif (e.button == 2 or e.button == 3):

                                l_case_modified_during_round = self.game.get_l_case_modified_during_round(
                                )
                                if ((x_i, y_i)
                                        in l_case_modified_during_round):

                                    l_case_modified_during_round.remove(
                                        (x_i, y_i))
                                    game_board = self.game.get_game_board()

                                    letter_index = game_board[x_i][y_i]
                                    game_board[x_i][y_i] = -1

                                    player = self.game.get_player_turn()
                                    player_easel = player.get_easel()

                                    index_free_case = player_easel.get_first_free_place(
                                    )

                                    easel_l_value = player_easel.get_l_letter(
                                    )
                                    easel_l_value[
                                        index_free_case] = letter_index

        elif (e.type == pygame.MOUSEBUTTONDOWN):

            mouse_x = e.pos[0]
            mouse_y = e.pos[1]

            #Management of clicks on the window of the joker's letter choice
            if (self.joker_choice_mode):

                for button in self.l_button_to_draw_by_page[self.page]:

                    for letter_index in range(
                            len(self.l_joker_letter_choice_rect)):
                        letter_choice_rect = self.l_joker_letter_choice_rect[
                            letter_index]

                        if (letter_choice_rect.in_bounds(mouse_x, mouse_y)):

                            self.joker_choice_mode = False

                            game_board = self.game.get_game_board()
                            l_joker_pos = self.game.get_l_joker_pos()

                            last_joker_pos = l_joker_pos[-1]
                            game_board[last_joker_pos[0]][
                                last_joker_pos[1]] = letter_index

        elif (e.type == pygame.MOUSEMOTION):

            mouse_x = e.pos[0]
            mouse_y = e.pos[1]

            for button in self.l_button_to_draw_by_page[self.page]:

                if (button.in_bounds(mouse_x, mouse_y)):
                    button.highlight(0, (23, 192, 187))
                else:
                    button.remove_highlighting()

    #GETTERS/SETTERS
    def get_game_instance(self):
        return self.game

    def set_game_instance(self, game_instance):
        self.game = game_instance

    def change_page(self, page):
        self.page = page
コード例 #38
0
ファイル: alien_invasion.py プロジェクト: AScharphorn/CIT228
class AlienInvasion:
    """Overall class to manage game assets and behavior."""

    def __init__(self):        
        """Initialize the game and create game resources."""
        pygame.init()
        self.settings = Settings()

        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
        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)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()

        self._create_fleet()

        # Make the Play button.
        self.play_button = Button(self, "Play")

    def run_game(self):
        """Start the main loop for the game."""
        while True:
            self._check_events()

            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()
                
            self._update_screen()

    def _update_bullets(self):
        """Update the position of bullets and get rid of old bullets."""
        # Update bullet positions.
        self.bullets.update()

        # Get rip of bullets that have disappeared.
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)
        print(len(self.bullets))
        
        self._check_bullet_alien_collisions()

    def _check_bullet_alien_collisions(self):
        """Respond to bullet-alien collisions"""
        # Remove any bullets and aliens that have collided.
        collisions = pygame.sprite.groupcollide(
            self.bullets, self.aliens, True, True)

        if collisions:
            for aliens in collisions.values():
                self.stats.score += self.settings.alien_points * len(aliens)
            self.sb.prep_score()
            self.sb.check_high_score()
        
        if not self.aliens:
            # Destory the existing bullets and create new fleet.
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()

            # Increase level.
            self.stats.level += 1
            self.sb.prep_level()

    def _check_events(self):
        # Respond to Keypresses and mouse events.
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running=False
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_keydown_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()
        
    def _check_keyup_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False

    def _fire_bullet(self):
        """Create a new bullet and add it to the bullets group."""
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _update_screen(self):
        # Update images on the screen, and flip to the new scene.
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.aliens.draw(self.screen)

        # Draw the score information.
        self.sb.show_score()

        # Draw the play button if the game is inactive.
        if not self.stats.game_active:
            self.play_button.draw_button()
            
        pygame.display.flip()

    def _create_fleet(self):
        """Create the fleet of aliens."""
        # Create the alien and find the number of aliens in a row.
        # Spacing between each alien is equal to one alien width
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)

        # Determin the number of rows of aliens that fit on the screen.
        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height -
                                (3 * alien_height) - ship_height)
        number_rows = available_space_y // (2 * alien_height)

        # Create the full fleet of aliens.
        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                self._create_alien(alien_number, row_number)
            
    def _create_alien(self, alien_number, row_number):
        # Create and alien and place it in the row.
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        self.aliens.add(alien)

    def _update_aliens(self):
        """
        Check if the fleet is at an edge,
           then update the positions of all aliens in the fleet.
        """
        self._check_fleet_edges()
        self.aliens.update()

        # Look for alien-ship collisions.
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()
        
        # Look for aliens hitting the bottom of the screen.
        self._check_aliens_bottom()
    
    def _check_fleet_edges(self):
        """Respond appropriatly if any aliens have reached an edge."""
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_directions()
                break

    def _change_fleet_directions(self):
        """Drop the entire fleet and change the fleet's direction."""
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1
    
    def _ship_hit(self):
        """Respond to the ship being hit by an alien."""
        if self.stats.ships_left > 0:
            # Decrement ships_left, and update scoreboard.
            self.stats.ships_left -= 1
            self.sb.prep_ships()

            # Get rip of any remaining aliens and bullets
            self.aliens.empty()
            self.bullets.empty()

            # Create a new fleet and center the ship.
            self._create_fleet()
            self.ship.center_ship()

            # Pause.
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _check_aliens_bottom(self):
        """Check if any of the laiens have reached the bottom of the screen."""
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                # Treat this the same as if the ship got hit
                self._ship_hit()
                break

    def _check_play_button(self, mouse_pos):
        """Start a new game when the player clicks Play."""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:
            # Reset the game settings.
            self.settings.initialize_dynamic_settings()

            # Reset the game statistics.
            self.stats.reset_stats()
            self.stats.game_active = True
            self.sb.prep_score()
            self.sb.prep_level()
            self.sb.prep_ships()

            # Get rid of any remaining aliens and bullets.
            self.aliens.empty()
            self.bullets.empty()

            # Create a new fleet and center the ship.
            self._create_fleet()
            self.ship.center_ship()

            # Hide the mouse cursor.
            pygame.mouse.set_visible(False)
コード例 #39
0
class AlienInvision:
    """Класс для управления ресурсами и поведением игры."""

    def __init__(self):
        """Инициализирует игру и создает игровые ресурсы."""

        pygame.init()
        self.settings = Settings()
        # запуск на весь экран
        # 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("Alien Invasion")

        # Создание экземпляра для хранения игровой статистики.
        self.stats = GameStats(self)
        
        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()

        self._create_fleet()

        # Создание кнопки Play.
        self.play_button = Button(self, "Play")

    def run_game(self):
        """Запуск основных циклoв игры."""
        while True:
            # Отслеживание событий клавиатуры и мыши.
            self._check_events()

            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()

            self._update_screen()

    def _check_events(self):
        """Обрабатывает нажатие клавиш и события мыши"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_play_button(self, mouse_pos):
        """Запускает новую игру при нажатии кнопки Play."""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:
            # Сброс игровых настроек.
            self.settings.initialize_dynamic_settings()
            # Сброс игровой статистики.
            self.stats.reset_stats()
            self.stats.game_active = True

            # Очистка списков пришельцев и снарядов.
            self.aliens.empty()
            self.bullets.empty()
            
            # Создание нового флота и размещение в центре.
            self._create_fleet()
            self.ship.center_ship()

            # Указатель мыши скрывается.
            pygame.mouse.set_visible(False)

    def _check_keydown_events(self, event):
        # нажатие клавиш
        if event.key == pygame.K_RIGHT:
            # переместить корабль вправо
            self.ship.moving_right = True
            # перемещает влево
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()

    def _check_keyup_events(self, event):
        # Реагирует на отпускание клавиш.
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False

    def _fire_bullet(self):
        '''Создание снаряда и включение его в группу bullets.'''
        if len(self.bullets) < self.settings.bullet_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _update_bullets(self):
        """Обновляет позиции снарядов и уничтожает старые снаряды."""
        # Обновление снаряда.
        self.bullets.update()
        
        # Удаление снарядов, вышедших за край экрана.
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)

        self._check_bullet_alien_collisions()

    def _check_bullet_alien_collisions(self):
        '''Обработка коллизий снарядов с пришельцами.'''
        # Удаление снарядов и пришельцев, участвующих  в колизиях.
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True) # 1 True - уничтожения снаряда

        if not self.aliens:
            # Уничтожение существующих снарядов и создание нового флота.
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()

    def _update_aliens(self):
        '''Обновляет позиции всех пришельцев во флоте.'''
        # Проверяет достиг ли флот края экрана, с последующим обновлением позиций всех пришельцев во флоте.
        self._check_fleet_edges()
        self.aliens.update()
        # Проверка колизий "пришелец - корабль".
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()

        # Проверяет, добрались ли пришельцы до нижнего края экрана.
        self._check_aliens_bottom()

    def _check_aliens_bottom(self):
        '''Проверяет, добрались ли пришельцы до нижнего края экрана.'''
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                # Происходит то же, что при столковении с кораблем.
                self._ship_hit()
                break

    def _ship_hit(self):
        '''Обрабатывает столковение корабля с пришельцем.'''
        if self.stats.ships_left > 0:
            # Уменьшение ships_left
            self.stats.ships_left -= 1

            # Очистка списков пришельца и снарядов.
            self.aliens.empty()
            self.bullets.empty()

            # Cоздание нового флота и размещение корабля в центре.
            self._create_fleet()
            self.ship.center_ship()

            # Пауза.
            sleep(0.5)
        else:
            self.stats.game_active = False

    def _create_fleet(self):
        '''Создание флота вторжения.'''
        # Создание пришельца и вычисление количества пришельцев в ряду.
        # Интервал между соседними пришельцами равен ширине пришельца.
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        avalible_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = avalible_space_x // (2 * alien_width)

        '''Определяет количество рядов, помещающихся на экране.'''
        ship_height = self.ship.rect.height
        avalible_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height)
        number_rows = avalible_space_y // (2 * alien_height)

        # Создание флота вторжения.
        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                # Создание пришельца и размищение его в ряду.
                self._create_alien(alien_number, row_number)

    def _create_alien(self, alien_number, row_number):
        '''Создание пришельца и размищение его в ряду.'''
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        self.aliens.add(alien)

    def _check_fleet_edges(self):
        '''Реагирует на достижение пришельца края экрана.'''
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        '''Опускает весь флот и меняет направление флота.'''
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _update_screen(self):
        """Обновляет изображения на экране и отображает новый экран."""
        # При каждом проходе цикла перерисовывается экран.
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()

        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.aliens.draw(self.screen)

        # Кнопка Play отображается в том случае, если игра не активна
        if not self.stats.game_active:
            self.play_button.draw_button()
        # Отображение последнего прорисованного зкрана.
        pygame.display.flip()
コード例 #40
0
class AlienInvasion:
    """Overall class to manage game assets and behaviour."""
    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        self.settings = Settings()

        #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("Alien Invasion")

        # Create an instance to store game stats.
        self.stats = GameStats(self)
        # Create scoreboard
        self.scoreboard = Scoreboard(self)

        # Create objects
        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()
        self._create_fleet()

        # Make play button
        self.play_button = Button(self, "Play")

    def run_game(self):
        """Start the main loop for the game"""
        while True:
            # Watch for keyboard and mouse events
            self._check_events()
            if self.stats.game_active:
                # Updates ship's movement
                self.ship.update()

                # Update bullets
                self._bullets_update()

                # Update aliens
                self._aliens_update()
            # Redraw the screen during each pass through the loop
            self._update_screen()

            # Make themost recently drawn screen visible
            pygame.display.flip()

    def _check_events(self):
        """ Responds to keypresses and mouse events."""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keyDown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyUP_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_keyDown_events(self, event):
        """ Responds to keypresses."""
        if event.key == pygame.K_RIGHT:
            # Move the ship to the right
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()

    def _check_keyUP_events(self, event):
        """ Responds to key releases."""
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False

    def _update_screen(self):
        """ Updates the images on the screen, and flip to the new screen."""
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.aliens.draw(self.screen)

        # Draw score information
        self.scoreboard.show_score()

        if not self.stats.game_active:
            self.play_button.draw_button()

    def _fire_bullet(self):
        """ Create a new bullet each time spacebar is pressed and add it to the bullets group."""
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _remove_bullets(self):
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)

    def _create_fleet(self):
        """ Create fleet of aliens """
        # Make an alien and find the amount of aliens in a row
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)

        # Determine the amount of  alien rows
        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height - (3 * alien_height) -
                             ship_height)
        number_rows = available_space_y // (2 * alien_height)

        # Create full fleet
        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                self._create_alien(alien_number, row_number)

    def _create_alien(self, alien_number, row_number):
        alien = Alien(self)
        alien_width = alien.rect.width
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        self.aliens.add(alien)

    def _bullets_update(self):
        self.bullets.update()
        self._remove_bullets()
        self._check_bullet_alien_collisions()

    def _check_bullet_alien_collisions(self):
        """ Check for any bullets if they have hit an alien and if so then get rid of the alien. Also spawns new fleet if last fleet is annihalated"""
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens,
                                                True, True)
        if collisions:
            for hits in collisions.values():
                self.stats.score += self.settings.alien_points * len(hits)
            self.scoreboard.prep_score()
            self.scoreboard.check_high_score()

        if not self.aliens:
            #Destroy existing bullets and spawn new fleet
            self.bullets.empty()
            self._create_fleet()

            # Level up
            self.settings.level_up()
            self.stats.level += 1
            self.scoreboard.prep_level()

    def _aliens_update(self):
        """ Updates the aliens positions."""
        self._check_fleet_edges()
        self.aliens.update()
        # Look for alien-ship collisions.
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()
        # Look for aliens reaching bottom of the screen
        self._check_aliens_bottom()

    def _check_fleet_edges(self):
        """Respond appropriately if any aliens have reached an edge."""
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        """ Drop the entire fleet one row and chenge the fleet's direction. """
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _ship_hit(self):
        """ Respond to the ship being hit by an alien."""
        if self.stats.ships_left > 0:
            # Decrement ships_left.
            self.stats.ships_left -= 1
            self.scoreboard.prep_ships()

            # Get rid of any remaining aliens and bullets.
            self.aliens.empty()
            self.bullets.empty()

            # Create a new fleet and center the ship.
            self._create_fleet()
            self.ship.center_ship()

            # Pause
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _check_aliens_bottom(self):
        """ Check if any aliens have reached the bottom of the screen."""
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                # Treat the same as if ship got hit.
                self._ship_hit()
                break

    def _check_play_button(self, mouse_pos):
        """ Start a new game when player clicks Play."""
        if self.play_button.rect.collidepoint(
                mouse_pos) and not self.stats.game_active:
            self.stats.reset_stats()
            self.settings.initialize_dynamic_settings()
            self.stats.game_active = True

            #Hide mouse cursor
            pygame.mouse.set_visible(False)

            # Get rid of any leftover aliens and bullets
            self.aliens.empty()
            self.bullets.empty()

            #Create a new fleet and center the ship.
            self._create_fleet()
            self.ship.center_ship()

            self.scoreboard.prep_score()
            self.scoreboard.prep_high_score()
            self.scoreboard.prep_ships()
コード例 #41
0
class AlienInvasion:
    def __init__(self):
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption('Alien Invasion')
        self.stats = GameStats(self)
        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()
        self._create_flet()
        self.sb = Scoreboard(self)
        self.play_button = Button(self, "Gra")

    def ship_hit(self):
        if self.stats.ship_left > 0:
            self.stats.ship_left -= 1
            self.sb.prep_ships()
            self.aliens.empty()
            self.bullets.empty()
            self._create_flet()
            self.ship.center_ship()
            sleep(0.5)

        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def run_game(self):
        while True:
            self._check_events()
            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()
            self._screen_update()

    def _update_aliens(self):
        self._check_flet_edges()
        self.aliens.update()
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self.ship_hit()
        self._check_aliens_botom()

    def _check_aliens_botom(self):
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                self.ship_hit()
                break

    def _check_flet_edges(self):
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._changes_fleet_direction()
                break

    def _changes_fleet_direction(self):
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.flet_drop_speed
        self.settings.flet_direction *= -1

    def _check_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)

            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)

    def _check_play_button(self, mouse_pos):
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:
            self.settings.initialize_dynamic_settings()

            self.stats.reset_stats()
            self.stats.game_active = True
            self.sb.prep_score()
            self.sb.prep_level()
            self.sb.prep_ships()
            self.aliens.empty()
            self.bullets.empty()

            self._create_flet()
            self.ship.center_ship()

            pygame.mouse.set_visible(False)

    def _check_keydown_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()

    def _check_keyup_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False

    def _fire_bullet(self):
        if len(self.bullets) <= self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _create_flet(self):
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)
        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height - (3 * alien_height) -
                             ship_height)
        number_rows = available_space_y // (2 * alien_height)
        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                self._creat_alien(alien_number, row_number)

    def _creat_alien(self, alien_number, row_number):
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size

        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        self.aliens.add(alien)

    def _screen_update(self):

        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.aliens.draw(self.screen)

        self.sb.show_score()
        if not self.stats.game_active:
            self.play_button.draw_button()

        pygame.display.flip()

    def _update_bullets(self):
        self.bullets.update()
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)

        self._check_bulet_alien_collision()

    def _check_bulet_alien_collision(self):
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens,
                                                True, True)
        if not self.aliens:
            self.bullets.empty()
            self._create_flet()
            self.settings.incrase_speed()
            self.stats.level += 1
            self.sb.prep_level()
        if collisions:
            for aliens in collisions.values():
                self.stats.score += self.settings.alien_points * len(aliens)
            self.sb.prep_score()
            self.sb.check_high_score()
コード例 #42
0
class AlienInvasion():
    """Overall class to manage game assets and behavior"""
    def __init__(self):
        """Initialize the game and create game resources"""
        pygame.init()
        self.settings = Settings()

        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
        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
        )  # the Ship class requires the AlienInvasion Class as input parameter
        self.bullets = pygame.sprite.Group(
        )  # bullets are many objects that we will control through a Group
        self.aliens = pygame.sprite.Group()

        self._create_fleet()

        # Make the Play button
        self.play_button = Button(self, 'Play')

    def run_game(self):
        """Start the main loop of the game"""
        while True:  # main game loop is run indefinetely until the sys.exit() command
            self._check_events(
            )  # helper method to watch for keyboard and mouse events

            if self.stats.game_active:
                self.ship.update(
                )  # update the position of the ship based on key presses
                self._update_bullets()
                self._update_aliens()

            self._update_screen(
            )  # helper method to update the screen on every pass

    def _check_events(
            self):  # helper method that only affects the run_game() method
        """Respond to key presses and mouse events"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()  # quit the python interpreter when q is pressed
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_keydown_events(self, event):
        """respond to key presses"""
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True  # set the moving right flag to True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True  # set the moving left flag to True
        elif event.key == pygame.K_q:
            self._save_high_score(self.stats.high_score)
            sys.exit()  # exit when q is pressed
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()

    def _check_keyup_events(self, event):
        """respond to key presses"""
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False  # set the moving right flag to False when the Key is released
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False  # set the moving left flag to False when Key is released

    def _fire_bullet(self):
        """Create a new bullet and add it to the bullet group"""
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _check_play_button(self, mouse_pos):
        """start a new game when the player hits play"""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:
            # reset the game's dynamic settings
            self.settings.initialize_dynamic_settings()

            # reset game statistics
            self.stats.reset_stats()
            self.stats.game_active = True
            self.sb.prep_score()
            self.sb.prep_level()
            self.sb.prep_ships()

            # get rid of any remaining aliens or bullets
            self.aliens.empty()
            self.bullets.empty()

            # create a new fleet and center the ship
            self._create_fleet()
            self.ship.center_ship()

            # hide the mouse cursor
            pygame.mouse.set_visible(False)

    def _update_bullets(self):
        """Update the position of bullets and get rid of the old bullets"""
        # update bullet positions
        self.bullets.update()

        # get rid of bullets that have disappeared
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)

        self._check_bullet_alien_collision()

    def _check_bullet_alien_collision(self):
        """check whether bullet has hit aliens and whether fleet is empty, then repopulate"""
        # remove any bullets and aliens that have collided
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens,
                                                True, True)

        if collisions:
            for aliens in collisions.values():
                self.stats.score += self.settings.alien_points * len(aliens)
            self.sb.prep_score()
            self.sb.check_high_score()

        # check if all aliens are shot down
        # if so, repopulate the group
        if not self.aliens:
            # destroy existing bullets and create new fleet
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()  # increase difficulty

            # Increase Level
            self.stats.level += 1
            self.sb.prep_level()

    def _update_aliens(self):
        """
        check if the fleet is at an edge,
        then update the positions of all alliens in the fleet
        """
        self._check_fleet_edges()
        self.aliens.update()

        # Look for alien-ship collisions
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()

        # look for aliens hitting the bottom of the screen
        self._check_aliens_bottom()

    def _ship_hit(self):
        """Respond to the ship being hit by an alien"""
        if self.stats.ships_left > 0:
            # decrement ships left
            self.stats.ships_left -= 1
            self.sb.prep_ships()

            # get rid of any remaining aliens or bullets
            self.aliens.empty()
            self.bullets.empty()

            # create a new fleet and center the ship
            self._create_fleet()
            self.ship.center_ship()

            # Pause
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _check_aliens_bottom(self):
        """check if aliens hit the bottom, if yes start over"""
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                # Treat this the same as if the ship was hit
                self._ship_hit()
                break

    def _create_fleet(self):
        """Create the fleet of ALiens"""
        # Create an alien and find the number of aliens in a row
        # spacing between each alien is equal to one alien width
        alien = Alien(self)  # u create the alien using the class u wrote
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)

        # determine the number of rows of aliens that fit in the screen
        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height - (3 * alien_height) -
                             ship_height)
        number_rows = available_space_y // (4 * alien_height)

        # create the full fleet of aliens
        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                # create an alien and place it in the row
                self._create_alien(alien_number, row_number)

    def _create_alien(self, alien_number, row_number):
        """create an alien and place it in the row"""
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        self.aliens.add(alien)  # alien added to the Group

    def _check_fleet_edges(self):
        """Respond appropriately if any aliens reached an edge"""
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        """frop the entire fleet and change its direction"""
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _save_high_score(self, high_score):
        """Save the high score to a txt file"""
        high_score_file = 'high_score.json'
        with open(high_score_file, 'w') as f:
            json.dump(high_score, f)

    def _update_screen(self):
        """update images on the screen, and flip to the new screen"""
        self.screen.fill((self.settings.bg_color))  # here the color is set
        self.ship.blitme()  # redraw the current position of the ship
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.aliens.draw(self.screen)

        # Draw the score information
        self.sb.show_score()

        # Draw the play button if the game is inactive
        if not self.stats.game_active:
            self.play_button.draw_button()

        pygame.display.flip()  # make the most recently drawn screen visible
コード例 #43
0
def main():
    print(getcwd())
    screen = pg.display.set_mode(SCREEN_SIZE)
    screen.fill(BACKGROUND_COLOR)
    pg.display.set_caption("GPR Robot GUI Controller")
    clock = pg.time.Clock()
    run = True

    # first screen elements
    input_x = InputBox(400, 100, 100, 32, text="x = ")
    input_y = InputBox(400, 133, 100, 32, text="y = ")
    manual_button = Button(325, 200, 275, 32, text="Enter Manual Mode")
    user_entry_boxes = [input_x, input_y]
    dimensions = [None, None]
    entries_accepted = [False, False]
    screen_transition_complete = False
    manual_mode = False

    # second screen elements
    info_box = InfoBox(
        int((1 / 16) * SCREEN_SIZE[0]),
        50,
        int((7 / 8) * SCREEN_SIZE[0]),
        32,
        text=INSTRUCTIONS,
    )
    console = Console(
        int((1 / 16) * SCREEN_SIZE[0]),
        info_box.rect.y + info_box.rect.h + 10,
        int((7 / 8) * SCREEN_SIZE[0]),
        32,
    )

    # robot class
    # gpr_robot = Robot()
    gpr_robot = 0
    counter = 0
    while run:
        clock.tick(FRAMERATE)
        counter += 1
        if all(entries_accepted):
            if not screen_transition_complete:
                pg.display.update()
                screen.fill(BACKGROUND_COLOR)
                screen_transition_complete = True

            draw_second_header(screen, dimensions, manual_mode=manual_mode)
            info_box.draw(screen)
        else:
            draw_first_window(screen)

        for event in pg.event.get():  # Check for any events
            if event.type == pg.QUIT:  # Check if user quit the program
                run = False  # Terminate While Loop
            if all(entries_accepted):
                try:
                    auto_move(dimensions[0], dimensions[1])
                except:
                    pass
            else:
                button_clicked = manual_button.handle_event(event)
                if button_clicked:
                    entries_accepted = [True, True]
                    manual_mode = True
                for index, box in enumerate(user_entry_boxes):
                    ret = box.handle_event(event)
                    if ret:
                        try:
                            ret = float(ret)
                            dimensions[index] = ret
                            entries_accepted[index] = True
                            box.accepted_value = True
                            box.color = COLOR_ACCEPTED
                            if index == 0:
                                screen.blit(
                                    CHECK_MARK_IMG,
                                    (box.text_pos_x + 300,
                                     box.text_pos_y - 10),
                                )
                            else:
                                screen.blit(
                                    CHECK_MARK_IMG,
                                    (box.text_pos_x + 300,
                                     box.text_pos_y - 42),
                                )
                        except:
                            box.color = COLOR_REJECTED
                            warning_msg = (
                                f"The value must be a number. User entered: {ret}"
                            )
                            warning_text = MSG_FONT.render(warning_msg, 1, RED)
                            screen.blit(warning_text, (90, 250))
                            warn(warning_msg)
                            dimensions[index] = USER_ENTRY_ERROR_CODE

        if all(entries_accepted):
            keys_pressed = pg.key.get_pressed()
            command = manual_move(gpr_robot, keys_pressed)
            if counter % 2 == 0:
                console.update(command)
                console.draw(screen)
        else:
            draw_dimension_text(screen, dimensions)

            for box in user_entry_boxes:
                box.update()

            for box in user_entry_boxes:
                box.draw(screen)

            manual_button.draw(screen)

        draw_bottom_banner(screen)
        pg.display.flip()

    pg.quit()
コード例 #44
0
                    # pass all other events down to the hoster
                    if event.type in MOUSE_POS_EVENT_TYPES:
                        event.abs_pos = event.pos
                    self.hoster.process_event(event)

            if self.rerender_on_next_frame:
                self.update_screen()
                self.rerender_on_next_frame = False

        pygame.display.quit()


if __name__ == "__main__":
    test_button = Button(
        1, 1, RED,
        text="Navigate to Other!",
        on_click=lambda self, event: self.run_hook("NAVIGATE_TO", "other")
    )

    test_component_1 = GridView([
        [View(5, 1, RED), View(2, 1, GREEN)],
        [View(6, 1, BLUE), test_button]
    ])

    test_component_2a = GridView([
        [View(1, 1, GREEN), View(1, 1, RED)],
        [Button(1, 1, RED, text="HIT", on_click=lambda self, event: print("HIT")), View(1, 1, GREEN)]
    ], x_flex=1, y_flex=1)

    test_assets_dir = os.path.join(os.path.dirname(__file__), "test_assets")
    test_image_source = pygame.image.load(os.path.join(test_assets_dir, "smile.png"))
コード例 #45
0
    def init_game_page(self):
        """
            Initialize the game page, create widgets like buttons that you put in a list
            so you can manage their event and draw them later
        """

        interface_width = self.interface.GAME_WINDOW_WIDTH
        interface_height = self.interface.GAME_WINDOW_HEIGHT

        self.bttn_pick_new_letters = Button()
        self.bttn_pick_new_letters.set_text("Piocher de nouvelles lettres")
        self.bttn_pick_new_letters.set_text_size(24)
        self.bttn_pick_new_letters.set_color((255, 255, 255))
        self.bttn_pick_new_letters.set_pos((interface_width / 2, 670))
        self.bttn_pick_new_letters.set_underline(True)

        self.bttn_next_round = Button()

        if (self.game.get_game_taken_up()):
            self.bttn_next_round.set_text("Reprendre la partie")
        else:
            self.bttn_next_round.set_text("Commencer la partie")

        self.bttn_next_round.set_text_size(25)
        self.bttn_next_round.set_color((255, 255, 255))
        self.bttn_next_round.set_pos((970, 650))
        self.bttn_next_round.set_padding(10)
        self.bttn_next_round.set_border(True)
        self.bttn_next_round.set_border_thickness(3)

        self.bttn_pause = Button()
        self.bttn_pause.set_text("Mettre en pause")
        self.bttn_pause.set_text_size(26)
        self.bttn_pause.set_color((255, 255, 255))
        self.bttn_pause.set_pos((127, 300))
        self.bttn_pause.set_padding(8)

        bttn_display_help = Button()
        bttn_display_help.set_text("Afficher l'aide")
        bttn_display_help.set_text_size(26)
        bttn_display_help.set_color((255, 255, 255))
        bttn_display_help.set_pos((127, 330))
        bttn_display_help.set_padding(8)

        bttn_return_to_menu = Button()
        bttn_return_to_menu.set_text("Retour au menu principal")
        bttn_return_to_menu.set_text_size(24)
        bttn_return_to_menu.set_color((255, 255, 255))
        bttn_return_to_menu.set_pos((127, 380))
        bttn_return_to_menu.set_padding(8)

        page = Page.Game
        self.l_button_to_draw_by_page[page].append(self.bttn_pick_new_letters)
        self.l_button_to_draw_by_page[page].append(self.bttn_next_round)
        self.l_button_to_draw_by_page[page].append(self.bttn_pause)
        self.l_button_to_draw_by_page[page].append(bttn_display_help)
        self.l_button_to_draw_by_page[page].append(bttn_return_to_menu)

        self.message_placed_word = Message()
        self.message_scrabble = Message()
        self.message_pick_stack = Message()
        self.message_end_game = Message()

        self.l_message.append(self.message_placed_word)
        self.l_message.append(self.message_scrabble)
        self.l_message.append(self.message_pick_stack)
        self.l_message.append(self.message_end_game)
コード例 #46
0
    for cell in cells:
        cell.activated = False


buttons = []

font = pygame.font.SysFont("Arial", 32)
big_font = pygame.font.SysFont("Arial", 64)


def change_scene(new_scene):
    global scene
    scene = new_scene


play_button = Button(screen, font, width / 2, height / 2, 200, 50, "Play", on_click=lambda: change_scene("game"))
rules_button = Button(screen, font, width / 2, height / 2 + 100, 200, 50, "Edit Rules",
                      on_click=lambda: change_scene("rules"))
explanation_button = Button(screen, font, width / 2, height / 2 + 200, 200, 50, "Explanation",
                            on_click=lambda: change_scene("explanation"))
buttons.extend([play_button, rules_button, explanation_button])

rule_buttons = []

back_button = Button(screen, font, 60, 40, 100, 50, "Back", on_click=lambda: change_scene("home"))
previous_button = Button(screen, font, width * 0.15, height / 2, 150, 50, "Previous", on_click=lambda: decRule())
next_button = Button(screen, font, width * 0.85, height / 2, 150, 50, "Next", on_click=lambda: incRule())
reset_button = Button(screen, font, width * 0.9, height / 2 + 200, 100, 50, "Reset", on_click=lambda: resetRules())
delete_button = Button(screen, font, 180, height * 0.9, 100, 50, "Delete", on_click=lambda: deleteRule())
add_button = Button(screen, font, 60, height * 0.9, 100, 50, "Add", on_click=lambda: addRule())
duplicate_button = Button(screen, font, width / 2, height * 0.9, 170, 50, "Duplicate", on_click=lambda: duplicateRule())
コード例 #47
0
    def init_save_page(self):
        """
            Initialize the save page, create widgets like buttons that you put in a list
            so you can manage their event and draw them later
        """

        interface_width = self.interface.GAME_WINDOW_WIDTH
        interface_height = self.interface.GAME_WINDOW_HEIGHT

        bttn_save = Button("Sauvegarder la partie")
        bttn_save.set_color((0, 0, 0))
        bttn_save.set_background_color((255, 255, 255))
        bttn_save.set_pos((interface_width / 2, 330))
        bttn_save.set_padding(10)
        bttn_save.set_text_size(24)
        bttn_save.set_border(True)
        bttn_save.set_border_color((0, 224, 73))
        bttn_save.set_border_thickness(3)

        bttn_dont_save = Button("Quitter sans sauvegarder")
        bttn_dont_save.set_color((0, 0, 0))
        bttn_dont_save.set_background_color((255, 255, 255))
        bttn_dont_save.set_pos((interface_width / 2, 440))
        bttn_dont_save.set_padding(10)
        bttn_dont_save.set_text_size(24)
        bttn_dont_save.set_border(True)
        bttn_dont_save.set_border_color((0, 224, 73))
        bttn_dont_save.set_border_thickness(3)

        bttn_cancel = Button("Retour au jeu")
        bttn_cancel.set_color((0, 0, 0))
        bttn_cancel.set_background_color((255, 255, 255))
        bttn_cancel.set_pos((interface_width / 2, 500))
        bttn_cancel.set_padding(10)
        bttn_cancel.set_text_size(24)
        bttn_cancel.set_border(True)
        bttn_cancel.set_border_color((0, 224, 73))
        bttn_cancel.set_border_thickness(3)

        page = Page.Save
        self.l_button_to_draw_by_page[page].append(bttn_save)
        self.l_button_to_draw_by_page[page].append(bttn_cancel)
        self.l_button_to_draw_by_page[page].append(bttn_dont_save)
コード例 #48
0
class AlienInvasion:
    """Overall class to manage game assets and behavior."""
    def __init__(self):
        """Initialize the game."""
        # Initialize game display
        pygame.init()
        self.settings = Settings()
        if self.settings.fullscreen:
            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
        else:
            self.screen = pygame.display.set_mode(
                (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Alien Invasion")

        # Game is paused initiallly
        self.active = False

        # Initialize basic logic variables
        self.level = 1
        self.ships_remaining = self.settings.ship_limit

        # Initialize game elements
        self.player_ship = Ship(self)
        self.fleet = Fleet(self)
        self.play_button = Button(self, "Play")
        self.scoreboard = Scoreboard(self)

    def run(self):
        """Start the main game loop."""
        while True:
            # Check for keyboard/mouse events
            self._check_events()

            # Update player ship and alien fleet, if game is active
            if self.active:
                self.player_ship.update()
                self.fleet.update()

            # Draw the game
            self._draw()

    def _draw(self):
        """Draw the game screen and all elements."""

        # Redraw the background
        self.screen.fill(self.settings.bg_color)

        # Redraw the player ship
        self.player_ship.draw()

        # Redraw the alien fleet
        self.fleet.draw()

        # Redraw the scoreboard
        self.scoreboard.draw()

        # Redraw play button if game is inactive
        if not self.active:
            self.play_button.draw()

        # Make the most recently drawn screen visible
        pygame.display.flip()

    def _start_game(self):
        """Start a new game."""
        # Reset game
        self.level = 1
        self.ships_remaining = self.settings.ship_limit
        self.scoreboard.reset()
        self.settings.initialize_dynamic_settings()
        self.fleet = Fleet(self)
        self.player_ship.reset()

        # Hide cursor
        pygame.mouse.set_visible(False)

        # Start game
        self.active = True

    def kill_player(self):
        """Handle player death."""
        if self.ships_remaining > 0:
            # Decrement number of ships remaining
            self.ships_remaining -= 1
            self.scoreboard.reset()

            # Create new fleet and ship
            self.fleet = Fleet(self)
            self.player_ship.reset()

            # Pause
            sleep(0.5)
        else:
            self.active = False
            pygame.mouse.set_visible(True)

    def kill_alien(self):
        """Handle alien kills."""
        self.scoreboard.set_score(self.scoreboard.score +
                                  self.settings.alien_points)

        # Create a new fleet if all aliens are gone
        if not self.fleet.aliens:
            self.player_ship.reset()
            self.fleet = Fleet(self)
            # Increment speed (difficulty)
            self.settings.increase_speed()
            # Increment level
            self.level += 1
            self.scoreboard.prep_level()

    def _check_events(self):
        """Respond to keyboard and mouse events."""
        for event in pygame.event.get():
            # Exit when the game window is closed
            if event.type == pygame.QUIT:
                self.scoreboard.save_high_score()
                sys.exit()
            # Respond to mouse events
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)
            # Respond to key events
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_event(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_event(event)

    def _check_keydown_event(self, event):
        """Respond to keypresses."""
        if event.key == pygame.K_RIGHT:
            self.player_ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.player_ship.moving_left = True
        elif event.key == pygame.K_SPACE:
            self.player_ship.fire_bullet()
        elif event.key == pygame.K_q:
            self.scoreboard.save_high_score()
            sys.exit()
        elif event.key == pygame.K_p and not self.active:
            self._start_game()

    def _check_keyup_event(self, event):
        """Respond to key releases."""
        if event.key == pygame.K_RIGHT:
            self.player_ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.player_ship.moving_left = False

    def _check_play_button(self, mouse_pos):
        """Start a new game when the player clicks Play."""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.active:
            self._start_game()
コード例 #49
0
def click_button_multi():
    global MAIN_MENU, SINGLE_PLAY, MULTI_PLAY, MULTI_AI_PLAY
    #os.startfile('multi_main.py')
    MULTI_PLAY = True
    MAIN_MENU = False


def click_button_multi_AI():
    global MAIN_MENU, SINGLE_PLAY, MULTI_PLAY, MULTI_AI_PLAY
    #print('ok good MULTI AI')
    MULTI_AI_PLAY = True
    MAIN_MENU = False


button_single = Button(410, 350, "Одиночная игра", click_button_single)
button_multi = Button(130, 350, "Мультиплеер", click_button_multi)
button_multi_AI = Button(670, 350, "Мультиплеер ИИ", click_button_multi_AI)

buttons = [button_single, button_multi, button_multi_AI]

rooms = []
room_num = 1
for i in range(1, 7):
    for j in range(1, 6):
        text = 'room: {}'.format(room_num)
        rooms.append(Button(j * 160 - 80, i * 100 - 50, text, room_num))
        room_num += 1

while run:
    if MAIN_MENU:
コード例 #50
0
class AlienInvasion:
    """Common class to manage game assets and behavior"""
    def __init__(self):
        """Initialize game and create game resources."""
        pygame.init()
        self.settings = Settings()
        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("Вторжение инопланетян")
        # Create an instance to store game statistics,
        #   and create a scoreboard.
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()
        self._create_fleet()
        # Play Button
        self.play_button = Button(self, "Играть")

    def run_game(self):
        """Start main loop for the game"""
        while True:
            self._check_events()

            if self.stats.game_active:
                self.ship.update_status()
                self.bullets.update()
                self._update_bullets()
                self._update_aliens()
            self._update_screen()

    def _check_events(self):
        """Respond to keypress and mouse movements"""
        # Watch for keyboard and mouse movements
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_play_button(self, mouse_pos):
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)

        if button_clicked and not self.stats.game_active:
            self._start_game()

    def _start_game(self):
        # Reset stats
        self.settings.difficulty(1)  # available diff levels : 3
        self.stats.reset_stats()
        self.stats.game_active = True
        self.sb.prep_score()
        self.sb.prep_level()
        self.sb.prep_ships()

        self.aliens.empty()
        self.bullets.empty()

        self._create_fleet()
        self.ship.center_ship()
        # Hide mouse
        pygame.mouse.set_visible(False)

    def _check_keydown_events(self, event):
        """Respond to keypress"""
        # If the player presses both keys at once, two separate events will be detected.
        # We can use elif blocks here because each event is connected to only one key.
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()
        # Enable and disable fullscreen mode
        elif event.key == pygame.K_p:
            self._start_game()
        elif event.key == pygame.K_f:
            if self.screen.get_flags() and pygame.FULLSCREEN:
                self.screen = pygame.display.set_mode(
                    (self.settings.screen_width, self.settings.screen_height))
            else:
                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

    def _check_keyup_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False

    def _fire_bullet(self):
        """Create new bullet and add it to the bullets group"""
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _update_bullets(self):
        # Upd bullet positions
        self.bullets.update()
        # Remove bullets that have disappeared
        for bullet in self.bullets.copy():
            if bullet in self.bullets.copy():
                if bullet.rect.bottom <= 0:
                    self.bullets.remove(bullet)
        self._check_bullet_alien_collisions()

    def _check_bullet_alien_collisions(self):
        # Check for any bullets that have hit aliens.
        # If so, get rid of the bullet and the alien
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens,
                                                True, True)
        if collisions:
            for aliens in collisions.values():
                self.stats.score += self.settings.alien_points * len(aliens)
                self.sb.prep_score()
                self.sb.check_high_score()
        if not self.aliens:
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()
            # Increase level
            self.stats.level += 1
            self.sb.prep_level()

    def _update_aliens(self):
        self._check_fleet_edges()
        self.aliens.update()

        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()
        self._check_aliens_bottom()

    def _ship_hit(self):
        if self.stats.ships_left > 0:
            self.stats.ships_left -= 1
            self.sb.prep_ships()
            self.aliens.empty()
            self.bullets.empty()
            # Create new fleet and center the ship
            self._create_fleet()
            self.ship.center_ship()
            # Pause
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _create_fleet(self):
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)

        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height - (3 * alien_height) -
                             ship_height)
        number_rows = available_space_y // (2 * alien_height)

        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                self._create_alien(alien_number, row_number)

    def _create_alien(self, alien_number, row_number):
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        self.aliens.add(alien)

    def _check_aliens_bottom(self):
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                self._ship_hit()
                break

    def _check_fleet_edges(self):
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _update_screen(self):
        """Upd images on the screen, and flip to the new screen"""
        # Redraw the screen during each pass through the loop.
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.aliens.draw(self.screen)

        self.sb.show_score()

        if not self.stats.game_active:
            self.play_button.draw_button()

        # Make the most recently drawn screen visible. This will update the contents of the entire display.
        pygame.display.flip()
コード例 #51
0
class AlienInvasion:
    def __init__(self):
        """Initialize game & resources"""
        pygame.init()  # intializes background settings
        self.settings = Settings()

        # the self.screen obj creates a `surface` that represents game screen where elements can be drawn
        ###  run in 1200 x 800 mode
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))

        ### run in fullscreen mode
        # 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

        pygame.display.set_caption("Alien_Invasion")

        # Create instance of game statistics & scoreboard
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)

        # the self.ship instance is assigned to give Ship access to all game resourses via self parameter
        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group(
        )  # similar to a list with extra features

        # create instance of alien
        self.aliens = pygame.sprite.Group()
        self._create_fleet()

        # Create a Play button
        self.play_button = Button(self, "Play !")

# # create instance of laser_blast
# self.laser = pygame.sprite.Group()

    def run_game(self):
        """Start main loop in game"""
        while True:
            self._check_events()  # check event listener

            if self.stats.game_active:
                self.ship.update()  # update position
                # self.bullets.update()  # will update each sprite in the group
                self._update_bullets()
                self._update_aliens()

#            self.laser.update()
            self._update_screen()  # refresh screen

    def _check_events(self):
        # create event listener to watch keyboard or mouse events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_play_button(self, mouse_pos):
        """ Start a new game when player clicks Play """
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:
            # Reset game settings
            self.settings.initialize_dynamic_settings()

            # Reset game stats
            self.stats.reset_stats()
            self.stats.game_active = True
            self.sb.prep_score()
            self.sb.prep_level()
            self.sb.prep_ships()

            # Remove any remaining aliends and bullets
            self.aliens.empty()
            self.bullets.empty()

            # Create new fleet and center the ship
            self._create_fleet()
            self.ship.center_ship()

            # Hide the mouse cursor when inside of game window
            pygame.mouse.set_visible(False)

    def _check_keydown_events(self, event):
        """ Set directions for current movements """
        # print('key pressed was ', (event))
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True  # move ship to the right
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True  # move ship to the left
        elif event.key == pygame.K_q:  # quit is Q is pressed
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()
# elif event.key == pygame.K_l:
#     self._fire_laser()

    def _check_keyup_events(self, event):
        """ respond to changes in direction """
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False  # moving right key released, stop moving
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False  # moving left key released, stop moving

    def _fire_bullet(self):
        """ Create a new bullet and add it to the bullets group """
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _fire_laser(self):
        print("LASER FIRED")
# print(self.settings.laser_fire_allowed)
# if self.settings.laser_fire_allowed:
#     #laser_blast = LaserBlast(self)
#     laser_blast = Bullet(self)

#     laser_blast.color = self.settings.laser_color
#     self.bullets.add(laser_blast)

    def _update_bullets(self):
        """  Update position of bullets to get rid of bullets that have exited screen """
        # Remove bullets that have reached top of screen
        self.bullets.update()  ## MOVED HERE !!!!!!

        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)
            # print(len(self.bullets))

        self._check_bullet_alien_collisions()

    def _check_bullet_alien_collisions(self):
        """ Handles hits to fleet """
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens,
                                                True, True)

        if collisions:
            for aliens in collisions.values():
                # print(f' Collision values() is {aliens}')
                self.stats.score += self.settings.alien_points * len(aliens)
            self.sb.prep_score()
            self.sb.check_high_score()

            # print out collisions dictionary
            for key, value in collisions.items():
                print(f' key: {key} value: {value}')

        if not self.aliens:
            # Destroy bullets and create new fleet
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()

            # Increase level
            self.stats.level += 1
            self.sb.prep_level()

    def _update_aliens(self):
        """ Verify if fleet at edges. if so, change position of fleet """
        self._check_fleet_edges()

        self.aliens.update()
        if pygame.sprite.spritecollideany(self.ship, self.aliens) != None:
            print("SHIP Hit !")
            self._ship_hit()

        # Verify if aliens reach the bottom of the screen
        self._check_aliens_bottom()

    def _ship_hit(self):
        """ Respond to ship being hit by alien """
        if self.stats.ships_left > 0:
            # Decrement ships_left
            self.stats.ships_left -= 1
            self.sb.prep_ships()

            # Remove remianing aliens & bullets
            self.aliens.empty()
            self.bullets.empty()

            # Create new fleet and ship at start location
            self._create_fleet()
            self.ship.center_ship()

            # pause
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _create_fleet(self):
        """ Create a fleet of aliens """
        alien = Alien(self)  # used for calculations, NOT part of fleet
        # <Alien sprite(in 0 groups)>

        # Get dimensions for ship & alien
        ship_height = self.ship.rect.height
        alien_width, alien_height = alien.rect.size  # (60, 58)

        # find available space for aliens to fit on screen
        available_space_y = (self.settings.screen_height - (3 * alien_height) -
                             ship_height)
        available_space_x = self.settings.screen_width - (2 * alien_width)
        # available_space_y = (800) - (3 * 58) - 48    = 578
        # available_space_x = 1200 - (2 * 60)    = 1080

        # determine total number of aliens per row & total number of rows
        number_aliens_x = available_space_x // (2 * alien_width)
        number_rows = available_space_y // (2 * alien_height)
        # number_aliens_x = 1080 // (2 * 60)   = 9
        # number_rows = 578 // (2 * 58)  = 4

        # Create rows of aliens
        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                # Fill row with aliens
                self._create_alien(alien_number, row_number)

        # rect = <rect(x, y, width, height)>       <rect(180, 58, 60, 58)>
    def _create_alien(self, alien_number, row_number):
        alien = Alien(self)
        alien_width, height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        # alien.x = 60 + (2 * 60 * 0..9)   alien.x = 60.0, 180.0, 300.0, 420.0, ...
        alien.rect.x = alien.x
        # Each alien row starts below at twice the height of an alien ship
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        # alien.rect.y =   58 + (2 * 58 * 0..4)                     58, 174, 290
        self.aliens.add(alien)

    def _check_fleet_edges(self):
        """ Determine if fleet hits edge of screen and respond  """
        for alien in self.aliens.sprites():
            #  if self.rect.right >= screen_rect.right or self.rect.left <= 0:
            if alien.check_edges():
                print("alien.rect BEFORE",
                      alien.rect)  # rect = <rect(x, y, width, height)>
                print("direction BEFORE ", self.settings.fleet_direction)
                self._change_fleet_direction()
                print("direction AFTER ", self.settings.fleet_direction)
                print("Change in y is ", alien.rect.y)
                break

    def _change_fleet_direction(self):
        """ Drop the entire fleet and change direction """
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _check_aliens_bottom(self):
        """ Verify if aliends reach bottom od screen """
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                self._ship_hit()
                break

    def _update_screen(self):
        """ Update images """
        # Redraw screen during each pass through the loop
        # a surface obj is created via self.screen
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()

        # call draw method to render alien
        self.aliens.draw(self.screen)

        # Draw scoreboard info
        self.sb.show_score()

        # Draw the play button if the game is inactive
        if not self.stats.game_active:
            self.play_button.draw_button()


# for blast in self.laser.sprites():
#     blast.draw_laser()

# make most recent screen drawn visible
# updates entire display
        pygame.display.flip()
コード例 #52
0
menu_button_style = {
    "font_kwargs": {
        "font_name": "verdana",
        "font_size": 26
    },
    "border_width": 2,
    "margins": (5, ) * 4
}

menu_screen = View(children=[
    GridView(
        [[Text(2, 3, text="Arithma", **menu_h1_style)],
         [
             Button(2,
                    2,
                    text="Levels",
                    on_click=lambda self, event: self.run_hook(
                        "NAVIGATE_TO", "level_select"),
                    **menu_button_style)
         ],
         [
             Button(2,
                    2,
                    text="Settings",
                    on_click=lambda self, event: self.run_hook(
                        "NAVIGATE_TO", "settings"),
                    **menu_button_style)
         ],
         [
             Button(1,
                    2,
                    text="Credits",
コード例 #53
0
        if p == 1:
            win.blit(text2, (100, 350))
            win.blit(text1, (400, 350))
        else:
            win.blit(text1, (100, 350))
            win.blit(text2, (400, 350))

        for btn in btns:
            btn.draw(win)

    pygame.display.update()


btns = [
    Button("Rock", 50, 500, (0, 0, 0)),
    Button("Scissors", 250, 500, (255, 0, 0)),
    Button("Paper", 450, 500, (0, 255, 0))
]


def main():
    run = True
    clock = pygame.time.Clock()
    n = Network()
    player = int(n.getP())
    print("You are player: ", player)

    while run:
        clock.tick(60)
        try:
コード例 #54
0
class AlienInvasion:
    """Alien Invasion Class"""
    def __init__(self):
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Alien Invasion")
        self.stats = GameStates(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 run_game(self):
        """Run game"""
        while True:
            self._check_events()

            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()

            self._update_screen()

    def _check_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)

            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)

            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_play_button(self, mouse_pos):
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:
            self.stats.reset_stats()
            self.stats.game_active = True

            # Get rid of any remaining aliens and bullets
            self.aliens.empty()
            self.bullets.empty()

            # Create a new fleet and center the ship
            self._create_fleet()
            self.ship.center_ship()

            pygame.mouse.set_visible = False

    def _update_screen(self):
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.aliens.draw(self.screen)

        if not self.stats.game_active:
            self.play_button.draw_button()

        pygame.display.flip()

    def _check_keydown_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()

    def _check_keyup_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False

    def _fire_bullet(self):
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _update_bullets(self):
        self.bullets.update()

        # Get rid of bullets that have disappeared
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)

        self._check_bullet_alien_collisions()

    def _check_bullet_alien_collisions(self):
        # Check for any bullets that have hit aliens
        # If so, get rid of the bullet and the alien
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens,
                                                True, True)

        if collisions:
            pass

        if not self.aliens:
            # Destory existing bullets and create new fleet
            self.bullets.empty()
            self._create_fleet()

    def _create_fleet(self):
        # Create an alien and find the number of aliens in a row.
        # Spacing between each alien is equal to one alien width.
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)

        # Determine the number of rows of aliens that fit on the screen
        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height - (3 * alien_height) -
                             ship_height)
        number_rows = available_space_y // (2 * alien_height)

        # Crate the full fleet of aliens
        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                self._create_alien(alien_number, row_number)

    def _create_alien(self, alien_number, row_number):
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien_height + 2 * alien_height * row_number
        self.aliens.add(alien)

    def _update_aliens(self):
        self._check_fleet_edges()
        self.aliens.update()

        # Look for alien-ship collisions
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()

        self._check_aliens_bottom()

    def _check_fleet_edges(self):
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _ship_hit(self):
        if self.stats.ship_left > 0:
            self.stats.ship_left -= 1

            self.aliens.empty()
            self.bullets.empty()

            self._create_fleet()
            self.ship.center_ship()

            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible = True

    def _check_aliens_bottom(self):
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                self._ship_hit()
                break
コード例 #55
0
class AlienInvasion:
	"""Overall class to manage game assets and behavior."""

	def __init__(self):
		"""Initialize the game, and create game resources."""
		pygame.init()
		self.settings = Settings()
		
		self.screen = pygame.display.set_mode(
			(self.settings.screen_width, self.settings.screen_height))
		#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
		pygame.display.set_caption("14-3. Challenging Target Practice")

		# Create an instance to store game statistics.
		self.stats = GameStats(self)

		self.ship = Ship(self)
		self.bullets = pygame.sprite.Group()
		self.rectangles = pygame.sprite.Group()

		self._create_rectangle()

		# Make the Play button.
		self.play_button_easy = Button(self, "Easy", 0)
		self.play_button_moderate = Button(self, "Moderate", 1)
		self.play_button_hard = Button(self, "Hard", 2)

	def _check_keydown_events(self, event):
		"""Respond to keypresses."""
		if event.key == pygame.K_UP:
			self.ship.moving_top = True
		elif event.key == pygame.K_DOWN:
			self.ship.moving_bottom = True
		elif event.key == pygame.K_SPACE:
			self._fire_bullet()
		elif event.key == pygame.K_q:
			sys.exit()
		
	def _check_keyup_events(self, event):
		"""Respond to key releases."""
		if event.key == pygame.K_UP:
			self.ship.moving_top = False
		elif event.key == pygame.K_DOWN:
			self.ship.moving_bottom = False

	def _fire_bullet(self):
		"""Create a new bullet and add it to the bullets group."""
		if len(self.bullets) < self.stats.bullets_left:
			new_bullet = Bullet(self)
			self.bullets.add(new_bullet)
		#elif not self.stats.game_active:
		#	self.stats.game_active = True

	def _check_events(self):
		"""Respond to keypresses and mouse events."""
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				sys.exit()
			elif event.type == pygame.KEYDOWN:
				self._check_keydown_events(event)
			elif event.type == pygame.KEYUP:
				self._check_keyup_events(event)
			elif event.type == pygame.MOUSEBUTTONDOWN:
				mouse_pos = pygame.mouse.get_pos()
				self._check_play_button(mouse_pos)

	def _check_play_button(self, mouse_pos):
		"""Start a new game when the player clicks Play."""
		button_clicked_easy = self.play_button_easy.rect.collidepoint(mouse_pos)
		button_clicked_moderate = self.play_button_moderate.rect.collidepoint(mouse_pos)
		button_clicked_hard = self.play_button_hard.rect.collidepoint(mouse_pos)

		button_clicked = button_clicked_easy or button_clicked_moderate or \
							button_clicked_hard

		if button_clicked and not self.stats.game_active:
			# Reset the game settings.
			if button_clicked_easy:
				self.settings.initialize_dynamic_settings(0)
			elif button_clicked_moderate:
				self.settings.initialize_dynamic_settings(1)
			else:
				self.settings.initialize_dynamic_settings(2)

			# Reset the game statistics.
			self.stats.reset_stats()
			self.stats.game_active = True

			# Get rid of any remaining aliens and bullets.
			#self.rectangles.empty()
			self.bullets.empty()

			# Center the ship.
			self.ship.center_ship()

			# Hide the mouse cursor.
			pygame.mouse.set_visible(False)

	def _update_bullets(self):
		"""Update position of bullets and get rid of old bullets."""
		# Update bullet positions.
		self.bullets.update()

		# Get rid of bullets that have disappeared.
		for bullet in self.bullets.copy():
			if bullet.rect.left >= self.settings.screen_width:
				self.bullets.remove(bullet)
				self.stats.bullets_left -= 1
		
		if self.stats.bullets_left == 0:
			self.stats.game_active = False
			self.bullets.empty()
			self.stats.reset_stats()
			self.rectangles.empty()
			self._create_rectangle()

			self.play_button_easy.draw_button()
			self.play_button_moderate.draw_button()
			self.play_button_hard.draw_button()
			pygame.mouse.set_visible(True)

		else:
			self._check_bullet_rectangle_collision()
	
	def _check_bullet_rectangle_collision(self):
		"""Respond to bullet-alien collisions."""
		# Remove any bullets and aliens that have collided.
		collision = pygame.sprite.groupcollide(
				self.bullets, self.rectangles, True, True)

		if not self.rectangles:
			self.bullets.empty()
			self.rectangles.empty()
			self.stats.reset_stats()
			self.ship.center_ship()

			self._create_rectangle()

			self.settings.increase_speed()

	def _update_rectangle(self):
		"""Check if the rectangle is at an edge, then update its position."""
		"""Respond appropriately if rectangle have reached an edge."""
		for rectangle in self.rectangles.sprites():
			if rectangle.check_edges():
				self._change_rectangle_direction()
			rectangle.update()
	
	def _create_rectangle(self):
		"""Create an alien and place it in the row."""
		rectangle = Rectangle(self)
		rectangle.center_rectangle()
		self.rectangles.add(rectangle)

	def check_edges(self):
		"""Return True if rectangle is at edge of screen."""
		for rectangle in self.rectangles.sprites():
			if rectangle.check_edges():
				self._change_rectangle_direction()
				break
	
	def _change_rectangle_direction(self):
		"""Drop the entire fleet and change the fleet's direction."""
		self.settings.rectangle_direction *= -1

	def _update_screen(self):
		"""Update images on the screen, and flip to the new screen."""
		self.screen.fill(self.settings.bg_color)
		self.ship.blitme()
		for bullet in self.bullets.sprites():
			bullet.draw_bullet()

		for rect in self.rectangles.sprites():
			rect.draw_rectangle()

		# Draw the play button if the game is inactive.
		if not self.stats.game_active:
			self.play_button_easy.draw_button()
			self.play_button_moderate.draw_button()
			self.play_button_hard.draw_button()

		# Make the most recently drawn screen visible.
		pygame.display.flip()

	def run_game(self):
		"""Start the main loop for the game."""
		while True:
			self._check_events()

			if self.stats.game_active:
				self.ship.update()
				self._update_bullets()
				self._update_rectangle()
			
			self._update_screen()
コード例 #56
0
ファイル: helpScreen.py プロジェクト: sw104/ReBel
    def __init__(self, win, font, frameRate):
        self.win = win
        self.font = font
        self.frameRate = frameRate

        self.width = int(self.win.get_width() * 0.8)
        self.height = int(self.win.get_height() * 0.8)

        self.x = (self.win.get_width() - self.width) / 2.0
        self.y = (self.win.get_height() - self.height) / 2.0

        self.backgroundFade = pygame.Surface((self.win.get_width(), self.win.get_height()), pygame.SRCALPHA)
        self.backgroundFade.fill((255, 255, 255, 156))

        self.helpBackground = pygame.Rect(0 + (self.win.get_width() - self.width) / 2.0, 0 + (self.win.get_height() - self.height) / 2.0, self.width, self.height)

        self.button_back = Button("Back", (self.x + 20, self.height + self.y - 20), font=self.font)
        self.button_back.rect.y -= self.button_back.rect.h
        #
        self.button_serverPage = Button("Server", (self.x + self.width - 20, self.y + 20), font=self.font)
        self.button_serverPage.rect.x -= self.button_serverPage.rect.w
        #
        self.button_ringingPage = Button("Ringing", (self.button_serverPage.x - self.button_serverPage.rect.w - 10, self.y + 20), font=self.font)
        self.button_ringingPage.rect.x -= self.button_ringingPage.rect.w
        #
        self.buttons = [self.button_back, self.button_ringingPage, self.button_serverPage]

        self.serverTitleText = TextBox('Server Help:',
                                       (self.x+20, self.y+self.button_serverPage.rect.h+20), width=self.width-40, backgroundColour=(150, 150, 150), font=self.font, fontSize='large')
        self.serverSubTitleText = TextBox('Connecting to a server:',
                                          (self.x+20, self.serverTitleText.y+self.serverTitleText.h+10), width=self.width-40, font=self.font, fontSize='small')
        self.serverText_1 = TextBox("In 'Your Name' enter your name.",
                                    (self.x+20, self.serverSubTitleText.y+self.serverSubTitleText.h+7), width=self.width-40, font=self.font, fontSize='tiny')
        self.serverText_2 = TextBox("In 'Server IP' enter the public IP of the server as told by the person running the server, or the local IP of the " + \
                                    "server if on the same network, or leave it blank if you are on the same machine as the one runnning the server.",
                                    (self.x+20, self.serverText_1.y+self.serverText_1.h+10), width=self.width-40, font=self.font, fontSize='tiny')
        self.serverText_3 = TextBox("Leave 'Server Port' as the default value if the person running the server hasn't changed it, " + \
                                    "otherwise change it to the number they give.",
                                    (self.x+20, self.serverText_2.y+self.serverText_2.h+10), width=self.width-40, font=self.font, fontSize='tiny')
        self.serverText_4 = TextBox("Once these details have been entered click 'Connect to Server'. If you are able to connect to the " + \
                                    "server successfully a 'Connected' message will appear, if not a 'Server Offline' message will appear. " +
                                    "If you can't connect make sure to check your internet connection, the server IP, and the server port.",
                                    (self.x+20, self.serverText_3.y+self.serverText_3.h+10), width=self.width-40, font=self.font, fontSize='tiny')
        self.serverText_5 = TextBox("To reconnect to a server or to connect to a new one go back to the home screen, enter in the " + \
                                    "details of the new server (or leave the original details in if reconnecting), then click 'Connect " +
                                    "to Server' and then click 'Start Ringing' like normal.",
                                    (self.x+20, self.serverText_4.y+self.serverText_4.h+10), width=self.width-40, font=self.font, fontSize='tiny')
        self.serverText = [self.serverTitleText, self.serverSubTitleText, self.serverText_1, self.serverText_2, self.serverText_3, self.serverText_4, self.serverText_5]

        self.ringingTitleText = TextBox('Ringing Help:',
                                        (self.x+20, self.y+self.button_serverPage.rect.h+20), width=self.width-40, backgroundColour=(150, 150, 150), font=self.font, fontSize='large')
        self.ringingSubTitleText_1 = TextBox('Ringing Keys:',
                                             (self.x+20, self.ringingTitleText.y+self.ringingTitleText.h+10), width=self.width-40, font=self.font, fontSize='small')
        self.ringingText_1 = TextBox("By default bells 1 and 2 are set as the ringable and are rung with the 'j' and 'f' keys.",
                                     (self.x+20, self.ringingSubTitleText_1.y+self.ringingSubTitleText_1.h+7), width=self.width-40, font=self.font, fontSize='tiny')
        self.ringingText_2 = TextBox("All the bells can be configured to be rung and can be set to use any letter or number key. The key bindings are " + \
                                     "set in the 'Options' menu found in the ringing screen.",
                                     (self.x+20, self.ringingText_1.y+self.ringingText_1.h+10), width=self.width-40, font=self.font, fontSize='tiny')
        self.ringingText_3 = TextBox("The bell you set as your first bell will be placed at the bottom of the ringing circle, just to the right of the " + \
                                     "center.",
                                     (self.x+20, self.ringingText_2.y+self.ringingText_2.h+10), width=self.width-40, font=self.font, fontSize='tiny')
        self.ringingSubTitleText_2 = TextBox('Bell Tunings and Scales:',
                                             (self.x+20, self.ringingText_3.y+self.ringingText_3.h+16), width=self.width-40, font=self.font, fontSize='small')
        self.ringingText_4 = TextBox("By default the bells are in the key of C and are generated from a size 15 handbell in C. The key of the bells can " + \
                                     "changed by shifting them by both an integer number of semitones and an integer number of octaves. Currently this " + \
                                     "can only be done by manually changing the config file.",
                                     (self.x+20, self.ringingSubTitleText_2.y+self.ringingSubTitleText_2.h+10), width=self.width-40, font=self.font, fontSize='tiny')
        self.ringingText_5 = TextBox("The bells are tuned to a major scale by default though they can also be changed to natural, harmonic, and melodic " + \
                                     "minor scales. Currently this can only be done manually changing the config file.",
                                     (self.x+20, self.ringingText_4.y+self.ringingText_4.h+10), width=self.width-40, font=self.font, fontSize='tiny')
        
        self.ringingText = [self.ringingTitleText, self.ringingSubTitleText_1, self.ringingText_1, self.ringingText_2, self.ringingText_3]#,
コード例 #57
0
ファイル: space_pew.py プロジェクト: Tepah/Space_Pew
class SpacePew:
    """Overall class to manage game assets and behavior."""

    def __init__(self):
        """Initialize the game, and game resources."""
        pygame.init()
        self.settings = Settings()

        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height)
        )
        pygame.display.set_caption("Space Pew")

        # Create an instance to store game stats and create a scoreboard
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()
        self.wind = pygame.sprite.Group()
        self.drops = pygame.sprite.Group()
        self.projectiles = pygame.sprite.Group()
        self.clock = self.settings.clock

        # Make the Play button.
        self.play_button = Button(self, "Play")

        # Make the Normal and Hard Difficulty buttons.
        self.normal_button = Button(self, "Peewee")
        self.hard_button = Button(self, "REAL PP")

    def run_game(self):
        """Start the main loop for the game."""
        while True:
            self.clock.tick(self.settings.fps)
            self._check_events()

            if self.stats.game_active:
                self.ship.update()
                self._fire_bullet()
                if self.bullets:
                    self._update_bullets()
                if self.drops:
                    self._update_drops()
                if self.projectiles:
                    self._update_projectiles()
                self._update_aliens()
                if self.settings.spawn_ship:
                    self.ship.ship_spawn()
                    self.settings.spawn_ship = False

            self._blow_wind()
            self._update_wind()
            self._update_screen()

    def _check_events(self):
        """Responds to keypresses and mouse events"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                if not self.stats.game_active \
                        and not self.stats.difficulty_menu:
                    self._check_play_button(mouse_pos)
                elif self.stats.difficulty_menu:
                    self._check_difficulty_menu(mouse_pos)

    def _check_play_button(self, mouse_pos):
        """Start a new game when a player clicks Play."""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked:
            # Shows the difficulty buttons
            self.stats.difficulty_menu = True

    def _check_difficulty_menu(self, mouse_pos):
        if self.normal_button.rect.collidepoint(mouse_pos):
            # Reset the game settings.
            self.settings.initialize_dynamic_settings()
            self._start_game()
            self.stats.difficulty_menu = False
        elif self.hard_button.rect.collidepoint(mouse_pos):
            # Starts game in HARD MODE
            self.settings.initialize_dynamic_settings()
            self.settings.hard_mode_settings()
            self._start_game()
            self.stats.difficulty_menu = False

    def _start_game(self):
        # Reset the game statistics.
        self.stats.reset_stats()
        self.stats.game_active = True

        self._clean_slate()
        self.ship.ship_spawn()

        self.sb.prep_score()
        self.sb.prep_level()
        self.sb.prep_ships()

        # Hide the mouse cursor.
        pygame.mouse.set_visible(False)

    def _check_keydown_events(self, event):
        """Responds to keypresses"""
        if event.key == pygame.K_d:
            self.ship.moving_right = True
        elif event.key == pygame.K_a:
            self.ship.moving_left = True
        elif event.key == pygame.K_w:
            self.ship.moving_up = True
        elif event.key == pygame.K_s:
            self.ship.moving_down = True
        elif event.key == pygame.K_ESCAPE:
            sys.exit()
        elif event.key == pygame.K_k:
            self._continue_shooting()
        elif event.key == pygame.K_EQUALS:
            self.settings.switch_god_bullet()
        elif event.key == pygame.K_p:
            if not self.stats.game_active:
                self._start_game()

    def _continue_shooting(self):
        if not self.ship.is_shooting:
            self.ship.is_shooting = True
        else:
            self.ship.is_shooting = False

    def _fire_bullet(self):
        """Create a new bullet and add it to the bullets group."""
        if len(self.bullets) < self.settings.bullets_allowed and \
                self.ship.is_shooting and self.settings.bullet_counter % 5 == 0:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)
        self.settings.bullet_counter += 1

    def _blow_wind(self):
        if len(self.wind) < self.settings.wind_limit and \
                self.settings.wind_counter % 200 == 0:
            new_wind = Wind(self)
            self.wind.add(new_wind)
        self.settings.wind_counter += 1

    def _check_keyup_events(self, event):
        """Responds to Key releasing"""
        if event.key == pygame.K_d:
            self.ship.moving_right = False
        elif event.key == pygame.K_a:
            self.ship.moving_left = False
        elif event.key == pygame.K_w:
            self.ship.moving_up = False
        elif event.key == pygame.K_s:
            self.ship.moving_down = False

    def _update_bullets(self):
        """Update position of bullets and get rid of old bullets."""
        # Update bullet positions.
        self.bullets.update()

        # Get rid of bullets that have disappeared.
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)

        self._check_bullet_alien_collisions()

    def _update_drops(self):
        """Update the position of the drops and get rid of old drops"""
        # update drop position
        self.drops.update()

        collided_drops = pygame.sprite.spritecollide(self.ship, self.drops, False
                                                     )

        for drop in collided_drops:
            self._check_drop(drop)

        # Get rid of drops that are gone
        for drop in self.drops.copy():
            if drop.rect.top >= self.settings.screen_height:
                self.drops.remove(drop)

    def _check_drop(self, drop):
        if drop.type == 'upgrade':
            self.ship.upgrade_bullet()
        elif drop.type == 'pierce':
            self.ship.upgrade_pierce()
        elif drop.type == 'bigger':
            self.ship.upgrade_bigger()
        elif drop.type == 'smaller':
            self.ship.upgrade_smaller()
        elif drop.type == 'more':
            self.ship.upgrade_amount()
        self.drops.remove(drop)

    def _update_projectiles(self):
        """Moves the bullets down and deletes any that fall out"""
        self.projectiles.update()

        # Deletes the projectiles that fall out of screen
        for projectile in self.projectiles.copy():
            if projectile.rect.top >= self.settings.screen_height:
                self.projectiles.remove(projectile)

        if pygame.sprite.spritecollideany(self.ship, self.projectiles):
            self._ship_hit()

    def _check_bullet_alien_collisions(self):
        # Check for any bullets that have hit aliens.
        # If so, get rid of the bullet and the alien.
        collisions = pygame.sprite.groupcollide(
            self.bullets, self.aliens, False, False)
        drop_determine = -1

        if collisions:
            for bullets, aliens in collisions.items():
                self._health_deplete(aliens, bullets, drop_determine)
            self.sb.prep_score()
            self.sb.check_high_score()

        # Checks if aliens are all dead
        if not self.aliens and self.ship.rect.y >= 600:
            self._respawn_aliens()

    def _health_deplete(self, aliens, bullets, drop_determine):
        """
        Checks if the alien health is depleted and deletes
        if health reaches 0
        """
        for alien in aliens:
            # Checks if the bullet has hit this alien before.
            if bullets.prev_alien != alien:
                if alien.health - \
                        bullets.settings.bullet_damage <= 0:
                    self.aliens.remove(alien)
                    self.stats.score += self.settings.alien_points \
                        * len(aliens)
                    drop_determine = randint(1, 100)
                else:
                    # Lowers the health if not quite at 0
                    alien.health -= \
                        bullets.settings.bullet_damage
                # Checks if bullets have pierce
                # and how many times it can pierce
                if bullets.pierce > 0:
                    bullets.pierce -= 1
                    bullets.set_pierced_alien(alien)
                else:
                    # Deletes the bullet if it hits an alien with no pierce
                    self.bullets.remove(bullets)
                if drop_determine > 0:
                    self._determine_drop(alien, drop_determine)

    def _determine_drop(self, alien, drop_determine):
        # Determines the drop rate for each item.
        if drop_determine <= 15:
            new_drop = Drops(self, alien)
            if drop_determine <= 4:
                # Drops the damage increase drop
                new_drop.upgrade_drop()
            elif drop_determine <= 6:
                # Drops the pierce increase drop
                new_drop.pierce_drop()
            elif drop_determine <= 9:
                # Drops the increasing size drop
                new_drop.bigger_drop()
            elif drop_determine <= 12:
                # Drops the decreasing size drop
                new_drop.smaller_drop()
            elif drop_determine <= 15:
                # Drop the increasing amount drop""
                new_drop.more_drop()
            self.drops.add(new_drop)

    def _respawn_aliens(self):
        """Destroy existing bul/proj/drops and create a new fleet."""
        self._clean_slate()

        # Increase level and difficulty
        self.stats.level += 1
        self.settings.increase_difficulty(self.stats.level)
        self.sb.prep_level()

    def _update_aliens(self):
        """Check if the fleet is at the edge, then
        Update the position of the aliens in the fleet"""
        self._check_fleet_edges()
        self.aliens.update()

        # Look for alien-ship collisions.
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()

        # Random variable shooter
        for alien in self.aliens:
            if len(self.projectiles) < self.settings.alien_projectile_limit:
                determine_num = randint(1, 100)
                if determine_num < 10 and\
                        self.settings.alien_projectile_counter %\
                        self.settings.alien_projectile_shoot == 0:
                    new_projectile = AlienProjectile(self, alien)
                    self.projectiles.add(new_projectile)
                self.settings.alien_projectile_counter += 1

        # Look for aliens hitting the bottom of the screen.
        self._check_alien_bottom()

    def _update_wind(self):
        """Update the position of the wind particles and gets rid of them"""
        self.wind.update()

        # Get rid of the wind that disappear
        for air in self.wind.copy():
            if air.rect.top > self.settings.screen_height:
                self.wind.remove(air)

    def _ship_hit(self):
        """Respond to the ship being hit by an alien."""

        if self.stats.ships_left > 0:
            # Decrement ships_left
            self.stats.ships_left -= 1
            self.sb.prep_ships()

            self._clean_slate()

            # Pause.
            sleep(0.5)
            self.settings.spawn_ship = True
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _create_fleet(self):
        """Create a fleet of aliens"""
        # Make an Alien.
        # Spacing between each alien is equal to one alien width.
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - \
            (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)

        # Determine the number of rows of aliens that fit on the screen.
        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height -
                             (3 * alien_height) - ship_height)
        number_rows = available_space_y // (3 * alien_height)

        # Create the full fleet of aliens.
        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                self._create_alien(alien_number, row_number)

    def _create_alien(self, alien_number, row_number):
        """Create an alien and place it in the row."""
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height \
            * row_number
        self.aliens.add(alien)

    def _check_fleet_edges(self):
        """Respond appropriately if any aliens have reached an edge."""
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _check_alien_bottom(self):
        """Check if any aliens have reached the bottom of the screen."""
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom > screen_rect.bottom:
                # Treat this the same as if the ship got hit.
                self._ship_hit()
                break

    def _change_fleet_direction(self):
        """Drop the entire fleet and change the fleet's direction."""
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _clean_slate(self):
        """Resets all aspects to reset positioning"""
        # Get rid of any remaining aliens, bullets, projectiles, and drops
        self.aliens.empty()
        self.bullets.empty()
        self.projectiles.empty()
        self.drops.empty()

        # Create a new fleet and center the ship.
        self._create_fleet()

    def _update_screen(self):
        """Update images on screen and flips to new screen"""
        self.screen.fill(self.settings.bg_color)
        for air in self.wind.sprites():
            air.draw_wind()
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        for drop in self.drops.sprites():
            drop.draw_drop()
        for projectile in self.projectiles.sprites():
            projectile.draw_projectile()
        self.aliens.draw(self.screen)

        # Draw the score information.
        self.sb.show_score()

        # Draw the play button if the game is inactive.
        if not self.stats.game_active and not self.stats.difficulty_menu:
            self.play_button.draw_play_button()
        elif self.stats.difficulty_menu and not self.stats.game_active:
            # Draws the difficulty buttons
            self.normal_button.draw_button(0, -60)
            self.hard_button.draw_button(0, 60)

        pygame.display.flip()
コード例 #58
0
pygame.display.set_caption("FastGrid: Mental Math Training")

#resources loading
bgMenu = pygame.image.load("background/menu.png")
bgMenu = pygame.transform.scale(bgMenu, (horizontal, vertical - 30))
bgStart = pygame.image.load("background/play.png")
bgStart = pygame.transform.scale(bgStart, (horizontal, vertical - 30))
pygame.mixer.init()
pygame.mixer.music.load("musica/Pressure.mp3")
pygame.mixer.music.play(-1)

# Font loading
font = pygame.font.Font("FreeSansBold.ttf", 75)

# Creating menu buttons using class "Button"
buttonStart = Button(399, 178, 534, 90)
buttonTutorial = Button(399, 320, 530, 90)
buttonOptions = Button(399, 462, 530, 90)
buttonCredits = Button(399, 605, 530, 90)

# Creating start buttons using class "Button"
buttonSomar = Button(1177, 316, 113, 89)
buttonSubtrair = Button(1177, 423, 113, 89)
buttonMultiplicar = Button(1177, 520, 113, 89)
buttonDividir = Button(1177, 618, 113, 89)
buttonLevelUpOn = Button(50, 508, 155, 46)
buttonLevelUpOff = Button(50, 554, 155, 46)

# Cria objeto para ser usado na lógica do jogo
logicNow = Logic()
コード例 #59
0
class Creator_Level_Selection:

    def __init__(self, levels, screen, screen_x, screen_y, VERBOSE, SHOW_FPS):
        self.levels = levels
        self.screen = screen
        self.screen_x = screen_x
        self.screen_y = screen_y
        self.VERBOSE = VERBOSE
        self.SHOW_FPS = SHOW_FPS

        self.creator_level_selection_screen_is_active = False

        self.pages = []
        self.selected_page = 0

        self.SUN = pygame.image.load('images/sun.png')

        self.font = pygame.font.SysFont('Comic Sans MS', 25)
        self.fps_font = pygame.font.Font('fonts/FreeSansBold.ttf', 20)

        # Generate buttons
        columns = math.floor(screen_x / 120) - 1
        rows = math.floor((screen_y - 200) / 120)
        x_left = (screen_x - ((columns * 120) - 30)) / 2
        y_top = ((screen_y - 200) - ((rows * 120) - 30)) / 2
        count = 0
        for i in range(int(math.floor(len(levels) / (columns * rows)) + 1)):
            if self.VERBOSE: print('Generating page %s') % str(i)
            page = pygame.sprite.Group()
            x = x_left
            y = y_top
            for _ in range(int(rows)):
                for _ in range(int(columns)):
                    count += 1
                    if self.VERBOSE: print('Generating selection button for level %s') % str(count)
                    if count == len(levels) + 1:
                        page.add(Button([x, y], 90, 90, 'New', 36, screen))
                        break
                    else: page.add(Button([x, y], 90, 90, str(count), 50, screen))
                    if self.VERBOSE: print('Generated selection button for level %s') % str(count)
                    x += 120
                if count == len(levels) + 1: break
                y += 120
                x = x_left
            if self.VERBOSE: print('Generated page %s') % str(i)
            self.pages.append(page)

        self.back_button = Button([(screen_x / 2) - 190, screen_y - 145], 90, 90, 'Prev', 30, screen)
        self.next_button = Button([(screen_x / 2) + 100, screen_y - 145], 90, 90, 'Next', 30, screen)

        i = 0
        s = ''
        while i < len(str(len(self.pages))):
            s += '0'
            i += 1
        self.text_size = self.font.size('%s/%s' % (s, str(len(self.pages))))
        self.text = self.font.render('%s/%s' % (str(self.selected_page + 1), len(self.pages)), True, (0, 0, 0))
        self.text_coords = ((screen_x / 2) - (self.text_size[0] / 2), (screen_y - 100) - (self.text_size[1] / 2))

    def start(self):
        self.creator_level_selection_screen_is_active = True

        if len(self.pages) == 1:
            self.back_button.disabled = True
            self.next_button.disabled = True
        elif len(self.pages) > 1: self.back_button.disabled = True

        clock = pygame.time.Clock()

        if self.VERBOSE: print('Level selection screen initialized')

        while self.creator_level_selection_screen_is_active:

            # Handle events
            for event in pygame.event.get():

                # If user quits
                if event.type == pygame.QUIT or pygame.key.get_pressed()[pygame.K_ESCAPE]:
                    if self.VERBOSE: print('Level selection canceled, returning to main menu')
                    return

            mouse_pos = pygame.mouse.get_pos()

            if self.back_button.check_click(mouse_pos[0], mouse_pos[1]):
                if self.VERBOSE: print('Switching to level selection page %s') % str(self.selected_page)
                self.selected_page -= 1
                if self.selected_page == 0: self.back_button.disabled = True
                self.next_button.disabled = False
                self.text = self.font.render('%s/%s' % (str(self.selected_page + 1), len(self.pages)), True, (0, 0, 0))

            if self.next_button.check_click(mouse_pos[0], mouse_pos[1]):
                if self.VERBOSE: print('Switching to level selection page %s') % str(self.selected_page + 2)
                self.selected_page += 1
                if self.selected_page == len(self.pages) - 1: self.next_button.disabled = True
                self.back_button.disabled = False
                self.text = self.font.render('%s/%s' % (str(self.selected_page + 1), len(self.pages)), True, (0, 0, 0))

            button = self.getClickedButton(mouse_pos)
            if button is not None:
                if button.text == 'New':
                    if self.VERBOSE: print('Creating new level')
                    return Level_Creator(self.VERBOSE, self.SHOW_FPS).start(self.screen, None, None)
                else:
                    if self.VERBOSE: print('Editing level %s') % button.text
                    selected_level = int(button.text) - 1
                    return Level_Creator(self.VERBOSE, self.SHOW_FPS).start(self.screen, self.levels[selected_level], selected_level)

            '''
            All drawing
            '''

            self.screen.fill(pygame.Color('lightblue'))
            self.screen.blit(self.SUN, (50, 50))

            for p in self.pages[self.selected_page]:
                p.draw()

            self.back_button.draw()
            self.next_button.draw()
            self.screen.blit(self.text, self.text_coords)

            if self.SHOW_FPS: self.screen.blit(self.fps_font.render(str(int(clock.get_fps())), True, pygame.Color('white'), pygame.Color('black')), (0, 0))

            pygame.display.flip()

            clock.tick(60)

    # Returns clicked button
    def getClickedButton(self, mouse_pos):
        for b in self.pages[self.selected_page]:
            if b.check_click(mouse_pos[0], mouse_pos[1]): return b
        return None
コード例 #60
0
	def createWidget(self, parent):
		return Button(parent, showHitRects=showHitRects)