Exemple #1
0
def do_button(screen, ren, where, x, y):
    ren_rect = ren.get_rect().inflate(20, 10)
    if where == "topleft":
        ren_rect.topleft = screen.get_rect().topleft
        if x != None:
            ren_rect[0] = x
        if y != None:
            ren_rect[1] = y
    if where == "midtop":
        ren_rect.midtop = screen.get_rect().midtop
        if y != None:
            ren_rect[1] = y
    if where == "topright":
        ren_rect.topright = screen.get_rect().topright
        if x != None:
            ren_rect[0] = ren_rect[0] - x
        if y != None:
            ren_rect[1] = y
    if where == None:
        if x != None:
            ren_rect[0] = x
        if y != None:
            ren_rect[1] = ren_rect[1] + y
    screen.blit(ren, ren_rect.inflate(-20, -10))
    update(ren_rect)
    return ren_rect
Exemple #2
0
def paint_screen(screen, color, *rect):
    if not rect:
        screen.fill(color)
        update()
    else:
        screen.fill(color, rect)
        update(rect)
Exemple #3
0
def main():
    rect = Rect((0, 0), SCREEN_SIZE)
    surface = Surface(SCREEN_SIZE)
    pxarray = PixelArray(surface)
    P = [(0, 100), (100, 0), (200, 0), (300, 100), (400, 200), (500, 200),
         (600, 100), (400, 400), (700, 50), (800, 200)]
    n = len(P) - 1 # n = len(P) - 1; (P[0], ... P[n])
    k = 3          # degree of curve
    m = n + k + 1  # property of b-splines: m = n + k + 1
    _t = 1 / (m - k * 2) # t between clamped ends will be evenly spaced
    # clamp ends and get the t between them
    t = k * [0] + [t_ * _t for t_ in xrange(m - (k * 2) + 1)] + [1] * k

    S = Bspline(P, t, k)
    # insert a knot (just to demonstrate the algorithm is working)
    S.insert(0.9)

    step_size = 1 / STEP_N
    for i in xrange(STEP_N):
        t_ = i * step_size
        try: x, y = S(t_)
        # if curve not defined here (t_ is out of domain): skip
        except AssertionError: continue
        x, y = int(x), int(y)
        pxarray[x][y] = (255, 0, 0)
    del pxarray

    for p in zip(S.X, S.Y): draw.circle(surface, (0, 255, 0), p, 3, 0)
    SCREEN.blit(surface, (0, 0))

    while 1:
        for ev in event.get():
            if ev.type == KEYDOWN:
                if ev.key == K_q: exit()
        display.update()
    def draw(self):
        if self.drawn is False:
            Constants.SCREEN.fill((0, 0, 0))
            game_ended = self.title_font.render(self.dis_text, 1,
                                                (255, 255, 255))
            background = pygame.Surface(Constants.SCREEN.get_size())
            game_ended_rect = game_ended.get_rect()
            game_ended_rect.center = background.get_rect().center
            Constants.SCREEN.blit(game_ended, game_ended_rect)
            # Center our 'Press any key text'
            font = pygame.font.Font(None, 30)
            presskey = font.render("Press the ESC key to quit, or (m) "
                                   "to go back to the Menu", 1,
                                   (255, 255, 255))
            background = pygame.Surface(Constants.SCREEN.get_size())
            presskeyrect = presskey.get_rect()
            presskeyrect.centerx = background.get_rect().centerx
            presskeyrect.y = Constants.HEIGHT - 40
            Constants.SCREEN.blit(presskey, presskeyrect)

            alphaSurface = pygame.Surface((Constants.WIDTH,Constants.HEIGHT)) # The custom-surface of the size of the screen.
            alphaSurface.fill((0,0,0))
            alphaSurface.set_alpha(Constants.ALPHA_SURFACE) # Set the incremented alpha-value to the custom surface.
            Constants.SCREEN.blit(alphaSurface,(0,0))

            display.update()
            self.drawn = True
        else:
            pass
Exemple #5
0
    def start_editor(self):
        glyph = self.editor_info
        glyph_rect = glyph.rect
        glyph.input(PAGES['editor'])
        glyph.update()
        editor = self.editor
        editor_rect = editor.rect
        SCREEN.blit(EDITOR_BKGSCREEN, (0, 0))
        SCREEN.blit(glyph.image, glyph_rect)
        SCREEN.blit(editor.image, editor_rect)
        editor_focus = False
        while 1:
            mouse_pos = mouse.get_pos()
            link = glyph.get_collisions(mouse_pos)
            if link: mouse.set_cursor(*HAND_CURSOR)
            else: mouse.set_cursor(*DEFAULT_CURSOR)
            for ev in event.get():
                if ev.type == MOUSEBUTTONDOWN:
                    if link: pass

                    if editor.rect.collidepoint(mouse_pos): editor_focus = True

                    else: editor_focus = False

                if ev.type == KEYDOWN:
                    if ev.key == K_ESCAPE: exit()
                    if editor_focus == True: editor.input(ev)

            cursor = editor.get_cursor()
            editor.image.fill((255, 205, 0), cursor)

            SCREEN.blit(editor.image, editor_rect)
            display.update()
Exemple #6
0
    def draw(self):
        #Animate the car until we want a 'trail' of fire
        if self.steps * self.speed <= Constants.WIDTH:
            Constants.SCREEN.fill((0, 0, 0))
            #Center our 'Press any key text'
            font = pygame.font.Font(None, 30)
            presskey = font.render("Press any key to continue to the Menu", 1,
                                   (255, 255, 255))
            background = pygame.Surface(Constants.SCREEN.get_size())
            presskeyrect = presskey.get_rect()
            presskeyrect.centerx = background.get_rect().centerx
            presskeyrect.y = Constants.HEIGHT - 40
            Constants.SCREEN.blit(presskey, presskeyrect)
        #Move the car until it's off the screen
        if self.rect.left <= Constants.WIDTH:
            self.rect.midright = (self.steps * self.speed, Constants.HEIGHT
                                  / 2)
            Constants.SCREEN.blit(self.image, self.rect)
        #Once it's off the screen, show our ActionRPM text
        else:
            label = self.font.render("ActionRPM", 1, (0, 0, 0))
            Constants.SCREEN.blit(label, (Constants.WIDTH / 3.5,
                                          Constants.HEIGHT / 3))

        alphaSurface = pygame.Surface((Constants.WIDTH,Constants.HEIGHT)) # The custom-surface of the size of the screen.
        alphaSurface.fill((0,0,0))
        alphaSurface.set_alpha(Constants.ALPHA_SURFACE) # Set the incremented alpha-value to the custom surface.
        Constants.SCREEN.blit(alphaSurface,(0,0))

        display.update()
 def __draw(self):
    
    self.__gen.draw(self.__canvas)
    
    
    if self.__mouseDown:
       diffX = self.__mouseCurrPos[0] - self.__mouseDownPos[0] 
       diffY = self.__mouseCurrPos[1] - self.__mouseDownPos[1]
       
       if diffX > 0 and diffY > 0:
          sizeX = max([diffX, diffY])
          sizeY = sizeX
       elif diffX > 0:
          sizeX = max([abs(diffX), abs(diffY)])
          sizeY = -sizeX
       elif diffY > 0:
          sizeY = max([abs(diffX), abs(diffY)])
          sizeX = -sizeY
       else:
          sizeX = min([diffX, diffY])
          sizeY = sizeX
       
          
       self.__drawSize = (sizeX, sizeY)
       
       pygame.draw.rect(self.__canvas, self.__highlightColor,
                        Rect(self.__mouseDownPos, self.__drawSize), 1)
    
    
    display.flip()
    display.update()
Exemple #8
0
def view_filter(screen):
    paint_screen(screen, gl.BLACK)
    show_message(screen, "Current filter", "top", 20, ("underline", "bold"))
    show_message(screen, "Imgv will only display files whose filenames:", (5, 30), 15, ("bold"))
    line = 60
    for k in gl.FILTER_COMMAND.keys():
        font = pygame.font.Font(gl.FONT_NAME, 12)
        if k == "startwith":
            ren = font.render("Start with: %s" % gl.FILTER_COMMAND["startwith"], 1, (255, 255, 255), (0, 0, 0))
        if k == "notstartwith":
            ren = font.render("Do not start with:  %s" % gl.FILTER_COMMAND["notstartwith"], 1, (255, 255, 255), (0, 0, 0))
        if k == "endwith":
            ren = font.render("End with:  %s" % gl.FILTER_COMMAND["endwith"], 1, (255, 255, 255), (0, 0, 0))
        if k == "notendwith":
            ren = font.render("Do not end with:  %s" % gl.FILTER_COMMAND["notendwith"], 1, (255, 255, 255), (0, 0, 0))
        if k == "contain":
            ren = font.render("Contain:  %s" % gl.FILTER_COMMAND["contain"], 1, (255, 255, 255), (0, 0, 0))
        if k == "notcontain":
            ren = font.render("Do not contain:  %s" % gl.FILTER_COMMAND["notcontain"], 1, (255, 255, 255), (0, 0, 0))
        ren_rect = ren.get_rect()
        ren_rect[0] = 5
        ren_rect[1] = line
        screen.blit(ren, ren_rect)
        line = line + 30
        update(ren_rect)
    while 1:
        ev = pygame.event.wait()
        check_quit(ev)
        if ev.type == KEYDOWN or ev.type == MOUSEBUTTONDOWN:
            return
Exemple #9
0
def square_four(screen, file):
    wait_cursor()
    draw_lines(screen)
    num_imgs = len(gl.files)
    if file >= num_imgs or file <= 0:
        file = 0
    img_four_name = gl.files[file]
    img_four_file = file
    img_four = load_img(img_four_name, screen, 0)
    file = file + 1
    img_four = adjust_img_size(img_four, screen.get_width(), screen.get_height())
    img_four_rect = img_four.get_rect()
    img_four_rect[0] = (screen.get_width() / 2)
    img_four_rect[1] = (screen.get_height() / 2)
    screen.blit(img_four, img_four_rect)
    update(img_four_rect)
    draw_lines(screen)
    if gl.FOUR_STATUS_BARS:
        font_size = 9
        font = pygame.font.Font(gl.FONT_NAME, font_size)
        name = os.path.basename(img_four_name)
        name = check_truncate(screen.get_width(), name)
        img_status = "%s [%d/%d]" % (name, img_four_file + 1, num_imgs)
        raise_up = 12
        show_message(screen, img_status, ((screen.get_width() / 2) + (screen.get_width() / 4 - font.size(img_status)[0]/2), screen.get_height() - raise_up), font_size, ("bold"))
    normal_cursor()
    return (file, img_four_rect, img_four_name, img_four_file)
    def _display_with_pygame(self, imagefile):
        try:
            t1 = time.time()
            # Clear the screen
            self._blank_screen()
            logging.debug('Time: {0}'.format(time.time() - t1))
            img = image.load(imagefile)
#            img = pygame.image.load(imagefile).convert()
            logging.debug(time.time() - t1)
            img, offset_x, offset_y = self.scale_image(img)
            logging.debug(time.time() - t1)
            self._screen.blit(img, (offset_x, offset_y))
            logging.debug(time.time() - t1)

            # update the display
            display.update()
            logging.debug('Time image displayed: {0}'.format(time.time() - t1))
            ''' fadeIn? from black '''
            # pygame.display.flip()
            # pause
            pygame_time.wait(self._image_display_time * 1000)

            # time.sleep(self._image_display_time)
            ''' fadeOut? to black '''

        except Exception, e:
            logging.error('Error: ' + str(e))
Exemple #11
0
def absorb(attack, defend, move, me):
    """
    function
    """
    if move.name == 'Dream Eater':
        if 'SLP' not in defend.buffs:
            display.update(write_btm('but it failed!'))
            sleep(1)
            return 0
    crit, type_, dmg = attack.calc_dmg(defend, move)
    if crit:
        display.update(write_btm('Critical Hit!'))
        sleep(1)
    if type_ > 1:
        display.update(write_btm("It's Super Effective!"))
        sleep(1)
    elif 0 < type_ < 1:
        display.update(write_btm("It wasn't", "very effective!"))
        sleep(1)
    elif type_ == 0:
        display.update(write_btm("It had no effect"))
        sleep(1)
    retval = dmg_pkmn(defend, dmg, me)
    if retval:
        meth = getattr(
            pokepong.move_sandbox, 'do_' + move.name.lower().replace(' ', '_').replace('-', '_'))
        meth(attack, defend, me)
    dmg_pkmn(attack, int(floor(dmg / 2) * -1), not me)
    return retval
Exemple #12
0
def print_version(screen, screen_height):
    imgvlogo = load_img(gl.IMGV_LOGO_SMALL, screen, False)
    imgvlogo_rect = imgvlogo.get_rect()
    imgvlogo_rect[0] = 5
    imgvlogo_rect[1] = screen_height - 50
    screen.blit(imgvlogo, imgvlogo_rect)
    update(imgvlogo_rect)

    msg = "Version      %s" % gl.IMGV_VERSION
    msg_font = pygame.font.Font(gl.FONT_NAME, 11)
    msg_font.set_bold(1)
    char = 0
    i = 0
    pygame.event.set_blocked(MOUSEMOTION)
    while 1:
        event = pygame.event.poll()
        pygame.time.wait(1)
        check_quit(event)
        if char < len(msg):
            if msg[char] != ' ': # don't delay on spaces
                pygame.time.delay(75)
            ren = msg_font.render(msg[char], 1, gl.RED) # one char at a time
            ren_rect = ren.get_rect()
            # center it
            ren_rect[0] += (i + 7)
            ren_rect[1] = screen_height - 15
            screen.blit(ren, ren_rect)
            i += ren.get_width() # make letters space evenly
            char += 1
            update(ren_rect)
        else:
            break
    def draw(self):
        if self.timer >= GameIntro.delay:
            self.timer = 0
            if self.current_display == 2:
                # Constants.Levels = []
                # Constants.Levels.append(None)
                # Constants.Levels.append(None)
                # Constants.Levels[0] = Level_1.Level_1()
                Constants.PLAY = Play()
                Constants.STATE = Constants.PLAY
                #Constants.STATE = Play()
                Constants.STATE.set_level(0)
            else:
                self.current_display += 1
                Constants.SCREEN.fill(pygame.Color("black"))
                Constants.SCREEN.blit(GameIntro.images[self.current_display],
                                      self.rect)

                alphaSurface = pygame.Surface((Constants.WIDTH,Constants.HEIGHT)) # The custom-surface of the size of the screen.
                alphaSurface.fill((0,0,0))
                alphaSurface.set_alpha(Constants.ALPHA_SURFACE) # Set the incremented alpha-value to the custom surface.
                Constants.SCREEN.blit(alphaSurface,(0,0))
                
                display.update()
        else:
            pass
Exemple #14
0
 def draw(self):
     Constants.SCREEN.fill((0, 0, 0))
     Constants.SCREEN.blit(Volume.image,
                           Volume.image.get_rect(center=(Constants.WIDTH / 2, Constants.HEIGHT / 2)))
     Constants.SCREEN.blit(self.text, self.text_rect)
     Constants.SCREEN.blit(self.speedometer.image, self.speedometer.rect)
     display.update()
Exemple #15
0
def recoil(attack, defend, move, me):
    """
    function
    """
    crit, type_, dmg = attack.calc_dmg(defend, move)
    ret1 = dmg_pkmn(defend, dmg, me)
    if dmg:
        meth = getattr(
            pokepong.move_sandbox, 'do_' + move.name.lower().replace(' ', '_').replace('-', '_'))
        meth(attack, defend, me)
    if crit:
        display.update(write_btm('Critical Hit!'))
        sleep(1)
    if type_ > 1:
        display.update(write_btm("It's Super Effective!"))
        sleep(1)
    elif 0 < type_ < 1:
        display.update(write_btm("It wasn't", "very effective!"))
        sleep(1)
    elif type_ == 0:
        display.update(write_btm("It had no effect"))
        sleep(1)
    ret2 = dmg_pkmn(attack, dmg / 4, not me)
    if ret2:
        display.update(write_btm(attack.name + ' was', 'hit with recoil!'))
    if ret1 and ret2:
        return 3
    elif ret1:
        return 1
    elif ret2:
        return 2
    else:
        return 0
Exemple #16
0
def dmg_pkmn(pkmn, dmg, me):
    """
    function
    """
    if pkmn.substitute == 0:
        if pkmn.bide:
            pkmn.bidedmg += dmg * 2
        if dmg > 0:
            for d in range(dmg):
                if pkmn.hp <= 0:
                    return 1
                pkmn.sethp(pkmn.hp - 1)
                if not me:
                    display.update(draw_my_hp(pkmn))
                else:
                    display.update(draw_opp_hp(pkmn))
                sleep(.02)
        else:
            for d in range(0, dmg, -1):
                if pkmn.maxhp == pkmn.hp:
                    break
                pkmn.sethp(pkmn.hp + 1)
                if not me:
                    display.update(draw_my_hp(pkmn))
                else:
                    display.update(draw_opp_hp(pkmn))
                sleep(.02)

        return 0
    else:
        pkmn.substitute -= dmg
        if pkmn.substitute < 1:
            pkmn.substitute = 0
            display.update(write_btm('The substitute broke'))
            sleep(1)
Exemple #17
0
def update_display(update_queue):
    """(deque) -> NoneType
    Updates the display with Rect's given in update_queue, and clears update_queue. Specifically, for each such Rect,
    updates the display/screen only within that Rect."""
    display.update(update_queue)

    update_queue.clear()
Exemple #18
0
    def draw(self):
        """Draw all of the objects to the screen."""

        # Update all scene layers to the screen.
        self.all.update()
        self.dirty_rects = self.all.draw(self.screen)
        display.update(self.dirty_rects)
Exemple #19
0
def do_view_tagged(screen, num_imgs, file):
    "show all tagged dir names"
    paint_screen(screen, gl.BLACK)
    (esc_rect, close_font) = close_button(screen)
    line = 5
    if len(gl.MULT_DIRS) == 0:
        show_message(screen, "[No directories are currently tagged]", "bottom", 12)
    for d in gl.MULT_DIRS:
        font = pygame.font.Font(gl.FONT_NAME, 9)
        ren = font.render(d, 1, (255, 255, 255), (0, 0, 0))
        ren_rect = ren.get_rect()
        ren_rect[0] = 5
        ren_rect[1] = line
        screen.blit(ren, ren_rect)
        line = line + 12
        update(ren_rect)
    pygame.event.set_allowed(MOUSEMOTION)
    while 1:
        ev = pygame.event.wait()
        check_quit(ev)
        hover_cursor(pygame.mouse.get_pos(), (esc_rect,))
        if ev.type == KEYDOWN and ev.key not in (K_LALT, K_RALT, K_TAB, K_LCTRL, K_RCTRL) or ev.type == MOUSEBUTTONDOWN:
            gl.ADDED_DIR_NUMS = 0
            (num_imgs, file) = show_dirs(screen, num_imgs, file)
            break # break event loop
Exemple #20
0
    def run(self):
        running = True
        while running:
            new_time = PT.get_ticks()
            frame_time = (new_time - self.current_time)/1000.0
            self.current_time = new_time
            self.clock.tick()

            running = self.handleEvents()
            if(running == False):
                return False
            #Key Handling----------------------------
            # self.character.handle_keys() # handle the keys

            self.screen.fill((0,0,0)) # fill the screen with white

            # self.character.handle_collision(self.block_group)

            #move and draw the enemies
            player_face = self.character.get_face()
            for enemy in self.enemy_list.sprites():
                Enemy_face = enemy.get_face()
                enemy.set_face(player_face)
                enemy.draw()

            #draw blocks
            Draw.draw_map(self.block_group)

            self.character.draw(self.screen, self.block_group) # draw the character to the screen

            PD.flip()

            self.updates = 0

            #clock is added
            clock = PT.Clock()

            while frame_time > 0.0:
                delta = min(frame_time, self.interval)
                for enemy in self.enemy_list.sprites():
                    enemy.update(delta)
                self.character.handle_keys(self.block_group, self.interval)
                frame_time -= delta
                self.updates += 1

                last = PT.get_ticks()

                clock.tick()

                PD.flip()

                elapsed = (PT.get_ticks() - last) / 1000.0
                if (PG.key.get_pressed()):
                    self.update(self.character, elapsed)

            #camera handling
            self.cam.update(self.character)
            #end camera handle
            
            PD.update() # update the screen
Exemple #21
0
 def draw(self):
     screen.fill(color_black)
     draw.rect(screen, color_white, [[0,0],[int(screen.get_width()),int(screen.get_height()*.9)]])
     self.target.draw()
     self.player.draw()
     for ball in self.balls:
         ball.draw()
     display.update([[0,0],[int(screen.get_width()),int(screen.get_height()*.9)]])
Exemple #22
0
    def draw(self):
        """Run the update method of every sprite, keeping track of which ones
            are dirty and need updating, and then finally updating only the
            dirty areas."""

        self.layers.update()
        State.dirty = self.layers.draw(State.window)
        display.update(State.dirty)
Exemple #23
0
def change_box(screen, positions):
    change_img = load_img(gl.CHANGE_BOX, False)
    change_rect = change_img.get_rect()
    change_rect[0] = positions[1]
    change_rect[1] = positions[0]
    screen.blit(change_img, change_rect)
    update(change_rect)
    return change_rect
Exemple #24
0
def paint_screen(color, *rect):
    screen = get_surface()
    if not rect:
        screen.fill(color)
        update()
    else:
        screen.fill(color, rect)
        update(rect)
Exemple #25
0
 def message(self, qw, text):
     "Display entered text."
     frect = ((self.irect[0][0] + qw, self.irect[0][1]),
              (self.irect[1][0] - qw, self.irect[1][1]))
     draw.rect(self.screen, self.boxc, frect)
     if text:
         self.blitfont(text, (self.fontupleft[0] + qw, self.fontupleft[1])) 
     display.update(self.irect)
    def draw(self):
        if self.drawn is False:
            Constants.SCREEN.fill((0, 0, 0))
            high_title = self.title_font.render("Your High Scores", 1,
                                                (255, 255, 255))
            background = pygame.Surface(Constants.SCREEN.get_size())
            high_title_rect = high_title.get_rect()
            high_title_rect.centerx = background.get_rect().centerx
            high_title_rect.centery = 75
            Constants.SCREEN.blit(high_title, high_title_rect)
            # Center our 'Press any key text'
            font = pygame.font.Font(None, 30)
            presskey = font.render("Press any key to get back to the Menu, "
                                   "or the ESC key to quit", 1,
                                   (255, 255, 255))
            background = pygame.Surface(Constants.SCREEN.get_size())
            presskeyrect = presskey.get_rect()
            presskeyrect.centerx = background.get_rect().centerx
            presskeyrect.y = Constants.HEIGHT - 40
            Constants.SCREEN.blit(presskey, presskeyrect)

            if len(self.scores) == 0:
                score = self.score_font.render("No high scores yet!", 1,
                                               (255, 255, 255))
                score_rect = score.get_rect()
                score_rect.centerx = background.get_rect().centerx
                score_rect.y = high_title_rect.bottom + 100
                Constants.SCREEN.blit(score, score_rect)
            else:
                rect_top = high_title_rect.bottom + Constants.HEIGHT / 100
                rect_left = high_title_rect.left + Constants.WIDTH / 40
                for i in range(len(self.scores)):
                    color = (255, 0, 0)
                    curr_name = self.scores[i][0]
                    curr_score = self.scores[i][1]
                    if (self.from_new):
                        if (self.name == curr_name):
                            if (abs(self.score - curr_score) < .01):
                                color = (0, 255, 0)
                    curr_score = self.score_font.render(
                        str(i + 1) + ". " + self.scores[i][0] + ": " +
                        "%3.0f" % self.scores[i][1], 1, color)
                    curr_score_rect = curr_score.get_rect()
                    curr_score_rect.left = rect_left
                    curr_score_rect.top = rect_top
                    Constants.SCREEN.blit(curr_score, curr_score_rect)
                    rect_top += Constants.WIDTH / 20

            alphaSurface = pygame.Surface((Constants.WIDTH,Constants.HEIGHT)) # The custom-surface of the size of the screen.
            alphaSurface.fill((0,0,0))
            alphaSurface.set_alpha(Constants.ALPHA_SURFACE) # Set the incremented alpha-value to the custom surface.
            Constants.SCREEN.blit(alphaSurface,(0,0))

            display.update()
            self.drawn = True
        else:
            pass
Exemple #27
0
	def loop(self,FPS):
		while True:
			if (self.playerEvent() == 'QUIT'):
				quit()
				sys.exit()
			self.update()
			self.draw()
			display.update()
			self.fpsClock.tick(FPS)
Exemple #28
0
    def update(self, fps, time):
        #print("GC:", "update called")
        self.display.fill(self.config.background.color)
        self.info_y = 10

        self._draw()

        self._render_info("fps: {}".format(fps))
        pdis.update()
Exemple #29
0
 def show_current_image(self, file):
     self.current = load_img(gl.files[file], self.screen, False)
     (self.current, img_width, img_height) = preview_img(self.screen, self.current)
     current_rect = self.current.get_rect()
     current_rect[0] = 15
     current_rect[1] = self.prev_pic_row
     self.screen.blit(self.current, current_rect)
     update(current_rect)
     img_border(self.screen, img_width, img_height, 15, self.prev_pic_row - 2)
Exemple #30
0
def draw_lines(screen):
    "Draw the lines that split the screen into 4 squares"
    screen_width = screen.get_width()
    screen_height = screen.get_height()
    line_color = gl.FOUR_DIV_COLOR 
    vline = pygame.draw.line(screen, line_color, ((screen_width / 2), screen_height), ((screen_width / 2), 0), 1)
    hline = pygame.draw.line(screen, line_color, (0, (screen_height / 2)), (screen_width, (screen_height / 2)), 1)
    update(vline)
    update(hline)
Exemple #31
0
def PlayerCrash(background_game1, background_move1, background_game2,
                background_move2, player, enemies, siren, x, y):
    music.stop()
    crash = True
    coin_animation = 0
    sfxCrash.play()
    while crash:
        CLOCK.tick(8)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
        SCREEN.blit(background_game1, background_move1)
        player.draw(SCREEN)
        enemies.draw(SCREEN)
        SCREEN.blit(
            load(join(f_vfx,
                      f'explosion_{coin_animation}.png')).convert_alpha(),
            (x - 30, y - 9))
        SCREEN.blit(background_game2, background_move2)
        siren.draw(SCREEN)
        SCREEN.blit(imgCrash, (0, 0))
        SCREEN.blit(bgArcadeGameOver, (0, 0))
        display.update()
        coin_animation += 1
        if coin_animation == 7:
            crash = False
    player.draw(SCREEN)
    enemies.draw(SCREEN)
    SCREEN.blit(
        load(join(f_vfx, 'explosion_3.png')).convert_alpha(), (x - 30, y - 9))
    SCREEN.blit(background_game2, background_move2)
    siren.draw(SCREEN)
    SCREEN.blit(imgCrash, (0, 0))
    SCREEN.blit(bgArcadeLose, (0, 0))
    display.update()
    sleep(1)
Exemple #32
0
    def run(self, run_tutorial):
        # comment out this line to remove the tutorial

        if run_tutorial == 1:
            self._tutorial.begin_tutorial(self._screen)

        self.spawn()
        while not self._done:
            time.Clock().tick(FPS)  # setting fps not sure if it works tho
            if self._initiate_countdown:  # activate pre level screen
                self._load_pre_level_screen()
                self._initiate_countdown = False
            for e in event.get():
                if e.type == QUIT:  # user closes application
                    exit()
                elif e.type == KEYDOWN and e.key == K_TAB:
                    # will eventually be moved
                    self._access_pause_screen()
                elif e.type == KEYDOWN and e.key == K_m and self._room_manager.is_room_cleared(
                ):
                    self._done = self._room_manager.render_map(
                        self._screen, False, 0, True)
                    self._player_manager.player._data.pos.update(
                        WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2)
                    self._newRoom = True
                    self._items_dropped = False
                    self._drop_manager.clearHearts()
                    time.wait(200)
                elif e.type == KEYDOWN and e.key == K_e and self._room_manager.get_proximity(
                ):
                    self._screen.fill("BLACK")

                    upgradeChooser = random.choices([1, 2, 3],
                                                    weights=[0.33, 0.33, 0.33],
                                                    k=1)[0]

                    if upgradeChooser == 1:
                        self._player_manager._player._data._attack_speed -= 2
                        self._treasure_screen.update_treasure_screen(
                            self._screen,
                            "+2 to Attack Speed! Press any Key to Continue")

                    elif upgradeChooser == 2:
                        self._player_manager.player._data._max_health += 1
                        self._player_manager.player._data._health += 1
                        self._treasure_screen.update_treasure_screen(
                            self._screen,
                            "+1 to Health! Press any Key to Continue")

                    elif upgradeChooser == 3:
                        self._player_manager.player._data._vel += 1
                        self._treasure_screen.update_treasure_screen(
                            self._screen,
                            "+1 to Velocity! Press any Key to Continue")

                    display.flip()
                    display.update()
                    z = True
                    while z:
                        for e in event.get():
                            if e.type == KEYDOWN:
                                self._room_manager.set_cleared()
                                self._items_dropped = True
                                z = False

            self.update()
            self.draw(True)
Exemple #33
0
 def clear(self):
     """ Erase the window contents """
     self.__surface__.fill(self.__bg_color__)
     if self.__auto_update__:
         update()
Exemple #34
0
    def update(self):
        ###(variables)####
        trap_attack_player = False  # tells if a trap attacked
        trap_attack_enemy = False
        projectile_attack_player = False  # tells if a projectile attacked
        projectile_attack_enemy = False
        enemy_attacked = None
        self.enemy_ID = -1

        ###(attacks on player)####
        ##trap handling
        for trap in self.trap_group.sprites():
            if (trap.get_trap_attack_player()
                    and Globals.INVINCIBILITY_COUNT == 0):
                trap_attack_player = True
            if (trap.get_trap_attack_enemy()):
                enemies_attacked = trap.get_enemies_attacked()
                if enemies_attacked is not None:
                    for enemy in enemies_attacked:
                        enemy.decrement_health(1)
            if trap.will_remove():
                self.trap_group.remove(trap)
        ##icecream attacks
        for icecream in self.icecream_list.sprites():
            #see if the enemy will release weapon/attack
            if (icecream.will_attack(self.level)):
                #get a new puddle sprite
                #sending level through to tell it to make a puddle
                #with a longer life
                new_trap = icecream.attack(self.map.get_surface(), self.level)
                #add the new trap to the list of traps
                self.trap_group.add(new_trap)

            if (icecream.get_attacked_player() or trap_attack_player):
                if trap_attack_player:
                    trap_attack_player = False
                #if so start invincibility count after attack
                if Globals.INVINCIBILITY_COUNT == 0:
                    Globals.INVINCIBILITY_COUNT = self.INVINCIBILITY_TIME
                #see which enemy attacked the player
                self.enemy_ID = icecream.get_ID()

        #lettuce
        ##projectile handling
        for projectile in self.projectile_group.sprites():
            if (projectile.attacked_player
                    and Globals.INVINCIBILITY_COUNT == 0):
                projectile_attack_player = True
                projectile.attacked_player = False
                break
            if (projectile.projectile_attack_enemy):

                enemies_attacked = projectile.get_enemies_attacked()
                if enemies_attacked is not None:
                    for enemy in enemies_attacked:
                        enemy.decrement_health(1)
            # if projectile.will_remove():
            #     self.projectile_group.remove(projectile)
        ##lettuce attacks
        for lettuce in self.lettuce_list.sprites():
            #see if the enemy will release weapon/attack
            if (lettuce.will_attack(self.level)):
                #get a new puddle sprite
                new_projectile = lettuce.attack()
                #add the new projectile to the list of projectiles
                self.projectile_group.add(new_projectile)

            if (lettuce.get_attacked_player() or projectile_attack_player):
                if projectile_attack_player:
                    projectile_attack_player = False
                #if so start invincibility count after attack
                if Globals.INVINCIBILITY_COUNT == 0:
                    Globals.INVINCIBILITY_COUNT = self.INVINCIBILITY_TIME
                #see which enemy attacked the player
                self.enemy_ID = lettuce.get_ID()

##burger attacks
        for burger in self.burger_list.sprites():
            #see if the enemy will release weapon/attack
            if (burger.will_attack(self.level)):
                #get a new puddle sprite
                new_projectile = burger.attack()
                #add the new projectile to the list of projectiles
                self.projectile_group.add(new_projectile)

            if (burger.get_attacked_player() or projectile_attack_player):
                if projectile_attack_player:
                    projectile_attack_player = False
                #if so start invincibility count after attack
                if Globals.INVINCIBILITY_COUNT == 0:
                    Globals.INVINCIBILITY_COUNT = self.INVINCIBILITY_TIME
                #see which enemy attacked the player
                self.enemy_ID = burger.get_ID()

##egg attacks
        for egg in self.egg_list.sprites():
            if (egg.get_attacked_player()):
                if Globals.INVINCIBILITY_COUNT == 0:
                    Globals.INVINCIBILITY_COUNT = self.INVINCIBILITY_TIME
                #see which enemy attacked the player
                self.enemy_ID = egg.get_ID()

        ##cupcake attacks
        for cupcake in self.cupcake_list.sprites():
            #see if the enemy will release weapon/attack
            if cupcake.will_attack(self.level):
                #get a new puddle sprite
                new_projectile = cupcake.attack()
                #add the new projectile to the list of projectiles
                self.projectile_group.add(new_projectile)

            if (cupcake.get_attacked_player() or projectile_attack_player):
                if projectile_attack_player:
                    projectile_attack_player = False
                #if so start invincibility count after attack
                if Globals.INVINCIBILITY_COUNT == 0:
                    Globals.INVINCIBILITY_COUNT = self.INVINCIBILITY_TIME
                #see which enemy attacked the player
                self.enemy_ID = cupcake.get_ID()

        self.burn_player = False
        ######Pad damage here
        for pad in self.pad_list.sprites():
            if pad.rect.colliderect(self.character.rect):
                #DEPENDING ON PAD TYPE, CALL DIFFERENT PAD METHODS
                if pad.type == 0:
                    # pad.i_am_hot(self.character)
                    self.burn_player = pad.will_burn()
                    if self.burn_player and Globals.INVINCIBILITY_COUNT == 0:
                        Globals.INVINCIBILITY_COUNT = self.INVINCIBILITY_TIME
                elif pad.type == 1:
                    pad.i_am_cold(self.character)

        ##player damage & invincibility handling
        #If enemy attacked the player while player not invincible
        if ((self.enemy_ID != -1 or self.burn_player)
                and Globals.INVINCIBILITY_COUNT == self.INVINCIBILITY_TIME):
            self.character.decrement_health(self.enemy_ID)
            self.enemy_ID = -1
            self.burn_player = False
        #decrement invincibility count if player is in invincibility
        #handles player flashing during invincibility
        if (Globals.INVINCIBILITY_COUNT > 0):
            if (Globals.INVINCIBILITY_COUNT % 50 == 0):
                self.character.invincibility_frames()
            Globals.INVINCIBILITY_COUNT -= 1

        ###Joystick
        if self.use_joy == 'y':
            self.character.handle_joy(self.block_group, self.enemy_list,
                                      self.item_group, self.map.get_surface())
        else:
            self.character.handle_keys(self.block_group, self.enemy_list,
                                       self.item_group, self.map.get_surface())

        if self.character.chng_invincibility():
            self.INVINCIBILITY_TIME = self.character.get_invincibility()

        #get new items from the killed enemies
        new_items = self.character.get_items_of_killed()
        for item in new_items:
            if (item != None):
                self.item_group.add(item)
            #check if any of the items need to be removed (lifetime == 0)
            # if(item != None):
        for item in self.item_group.sprites():
            if item.will_remove():
                self.item_group.remove(item)

        player_traps = self.character.get_player_traps()
        for trap in player_traps:
            self.trap_group.add(trap)
            trap.set_enemy_list(self.enemy_list)
            # for traps in player_traps:
            if trap.will_remove():
                self.character.remove_player_trap(trap)

        player_projectiles = self.character.get_player_projectiles()
        for projectile in player_projectiles:
            self.projectile_group.add(projectile)
            projectile.set_enemy_list(self.enemy_list)

        #update the allsprites
        self.allsprites = PS.LayeredDirty(self.trap_group, self.pad_list,
                                          self.item_group, self.player_group,
                                          self.icecream_list, self.burger_list,
                                          self.egg_list, self.cupcake_list,
                                          self.lettuce_list,
                                          self.projectile_group)

        #cheese/door handling
        if self.character.get_modified_map():
            self.background = self.map.update_background()
            self.map_modified = False
        if self.character.banner != -1:  #make sure it doesn't redraw banner already presen t?
            self.objective.changeObj(self.character.banner)
            self.updated_obj = True  #allow banner to be drawn in draw()
            self.character.banner = -1

        #update camera's position on the map
        if self.character.update_camera():
            self.camera_background = self.camera.update(
                self.character.get_coordinates(), self.map.get_surface())

        self.allsprites.update(self.block_group, self.player_group)

        if (Locals.CHANGESTATE == "Menu"):
            PM.music.fadeout(1000)
            # Globals.SCORE = self.character.score
            return False

        PD.update()  # update the screen
 def draw(self):
     screen.fill((0, 0, 0))
     for planet in self.planets.values():
         planet.draw()
     display.update([[0, 0], [screen.get_width(), screen.get_height()]])
Exemple #36
0
def settings_loop(screen, game_clock, settings):
    def update_settings():
        data = {
            'map_size': int(map_size_dropdown.selected_option),
            'resolution':
            ast.literal_eval(resolution_dropdown.selected_option),
            'initial_hives': int(bee_hive_dropdown.selected_option),
            'initial_bees': int(bees_dropdown.selected_option),
            'flower_strat': flower_spawn_strat_dropdown.selected_option,
            'hive_strat': hive_spawn_strat_dropdown.selected_option,
            'music': music_dropdown.selected_option == 'True',
            'flower_num': int(flower_num_dropdown.selected_option)
        }
        new_settings = Settings(data)
        new_screen = display.set_mode(new_settings.frame_resolution, DOUBLEBUF)
        return 0, new_screen, new_settings

    frame_resolution = settings.frame_resolution
    game_frame_rate = settings.frame_rate

    gui_manager = UIManager(frame_resolution, main_theme)

    element_size = (150, 50)
    element_size_l = (250, 50)

    tooltip_size = (150, 25)
    tooltip_size_l = (250, 25)

    back_button = elements.UIButton(relative_rect=Rect((30, 30), (50, 50)),
                                    text='',
                                    object_id="back_button",
                                    manager=gui_manager)

    save_settings_button = elements.UIButton(relative_rect=Rect((30, 100),
                                                                (125, 50)),
                                             text="Save Settings",
                                             object_id="save_settings_button",
                                             manager=gui_manager)

    resolution_dropdown = elements.UIDropDownMenu(
        options_list=[
            '1920, 1080',
            '1536, 864',
            '1360, 768',
            '1280, 1024',
            '640, 360',
        ],
        starting_option=str(
            settings.frame_resolution)[1:len(str(settings.frame_resolution)) -
                                       1],
        relative_rect=Rect((200, 100), element_size),
        manager=gui_manager)
    resolution_tooltip = elements.UILabel(relative_rect=Rect((200, 75),
                                                             tooltip_size),
                                          text="Window Resolution",
                                          manager=gui_manager)

    map_size_dropdown = elements.UIDropDownMenu(
        options_list=['2000', '1000', '500'],
        starting_option=str(settings.map_size),
        relative_rect=Rect((200, 250), element_size),
        manager=gui_manager)
    map_size_tooltip = elements.UILabel(relative_rect=Rect((200, 225),
                                                           tooltip_size),
                                        text="Map Size",
                                        manager=gui_manager)

    music_dropdown = elements.UIDropDownMenu(
        options_list=["True", "False"],
        starting_option=str(settings.play_music),
        relative_rect=Rect((200, 400), element_size),
        manager=gui_manager)
    music_tooltip = elements.UILabel(relative_rect=Rect((200, 375),
                                                        tooltip_size),
                                     text="Play Music",
                                     manager=gui_manager)

    bee_hive_dropdown = elements.UIDropDownMenu(
        options_list=['2', '5', '10', '12', '20'],
        starting_option=str(settings.initial_hives),
        relative_rect=Rect((375, 100), element_size),
        manager=gui_manager)
    bee_hive_tooltip = elements.UILabel(relative_rect=Rect((375, 75),
                                                           tooltip_size),
                                        text="Number of Hives",
                                        manager=gui_manager)

    bees_dropdown = elements.UIDropDownMenu(
        options_list=['6', '8', '10', '12', '16', '20'],
        starting_option=str(settings.initial_bees_per_hive),
        relative_rect=Rect((375, 250), element_size),
        manager=gui_manager)
    bees_tooltip = elements.UILabel(relative_rect=Rect((375, 225),
                                                       tooltip_size),
                                    text="Initial Bees",
                                    manager=gui_manager)

    flower_spawn_strat_dropdown = elements.UIDropDownMenu(
        options_list=['normal distribution'],
        starting_option=settings.flower_spawn_strategy,
        relative_rect=Rect((550, 100), element_size_l),
        manager=gui_manager)
    flower_spawn_strat_tooltip = elements.UILabel(relative_rect=Rect(
        (550, 75), tooltip_size_l),
                                                  text="Flower Spawn Strategy",
                                                  manager=gui_manager)

    hive_spawn_strat_dropdown = elements.UIDropDownMenu(
        options_list=['default'],
        starting_option=settings.hive_spawn_strategy,
        relative_rect=Rect((550, 250), element_size_l),
        manager=gui_manager)
    hive_spawn_strat_tooltip = elements.UILabel(relative_rect=Rect(
        (550, 225), tooltip_size_l),
                                                text="Hive Spawn Strategy",
                                                manager=gui_manager)

    flower_num_dropdown = elements.UIDropDownMenu(
        options_list=['200', '300', '400', '500', '600', '700'],
        starting_option=str(settings.flower_num),
        relative_rect=Rect((550, 400), element_size_l),
        manager=gui_manager)

    music_tooltip = elements.UILabel(relative_rect=Rect((550, 375),
                                                        tooltip_size_l),
                                     text="Number of Flowers",
                                     manager=gui_manager)

    while True:
        screen.fill((219, 173, 92))
        time_delta = game_clock.tick(game_frame_rate) / 1000.0
        gui_manager.update(time_delta)
        gui_manager.draw_ui(screen)

        display.update()
        for e in event.get():
            if e.type == QUIT:
                quit()
                exit()

            if e.type == USEREVENT:
                if e.user_type == 'ui_button_pressed':
                    if e.ui_element == back_button:
                        return 0, screen, settings  # Returns back to main menu
                    elif e.ui_element == save_settings_button:
                        return update_settings()

            gui_manager.process_events(e)
Exemple #37
0
 def focus_changed(self, btn):
     self.screen.blit(self.submenu, (20, 490))
     self.screen.blit(self.bomb, (20, btn[1] + 2))
     update()
Exemple #38
0
 def draw(self):
     '''Draw the game window'''
     self.surf.fill(BLACK)
     self.locale.draw()
     self.gnome.draw()
     display.update()
def main():
    """
    The main function. The driving function for Pygame,
    and the one which pieces functions and classes together to run the program.
    """
    global primary, secondary, node_name, start
    pydisplay.init()
    pydisplay.set_caption("Create your graph")
    while True:  # will always be running
        pygame.draw.rect(screen, (192, 192, 192),
                         graph_screen)  # draw background for graph screen
        for event in pygame.event.get():
            if event.type in (QUIT, KEYDOWN):  # exit screen check
                sys.exit()

            if event.type == pygame.MOUSEBUTTONDOWN:  # button click check
                for button in buttons:  # check if a button is clicked
                    button.is_clicked(event.pos)
                mouse_pos = pymouse.get_pos()

                # adding nodes -> must be far enough away, on screen, correct mode
                if my_graph.not_within_min(
                        mouse_pos) and graph_screen.collidepoint(
                            mouse_pos) and add_node_mode == 1:
                    new_node = Node(node_name, not_selected_color, mouse_pos,
                                    0)
                    my_graph.add_node(new_node)
                    node_name += 1

                # adding edges -> a node must be selected and correct mode
                if not my_graph.not_within_min(
                        mouse_pos) and not add_node_mode:
                    for node in my_graph.get_graph():
                        if primary == -1 and node.state == 1:  # if no primary node has been selected
                            primary = node
                        elif primary != -1 and node.state == 1 and primary != node:  # cannot make a edge with itself
                            secondary = node
                        if primary != -1 and secondary != -1:  # add the edge and reset primary and secondary
                            new_edge = Edge(primary, secondary,
                                            not_selected_color)
                            if new_edge.get_edge_data(
                            ) not in my_graph.get_edges(
                            ):  # no duplicate edges allowed
                                my_graph.add_bi_edge(new_edge)
                            primary.not_selected()
                            secondary.not_selected()
                            primary = -1
                            secondary = -1

                # deleting nodes -> correct mode, and node selected
                if add_node_mode == 2 and not my_graph.not_within_min(
                        mouse_pos):
                    for node in my_graph.get_graph(
                    ):  # find which node was selected
                        if node.state == 1:
                            my_graph.del_node(node)

                # deleting edges -> correct mode, edge selected NEEDS FIXING
                if add_node_mode == 3 and not my_graph.not_within_min(
                        mouse_pos):
                    for node in my_graph.get_graph():
                        if primary == -1 and node.state == 1:  # if no primary node has been selected
                            primary = node
                        elif primary != -1 and node.state == 1 and primary != node:  # cannot make a edge with itself
                            secondary = node
                        if primary != -1 and secondary != -1:  # add the edge and reset primary and secondary
                            for edge in my_graph.edge_list:
                                if (edge.u is primary and edge.v is secondary
                                    ) or (edge.v is primary
                                          and edge.u is secondary):
                                    my_graph.del_edge(edge)
                            primary.not_selected()
                            secondary.not_selected()
                            primary = -1
                            secondary = -1

                if add_node_mode == 4 and not my_graph.not_within_min(
                        mouse_pos):
                    num_selected = 0  # make sure only one start node can be selected at a time
                    for node in my_graph.get_graph():
                        if node.state == 1:
                            start = node.name
                        node.not_selected()
                    for node in my_graph.get_graph():
                        if node.name == start:
                            node.colour = selected_color

        for button in buttons:  # draw all buttons
            button.draw()
        my_graph.draw()
        pydisplay.update()
Exemple #40
0
def start():
    pygame.init()
    p = Player((200, 0, 0))
    p2 = Player((100, 100, 0))
    p2.pos = (100, 100)
    p.prepare()
    p2.prepare()
    players = []
    players.append(p)
    players.append(p2)

    gameDisplay = display.set_mode(resolution[choseResolution])
    display.set_caption('Survival\'s King')
    clock = pygame.time.Clock()
    bullets = []

    gameItens = []
    item1 = Gun()
    item1.damage = 35
    item1.pos = (150, 150)

    gameItens.append(item1)

    crashed = False
    fpsCounter = 0
    fps = 0
    lastDisplay = 0

    while not crashed:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                crashed = True
        keys = pygame.key.get_pressed()
        if keys[pygame.K_w]:
            p.pos = (p.pos[0], p.pos[1] - p.moveSpeed)
        if keys[pygame.K_s]:
            p.pos = (p.pos[0], p.pos[1] + p.moveSpeed)
        if keys[pygame.K_a]:
            p.pos = (p.pos[0] - p.moveSpeed, p.pos[1])
        if keys[pygame.K_d]:
            p.pos = (p.pos[0] + p.moveSpeed, p.pos[1])
        if pygame.mouse.get_pressed()[0] == 1:
            if keys[pygame.K_f]:
                (gr, it, eq) = mouseOver()
                if it >= 0 and len(p.itens) > it:
                    pass
                if gr >= 0 and len(p.ground) > gr:
                    p.itens.append(p.ground[gr])
                    gameItens.remove(p.ground[gr])
                if eq >= 0 and len(p.itens) > eq:
                    pass
            else:
                p.equipedGun.fire(p, p.pos,
                                  (pygame.mouse.get_pos()[0] - p.pos[0],
                                   pygame.mouse.get_pos()[1] - p.pos[1]),
                                  bullets)

        for item in gameItens:
            drawItem(item, gameDisplay)

        for player in players:
            player.ground = []
            for bullet in bullets:
                drawBullet(bullet, gameDisplay)
                if hit(player, bullet):
                    player.takeShot(bullet)
                if bullet.die:
                    bullets.remove(bullet)

            for item in gameItens:
                if colide(player, item):
                    player.ground.append(item)
            drawPlayer(player, gameDisplay)

        drawStatsPanel(p, gameDisplay)

        if keys[pygame.K_f]:
            drawInventory(gameDisplay, p.itens, p.ground)

        fpsCounter += 1
        if pygame.time.get_ticks() - lastDisplay >= 1000:
            lastDisplay = pygame.time.get_ticks()
            fps = fpsCounter
            fpsCounter = 0

        fpsText = font.render('FPS: ' + str(fps), False, (200, 200, 200))
        gameDisplay.blit(fpsText, (10, 10))

        display.update()
        gameDisplay.fill((0, 0, 0))
        #gameDisplay.fill(pygame.image.load('/sprits/ground.png'))

        clock.tick(30)
    pygame.quit()
Exemple #41
0
 def play(self):
     set_repeat(1, 1)
     timer = Clock()
     while not self.end:
         for event in get():
             if event.type == QUIT:
                 exit()
             if event.type == KEYDOWN:
                 k = event.key
                 if k == K_ESCAPE:
                     self.game_pause()
                 if k == K_DOWN:
                     self.hero.rotate(0)
                     self.hero.ismoved = True
                 if k == K_UP:
                     self.hero.rotate(1)
                     self.hero.ismoved = True
                 if k == K_RIGHT:
                     self.hero.rotate(2)
                     self.hero.ismoved = True
                 if k == K_LEFT:
                     self.hero.rotate(3)
                     self.hero.ismoved = True
                 if k == K_SPACE:
                     self.hero.place_bomb(self.sprites_and_bombs)
             elif event.type == KEYUP and event.key != 32:
                 self.hero.ismoved = False
         for m in self.mobs:
             m.strategy()
         self.screen.fill(self.color)
         self.grass.update(self.screen)
         self.bonuses.update(self.screen)
         self.sprites.update(self.screen)
         self.hero.update(self.screen, self.sprites)
         self.mobs.update(self.screen, self.sprites_and_bombs)
         self.show_info()
         update()
         killed = False
         clock = get_ticks()
         for ex in self.hero.explosions:
             if clock + 780 < ex.clear_time:
                 for m in self.mobs:
                     if collide_rect(m, ex):
                         self.scores += 15
                         m.kill()
                 if collide_rect(self.hero, ex):
                     killed = True
         if killed or self.hero.collide(self.mobs):
             self.death()
             if self.end:
                 break
         else:
             for bon in self.bonuses:
                 if bon.visible() and collide_rect(self.hero, bon):
                     if bon.type == 4:
                         self.lives += 1
                     elif bon.type == 5:
                         self.max_bombs += 1
                         self.hero.max_bombs += 1
                     elif bon.type == 6:
                         self.strength += 1
                         self.hero.strength += 1
                     bon.remove(self.bonuses)
                     self.scores += 10
         if len(self.mobs) == 0:
             self.lvl += 1
             self.scores += 20
             self.load_level()
         timer.tick(self.fps)
    def next_frame(self, action, text=''):
        pump()
        reward = 1
        terminal = False
        # Check input action
        if action == 0:  # 0 means flap
            self.current_velocity_y = self.upward_speed
            self.is_flapped = True

        # Update score
        bird_center_x = self.bird_x + self.bird_width / 2
        for pipe in self.pipes:
            pipe_center_x = pipe["x_upper"] + self.pipe_width / 2
            if pipe_center_x < bird_center_x < pipe_center_x + 5:
                self.score += 1
                break

        # get detal_x, detal_y
        for pipe in self.pipes:
            if self.bird_x < pipe["x_lower"] + self.pipe_width:
                detal_x = pipe['x_lower'] + self.pipe_width - self.bird_x
                detal_y = pipe['y_lower'] - self.bird_y + self.bird_height

                # a triangle
                points = ((self.bird_x, self.bird_y + self.bird_height),
                          (pipe['x_lower'] + self.pipe_width,
                           pipe['y_lower']), (self.bird_x, pipe['y_lower']))
                break

        # Update index and iteration
        if (self.iter + 1) % 3 == 0:
            self.bird_index = next(self.bird_index_generator)
            self.iter = 0
        self.base_x = -((-self.base_x + 100) % self.base_shift)

        # Update bird's position
        if self.current_velocity_y < self.max_velocity_y and not self.is_flapped:
            self.current_velocity_y += self.downward_speed
        if self.is_flapped:
            self.is_flapped = False
        self.bird_y += min(
            self.current_velocity_y,
            self.bird_y - self.current_velocity_y - self.bird_height)
        if self.bird_y < 0:
            self.bird_y = 0

        # Update pipes' position
        for pipe in self.pipes:
            pipe["x_upper"] += self.pipe_velocity_x
            pipe["x_lower"] += self.pipe_velocity_x
        # Update pipes
        if 0 < self.pipes[0]["x_lower"] < 5:
            self.pipes.append(self.generate_pipe())
        if self.pipes[0]["x_lower"] < -self.pipe_width:
            del self.pipes[0]
        if self.is_collided():
            terminal = True
            reward = -1000
            self.__init__()

        # show info
        font = pygame.font.Font('freesansbold.ttf', 20)
        info = font.render(text, False, (255, 200, 10))

        # Draw everything
        self.screen.blit(self.background_image, (0, 0))
        self.screen.blit(self.base_image, (self.base_x, self.base_y))
        self.screen.blit(self.bird_images[self.bird_index],
                         (self.bird_x, self.bird_y))
        for pipe in self.pipes:
            self.screen.blit(self.pipe_images[0],
                             (pipe["x_upper"], pipe["y_upper"]))
            self.screen.blit(self.pipe_images[1],
                             (pipe["x_lower"], pipe["y_lower"]))
        self.screen.blit(info, (0, 100))
        pygame.draw.polygon(display.get_surface(), (255, 0, 0),
                            points,
                            width=1)

        image = array3d(display.get_surface())
        display.update()
        self.fps_clock.tick(self.fps)

        return image, reward, terminal, self.score, str(
            (int(detal_x / 4), int(detal_y / 4)))
 def update_display(self, dirty_rects):
     display.update(dirty_rects)
Exemple #44
0
    def change_level(self, currentLevel, stage):
        self.reset_level()
        self.level = currentLevel
        self.stage = stage
        ldata = Lvl_Data(self.level, stage)
        self.objective = ldata.objective
        self.updated_obj = False  ######CHANGED
        PM.music.load(ldata.music_file)
        PM.music.play(-1)
        PM.music.set_volume(0.5)
        ####turn back on only for presentations?
        if self.stage == 1:
            Cutscene(Globals.SCREEN, self.level)

        #interpretting mapfile.txt
        if (self.level > 1):
            del self.map
        Map.GRASS_ARRAY = []
        Map.PAD_ARRAY = []
        self.pad_list.empty()
        ##new map is different than level 1's map, of course.
        self.map = Map.Map(ldata.map_file, self.level)

        self.camera = cam.Camera(self.map.get_surface())
        self.camera_background = None

        self.background = self.map.create_background()
        self.allsprites.clear(Globals.SCREEN, self.background)
        Globals.SCREEN.blit(self.background, (0, 0))

        PD.update()

        self.num_enemies += self.map.get_num_enemies(1)  # icecream
        self.num_enemies += self.map.get_num_enemies(2)  # burger
        self.num_enemies += self.map.get_num_enemies(3)  # lettuce
        self.num_enemies += self.map.get_num_enemies(4)  # cupcake
        self.num_enemies += self.map.get_num_enemies(5)  # egg

        #icecream
        for e in range(self.map.get_num_enemies(1)):
            icecream = IceCream(self.map.get_enemy_coordx(e, 1),
                                self.map.get_enemy_coordy(e, 1))
            self.icecream_list.add(icecream)
        #burger
        for e in range(self.map.get_num_enemies(2)):
            burger = Burger(self.map.get_enemy_coordx(e, 2),
                            self.map.get_enemy_coordy(e, 2), self.level)
            self.burger_list.add(burger)
        #lettuce
        for e in range(self.map.get_num_enemies(3)):
            lettuce = Lettuce(self.map.get_enemy_coordx(e, 3),
                              self.map.get_enemy_coordy(e, 3))
            self.lettuce_list.add(lettuce)
        #cupcake
        for e in range(self.map.get_num_enemies(4)):
            cupcake = Cupcake(self.map.get_enemy_coordx(e, 4),
                              self.map.get_enemy_coordy(e, 4))
            self.cupcake_list.add(cupcake)
        #egg
        for e in range(self.map.get_num_enemies(5)):
            egg = Egg(self.map.get_enemy_coordx(e, 5),
                      self.map.get_enemy_coordy(e, 5), self.level)
            self.egg_list.add(egg)

        self.enemy_list.add(self.icecream_list)
        self.enemy_list.add(self.burger_list)
        self.enemy_list.add(self.lettuce_list)
        self.enemy_list.add(self.cupcake_list)
        self.enemy_list.add(self.egg_list)

        player_health = 0
        #get enemy health
        if self.stage > 1:
            player_health = self.character.get_health()

        self.character = Player(Globals.DELTA)
        self.player_group = PS.GroupSingle(self.character)

        if self.stage > 1:
            self.character.set_health(player_health, True)

        #pads
        for e in range(len(self.map.padtiles)):
            if self.map.pad_type[e] == 0:  # hot
                newPad = Pad.create_Pad(self.map.get_pad_x(e),
                                        self.map.get_pad_y(e), 0)
                self.pad_list.add(newPad)
            elif self.map.pad_type[e] == 1:
                newPad = Pad.create_Pad(self.map.get_pad_x(e),
                                        self.map.get_pad_y(e), 1)
                self.pad_list.add(newPad)

        #get block sprite group from the map file
        self.block_group = self.map.get_object_group()

        #list that holds traps
        self.trap_list = []
        # self.trap_group = PS.Group()

        # self.item_group = PS.Group()

        #allsprites has all dirty sprites (player, enemies, traps)
        self.allsprites = PS.LayeredDirty(self.trap_group, self.pad_list,
                                          self.item_group, self.player_group,
                                          self.icecream_list, self.burger_list,
                                          self.egg_list, self.lettuce_list,
                                          self.projectile_group)

        self.allsprites.clear(Globals.SCREEN, self.background)

        ####(Level variables)####
        Globals.INVINCIBILITY_COUNT = 0  # player's invinicibility frame time
        #what kind of enemy by ID (-1 means no enemy) used for collisions
        self.enemy_ID = -1
        #if true, tells map to update w/o key & door
        self.map_modified = False
        ##temp obj conditions
        self.cheesed = True
        self.killed = True
        self.camera_background = self.camera.update(
            self.character.get_coordinates(), self.map.get_surface())
Exemple #45
0
 def update(self):
     """ Update the window by copying all drawn objects from the
         frame buffer to the display.
         - self is the Window
     """
     update()
Exemple #46
0
def play():

    # OBJECTS
    croshair = game_objects.Object(images.croshair_img)
    bogeys = []
    missiles = []
    clip = 4
    score = 0
    missed = 0
    lives = 3
    ship = game_objects.Object(image=images.ship_img,
                               x=SHIP_LOCALE[0],
                               y=SHIP_LOCALE[1],
                               expire=False)

    missile_speed = 20 * 25 / fps
    min_bogey_speed = 5 * 25 / fps
    max_bogey_speed = 15 * 25 / fps
    show_target = 20 * fps / 25

    # ship_rect = config.ship_img.get_rect(center = (SHIP_LOCALE))
    ship.show(-1)

    # EVENTS
    SPAWNBOGEY = pygame.USEREVENT
    pygame.time.set_timer(SPAWNBOGEY, 800)  # Start 1500

    REFILL = pygame.USEREVENT + 1
    pygame.time.set_timer(REFILL, 700)

    running = True

    # GAME LOOP

    while running == True:

        # GARBAGE COLLECTION
        #
        # deletes objects that have expired:
        # whose time has run out and expiration is enabled
        missiles = [
            missile for missile in missiles if not missile.is_garbage()
        ]
        bogeys = [bogey for bogey in bogeys if not bogey.is_garbage()]

        # DRAWING
        screen.blit(images.background_img, (0, 0))
        ship.draw(screen)
        croshair.draw(screen)
        texts.clip_display(screen, config, clip)
        texts.score_display(screen, config, score)
        texts.missed_display(screen, config, missed)
        # texts.debug_display(screen, config, missiles, bogeys)

        # Draw Bogeys
        for bogey in bogeys:
            bogey.move_y()
            bogey.draw(screen)
            # Check if Bogey is leaving the screen
            if bogey.rect.centery > SCREEN_SIZE[1]:
                missed += 1
                bogey.show(0)

        # Draw Missiles
        for missile in missiles:
            missile.move_2d()
            missile.draw(screen)

        # Check collisions
        hits = check_collision(bogeys, missiles)
        score += hits

        # If enough bogeys aren't shot down
        # end the game
        if missed >= lives:
            running = False

        # EVENTS
        current_events = pygame.event.get()
        for event in current_events:

            # KEYBOARD
            if event.type == pygame.KEYDOWN:
                if event.key in (pygame.K_SPACE, pygame.K_ESCAPE,
                                 pygame.K_RETURN, pygame.K_KP_ENTER):
                    running = False

            # APP CLOSE
            if event.type == pygame.QUIT:
                running = False

            # MOUSE
            if event.type == pygame.MOUSEBUTTONDOWN:
                if clip > 0:
                    clip -= 1

                    mouse_x, mouse_y = mouse.get_pos()
                    vect = vector((mouse_x, mouse_y), SHIP_LOCALE)
                    missiles.append(spawn_missile(vect, missile_speed))

                    croshair.pos(mouse_x, mouse_y)
                    croshair.show(show_target)

            # TIMED EVENTS
            if event.type == SPAWNBOGEY:
                bogeys.append(
                    spawn_bogey(random.randrange(32, SCREEN_SIZE[0] - 32),
                                random_speed(min_bogey_speed,
                                             max_bogey_speed)))

            if event.type == REFILL:
                clip = refill_clip(clip)

        display.update()
        clock.tick(fps)

    # SHOW POST_GAME

    post_game = True

    while post_game:

        screen.blit(images.background_img, (0, 0))
        texts.clip_display(screen, config, clip)
        texts.score_display(screen, config, score)
        # texts.debug_display(screen, config, missiles, bogeys)
        texts.missed_display(screen, config, missed)
        gameover_rect = texts.gameover_display(screen, config, score)

        current_events = pygame.event.get()
        for event in current_events:

            # KEYBOARD
            if event.type == pygame.KEYDOWN:

                post_game = False

            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_x, mouse_y = mouse.get_pos()
                if gameover_rect.collidepoint((mouse_x, mouse_y)):
                    post_game = False

            # APP CLOSE
            if event.type == pygame.QUIT:
                post_game = False

        display.update()
        clock.tick(25)

    return score
Exemple #47
0
def main(username: str) -> int:
    global isMuted
    run, fps = True, 60
    lives, font_, clock = 5, SysFont("comicsans", 50), Clock()
    level = 0
    player = Player(300, 650, username)
    bgy, bgy2 = 0.0, -float(BACKGROUND.get_height())
    enemies, enemy_lasers = [], []
    player_laser_vel = -8
    wave_length, enemy_vel, laser_vel = 5, 1, 5
    mixer.music.load("assets/background.wav")
    mixer.music.play(-1)

    def update_window() -> None:
        WIN.blit(BACKGROUND, (0, bgy))
        WIN.blit(BACKGROUND, (0, bgy2))
        level_label = font_.render(f"Score: {player.score}", True, (255, 255, 255))
        lives_label = font_.render(f"Lives: {lives}", True, (255, 255, 255))
        WIN.blit(lives_label, (10, 10))
        for enemy in enemies:
            enemy.draw(WIN)
        for laser in enemy_lasers:
            laser.draw(WIN)
        WIN.blit(level_label, (WIDTH - level_label.get_width()-10, 10))
        player.draw(WIN)
        update()

    while run:
        clock.tick(fps)
        if len(enemies) == 0:
            if level == 10:
                update_scores(player)
                return 1
            wave_length += 1
            enemies.extend(spawn(wave_length))
            level += 1
            if level % 4 == 0:
                enemy_vel += 1
                player.v += 1
                player_laser_vel -= 1
            level_label = font_.render(F"Level {level}...", True, (255, 255, 255))
            WIN.blit(level_label, (WIDTH//2 - level_label.get_width()//2, HEIGHT//2))
            update()
            pygame.time.wait(2500)
        update_window()
        bgy += 1.4
        bgy2 += 1.4
        if bgy > HEIGHT:
            bgy = -BACKGROUND.get_height()
        if bgy2 > HEIGHT:
            bgy2 = -BACKGROUND.get_height()
        for event in get():
            if event.type == QUIT:
                quit()
        keys = get_pressed()
        if len(keys):
            player.move(keys)
        if keys[K_SPACE]:
            bulletSound.play()
            player.shoot()
        if keys[K_m]:
            isMuted = not isMuted
            if isMuted:
                mixer.music.stop()
            else:
                mixer.music.play(-1)
        for enemy in enemies[:]:
            enemy.move(enemy_vel)
            if randint(0, 2*30) == 1 and enemy.y > 0:
                enemy.shoot(enemy_lasers)
            if collide(enemy, player):
                enemies.remove(enemy)
                lives -= 1
            elif enemy.off_screen():
                enemies.remove(enemy)
                player.score -= 1
                player.score = max(player.score, 0)
        lives = move_lasers(laser_vel, player, enemy_lasers, lives)
        if lives <= 0:
            update_scores(player)
            return 1
        player.move_lasers(player_laser_vel, enemies)
    update_scores(player)
    return 1
Exemple #48
0
 def update(cls):
     fondo = display.get_surface()
     fondo.fill(COLOR_FONDO)
     cls.contents.draw(fondo)
     display.update()
Exemple #49
0
def cambiaColorFondo(sc, color):
    sc.fill(color)
    update()
 def _blank_screen(self):
     """Render a blank screen filled with the background color."""
     self._screen.fill((0, 0, 0))
     display.update()
Exemple #51
0
def graphsProcess(s):
    display.update()
Exemple #52
0
 def draw_game(self):
     self.DISPLAY.fill(self.BACKGROUND_COLOR)
     self.draw_grid()
     self.snake.draw(self.DISPLAY)
     self.apple.draw(self.DISPLAY)
     display.update()
Exemple #53
0
 def update(self):
     self._draw_background()
     self._draw_buttons()
     self._draw_tiles()
     self._draw_labels()
     update()
Exemple #54
0
    def update(self):
        # Update the window by copying all drawn objects from the
        # frame buffer to the display.
        # - self is the Window

        update()
Exemple #55
0
    def next_frame(self, action):
        pump()
        reward = 0.1
        terminal = False
        # Check input action
        if action == 1:
            self.current_velocity_y = self.upward_speed
            self.is_flapped = True

        # Update score
        bird_center_x = self.bird_x + self.bird_width / 2
        for pipe in self.pipes:
            pipe_center_x = pipe["x_upper"] + self.pipe_width / 2
            if pipe_center_x < bird_center_x < pipe_center_x + 5:
                self.score += 1
                reward = 1
                break

        # Update index and iteration
        if (self.iter + 1) % 3 == 0:
            self.bird_index = next(self.bird_index_generator)
            self.iter = 0
        self.base_x = -((-self.base_x + 100) % self.base_shift)

        # Update bird's position
        if self.current_velocity_y < self.max_velocity_y and not self.is_flapped:
            self.current_velocity_y += self.downward_speed
        if self.is_flapped:
            self.is_flapped = False
        self.bird_y += min(
            self.current_velocity_y,
            self.bird_y - self.current_velocity_y - self.bird_height)
        if self.bird_y < 0:
            self.bird_y = 0

        # Update pipes' position
        for pipe in self.pipes:
            pipe["x_upper"] += self.pipe_velocity_x
            pipe["x_lower"] += self.pipe_velocity_x
        # Update pipes
        if 0 < self.pipes[0]["x_lower"] < 5:
            self.pipes.append(self.generate_pipe())
        if self.pipes[0]["x_lower"] < -self.pipe_width:
            del self.pipes[0]
        if self.is_collided():
            terminal = True
            #if self.distance_reward < 0.2:
            #    reward = -1
            #else:
            if terminal == True:
                while 1 == 1:
                    print("1")
            reward = -1 + self.distance_reward
            #print(reward)
            self.__init__()

        # Draw everything
        self.screen.blit(self.background_image, (0, 0))
        self.screen.blit(self.base_image, (self.base_x, self.base_y))
        self.screen.blit(self.bird_images[self.bird_index],
                         (self.bird_x, self.bird_y))
        for pipe in self.pipes:
            self.screen.blit(self.pipe_images[0],
                             (pipe["x_upper"], pipe["y_upper"]))
            self.screen.blit(self.pipe_images[1],
                             (pipe["x_lower"], pipe["y_lower"]))
        image = array3d(display.get_surface())
        display.update()
        self.fps_clock.tick(self.fps)
        return image, reward, terminal, self.score
Exemple #56
0
def menu():
    init()
    FPS = 15
    clock = pygame.time.Clock()    
    red = (255, 0, 0)
    green = (0, 255, 0)
    blue = (255, 255, 100)
    
    screen.fill((0, 0, 0))
    display.update()
    play_is_pressed = False
    chosen_pers = None
    chosen_btn = 0
    first_screen_chosen_btn = 0
    
    
    #music
    pygame.mixer.music.load('2.mp3')
    pygame.mixer.music.play(-1)
    
    bg = pygame.image.load('images/bg1.png')
    bg1 = pygame.image.load('images/bg2.png')
    x = 250
    y = 250
    r = 20
    dx = 0
    dy = 0
    btn_play = [512 - 100, 368 - 50, 200, 90]
    btn_exit = [5, 690, 80, 50]
    first_screen_btns_r = [btn_play, btn_exit]
    
    btn_play = [512 - 100, 368 - 50,pygame.image.load('images/play.png')]
    btn_exit = [18, 700, pygame.image.load('images/exit.png')]
    first_screen_btns = [btn_play, btn_exit]    
    
    btn1 = [512 - 100 - 250, 368 - 100]
    btn2 = [512 - 100, 368 - 100]
    btn3 = [512 - 100 + 250, 368 - 100] 
    btn_back = [18, 700]
    btn_rating = [900, 700]
    
    r_btn1 = [512 - 100 - 250, 368 - 100, 200, 200]
    r_btn2 = [512 - 100, 368 - 100, 200, 200]
    r_btn3 = [512 - 100 + 250, 368 - 100, 200, 200] 
    r_btn_back = [18, 700, 60, 50]
    r_rating = [900, 700, 100, 60]
    buttons_r = [r_btn1, r_btn2, r_btn3, r_btn_back, r_rating]  
    
    btn1 += [pygame.image.load('images/Nps/Рыцарь/2(Стоит).png')]  
    btn2 += [pygame.image.load('images/Nps/Принцесса/Стоит.png')]
    btn3 += [pygame.image.load('images/Nps/Маг/2(Стоит).png')]
    btn_back += [pygame.image.load('images/back.png')]
    btn_rating += [pygame.image.load('images/rating.png')]
    buttons_ = [btn1, btn2, btn3, btn_back, btn_rating]     
    
    display.update()
    loop = 1
    rating_screen = 0
    st = 0
    check = 0
    while loop:
        pygame.mouse.set_visible(0)
        clock.tick(FPS)
        screen.fill((0, 0, 0))
        if st == 0:
            screen.blit(bg, (0,0))
            for btn in first_screen_btns:
                screen.blit(btn[2], btn[:2])
                
            draw.rect(screen, blue, first_screen_btns_r[first_screen_chosen_btn], 5)
            display.update()
            for i in event.get():
                if i.type == QUIT:
                    loop = 0
                elif i.type == KEYDOWN:
                    if i.key == K_SPACE:
                        if first_screen_chosen_btn == 0:
                            st = 1
                        else:
                            loop = 0
                    if i.key == K_s:
                        first_screen_chosen_btn = 1
                    if i.key == K_w:
                        first_screen_chosen_btn = 0
        elif st == 2:
            
            text_get("Last 5 player results", (255 ,255,255), 512, 100, 100)
            
            with open("history.txt", "r") as file: 
                text = list(map(str, [line[:-1] for line in file]))[-5:]
                for i in range(5):
                    text_get(text[i], (255,255,255), 512, 250 + i * 100, 79)
                for i in event.get():
                    if i.type == QUIT:
                        loop = 0
                    elif i.type == KEYDOWN:
                        if i.key == K_a:
                            check = 1
                        elif i.key == K_d:
                            check = 1
                        elif i.key == K_w:
                            check = 1
                        elif i.key == K_s:
                            check = 1
                        elif i.key == K_SPACE:
                            st = 1
                screen.blit(buttons_[3][2], buttons_[3][:2])
                draw.rect(screen, blue, buttons_r[3], 5)
                
                
                if keyPressed(pygame.K_SPACE) and check:
                    st = 1
                sleep(0.5)
                display.update()  
                    
        elif chosen_pers == None and st == 1:
            screen.blit(bg1, (0,0))
            text_get("Choose one of sprites:", (255, 255, 255), 512, 100, 50)
            for button in buttons_:
                screen.blit(button[2], button[:2])
               # draw.rect(screen, (255, 255, 255), button)
            draw.rect(screen, blue, buttons_r[chosen_btn], 5)
            display.update()
            for i in event.get():
                if i.type == QUIT:
                    loop = 0
                elif i.type == KEYDOWN:
                    if i.key == K_a:
                        chosen_btn = max(0, chosen_btn - 1)
                    elif i.key == K_d:
                        chosen_btn = min(4, chosen_btn + 1)
                    elif i.key == K_w:
                        if chosen_btn == 3 or chosen_btn == 4:
                            chosen_btn = 0
                    elif i.key == K_s:
                        chosen_btn = 3
                    elif i.key == K_SPACE:
                        if chosen_btn < 3:
                            chosen_pers = chosen_btn
                        elif chosen_btn == 4:
                            st  = 2
                        else:
                            st = 0
        
                    # sleep(0.5)            
        else:
            loop = 0
            # quit()  
            return chosen_pers
    quit()  
    time.delay(30)
Exemple #57
0
    def clear(self):
        # Erase the window contents
        # - self is the Window

        if self.__auto_update__:
            update()
Exemple #58
0
    def run(self):
        self.setup()
        self.running = introGame(self.screen, self.data,
                                 self.database.getProfile())

        add_rumput = True
        add_keris = True
        add_bambu = True
        while self.running:
            events = self.core.events()
            if events["type"]["quit"]:
                self.running = False
                break
            elif events["type"]["keydown"]:
                if events["keys"]["space"] or events["keys"]["up"]:
                    self.player.jump_up()

            #=== Move position ===#
            boundary_values = [0, self.grass_position[-1]]
            self.player.update(
                boundary_values,
                float(
                    self.clock.tick(self.config.parse["settings"]["frame"]) /
                    1000))
            self.tanah_position[0] = -(
                (-self.tanah_position[0] + self.speed) % self.tanah_diff)
            self.grass_position[0] = -(
                (-self.grass_position[0] + self.speed) % self.grass_diff)

            #=== Move rumput object ===#
            for rumput in self.rumputGroup:
                rumput.rect.left -= self.config.parse["settings"]["speed"]
                if rumput.rect.left < 4 and rumput.rect.left > 0 and add_rumput:
                    if len(self.rumputGroup) > 50: continue
                    else:
                        image = self.data["textures"][
                            "rumput" + str(random.randint(1, 6))]
                        self.rumputGroup.add(
                            Rumput(image, [
                                random.randint(self.config.getRect.width,
                                               3000),
                                self.config.getRect.height * 0.80
                            ]))
                elif rumput.rect.right < 0:
                    if len(self.rumputGroup) > 50:
                        self.rumputGroup.remove(rumput)
                    else:
                        self.rumputGroup.remove(rumput)
                        image = self.data["textures"][
                            "rumput" + str(random.randint(1, 6))]
                        self.rumputGroup.add(
                            Rumput(image, [
                                random.randint(self.config.getRect.width,
                                               3000),
                                self.config.getRect.height * 0.80
                            ]))

            #=== Move keris object ===#
            for keris in self.kerisGroup:
                keris.rect.left -= self.config.parse["settings"]["speed"]
                #=== Check object to object ===#
                if collide_mask(self.player, keris) and not keris.is_used:
                    keris.is_used = True
                    self.kerisGroup.remove(keris)
                    add_keris = True
                    self.health.add_value()
                    if self.score.add_score():
                        self.running = False
                        break

                if keris.rect.left < 4 and keris.rect.left > 0 and add_keris:
                    if self.health.revalue():
                        self.running = False
                        break
                    keris = Keris(self.data["anim"]["keris"], [
                        random.randint(self.config.getRect.width,
                                       self.config.getRect.width * 2), 10
                    ])
                    keris.rect.bottom += random.randint(
                        10, self.config.getRect.height - 130)
                    self.kerisGroup.add(keris)
                    add_keris = False

                elif add_keris and keris.is_used:
                    if random.randint(0, 1) == 1:
                        for _ in range(random.randint(1, 2)):
                            keris = Keris(self.data["anim"]["keris"], [
                                random.randint(self.config.getRect.width,
                                               self.config.getRect.width * 2),
                                10
                            ])
                            keris.rect.bottom += random.randint(
                                10, self.config.getRect.height - 130)
                            self.kerisGroup.add(keris)
                    else:
                        keris = Keris(self.data["anim"]["keris"], [
                            random.randint(self.config.getRect.width,
                                           self.config.getRect.width * 2), 10
                        ])
                        keris.rect.bottom += random.randint(
                            10, self.config.getRect.height - 130)
                        self.kerisGroup.add(keris)
                    add_keris = False
                elif keris.rect.right < 0:
                    self.health.revalue()
                    self.kerisGroup.remove(keris)
                    keris = Keris(self.data["anim"]["keris"], [
                        random.randint(self.config.getRect.width,
                                       self.config.getRect.width * 2), 10
                    ])
                    keris.rect.bottom += random.randint(
                        10, self.config.getRect.height - 130)
                    self.kerisGroup.add(keris)

            for bambuEnemy in self.bambuGroup:
                bambuEnemy.rect.left -= self.config.parse["settings"]["speed"]
                if collide_mask(self.player,
                                bambuEnemy) and not bambuEnemy.is_used:
                    bambuEnemy.is_used = True
                    add_bambu = True
                    self.health.revalue()
                    self.score.rescore()

                if bambuEnemy.rect.left < 4 and bambuEnemy.rect.left > 0 and add_bambu:
                    bambu = Bambu(self.data["other"]["bambu"], [
                        random.randint(self.config.getRect.width,
                                       self.config.getRect.width * 2), 10
                    ])
                    bambu.rect.bottom += self.config.getRect.height * 0.78
                    self.bambuGroup.add(bambu)
                    add_bambu = False

                elif bambuEnemy.rect.right < 0:
                    self.bambuGroup.remove(bambuEnemy)
                    bambu = Bambu(self.data["other"]["bambu"], [
                        random.randint(self.config.getRect.width,
                                       self.config.getRect.width * 2), 10
                    ])
                    bambu.rect.bottom += self.config.getRect.height * 0.78
                    self.bambuGroup.add(bambu)

            #=== Screen display ===#
            self.screen.blit(self.BACKGROUND, (0, 0))
            self.rumputGroup.draw(self.screen)
            self.screen.blit(self.tanah, self.tanah_position)
            self.screen.blit(self.grass, self.grass_position)
            self.bambuGroup.draw(self.screen)
            self.health.draw(self.screen)
            self.kerisGroup.draw(self.screen)
            self.player.draw(self.screen)
            self.score.draw(self.screen)

            #=== Check ===#
            if self.score.check():
                self.running = False
            elif self.health.check():
                self.running = False
            self.clock.tick(self.config.parse["settings"]["frame"])
            update()
        self.logs.warning("Menyimpan score")
        self.database.updateScore(self.score.getScore)
        self.logs.warning("Menutup game...")
        pygame.quit()
Exemple #59
0
                elif rhombus.collidepoint(mouse_pos):
                    grab = rhombus
                    other = triangle
                elif triangle.collidepoint(mouse_pos):
                    grab = triangle
                    other = rhombus

        Y_triangle = triangle.project((0, 1))
        Y_rhombus = rhombus.project((0, 1))
        draw.line(SCREEN, (255, 0, 0), (2, Y_triangle[0]), (2, Y_triangle[1]),
                  2)
        draw.line(SCREEN, (0, 0, 255), (7, Y_rhombus[0]), (7, Y_rhombus[1]), 2)

        X_triangle = triangle.project((1, 0))
        X_rhombus = rhombus.project((1, 0))
        draw.line(SCREEN, (255, 0, 0), (X_triangle[0], 2), (X_triangle[1], 2),
                  2)
        draw.line(SCREEN, (0, 0, 255), (X_rhombus[0], 7), (X_rhombus[1], 7), 2)

        draw.circle(SCREEN, (255, 255, 255), triangle.C.astype(int), 3)
        draw.circle(SCREEN, (255, 255, 255), rhombus.C.astype(int), 3)

        r = array(mouse.get_rel())
        if grab:
            grab.C = mouse_pos
            distance = grab.distance(other, -r)
            msg = font.render(str(distance), 0, (255, 255, 255))
            SCREEN.blit(msg, (0, 0))

        display.update()
Exemple #60
0
def main():
    pygame.init()

    # =============================================================================
    #     import ctypes
    #     # Query DPI Awareness (Windows 10 and 8)
    #     awareness = ctypes.c_int()
    #     errorCode = ctypes.windll.shcore.GetProcessDpiAwareness(0, ctypes.byref(awareness))
    #     print(awareness.value)
    #     errorCode = ctypes.windll.shcore.SetProcessDpiAwareness(0)
    #     print(errorCode)
    #     success = ctypes.windll.user32.SetProcessDPIAware()
    # =============================================================================
    screen = display.set_mode(size=(WIDTH, HEIGHT),
                              flags=pygame.SCALED,
                              display=0,
                              depth=32)
    #screen = display.set_mode(size=(WIDTH,HEIGHT),display=0,depth=32)

    # declaration of algorithms for ThorPy buttons
    runKnn = thorpy.make_button("kNN", func=lambda: run_classification("KNN"))
    runLda = thorpy.make_button("LDA", func=lambda: run_classification("LDA"))
    runNB = thorpy.make_button("NB", func=lambda: run_classification("NB"))
    runTree = thorpy.make_button("Decision Tree",
                                 func=lambda: run_classification("TREE"))
    runForest = thorpy.make_button("Random Forest",
                                   func=lambda: run_classification("RF"))
    runSvc = thorpy.make_button("SVM", func=lambda: run_classification("SVM"))
    runGB = thorpy.make_button("Gradient Boosting",
                               func=lambda: run_classification("GB"))
    runPerc = thorpy.make_button("Perceptron",
                                 func=lambda: run_classification("PERC"))
    runReset = thorpy.make_button("RESET", func=reset)
    # create a box of buttons
    box = thorpy.Box.make(elements=[
        runKnn, runLda, runNB, runTree, runForest, runSvc, runGB, runPerc,
        runReset
    ])
    menu = thorpy.Menu(box)
    box.set_topleft((600, 5))
    box.blit()
    box.update()

    display.set_caption("Simple classifier byPK")

    while True:
        clock.tick(40)
        for event in pygame.event.get():
            menu.react(event)  #read an event
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if pygame.mouse.get_pressed()[0]:
                pos = pygame.mouse.get_pos()
                if pos[0] < 600:
                    if color == RED:
                        red_points.append(pos)
                    if color == GREEN:
                        green_points.append(pos)
                if pos[0] > 600 and pos[1] > 450:
                    switch_color()
            refresh(screen)
        display.update()