def __init__(self,
                 diameter=32,
                 left=20,
                 top=20,
                 imagefile='crystal.png',
                 number='x',
                 # None or milliseconds until crystal disappears on its own:
                 lifetime_millis_max=None,
                 play_buzzer_on_negative_score=True):
        # todo: options for start/fadeout/end times
        # todo: option for scoring-number
        VirtualGameSprite.__init__(self)  # call Sprite initializer
        self.gamediameter = diameter
        self.gamerect = pygame.Rect(left, top, diameter, diameter)
        self.update_rect()
        self.image = load_image(
            imagefile,
            (self.rect.width, self.rect.height),
            convert_alpha=True)
        self.number = number
        self.visible = 0
        self.active = False
        self.pickup_sound = load_sound('ring_inventory.wav')
        self.pickup_sound_negative = load_sound('prompt_error.wav')
        self.flashing = False
        self.flashing_counter = 0

        # max time this crystal remains active
        self.lifetime_millis_max = lifetime_millis_max
        # current elapsed millis this crystal has been active
        self.lifetime_millis_elapsed = 0

        self.play_buzzer_on_negative_score = play_buzzer_on_negative_score
Beispiel #2
0
def main():
#Initialize Everything

    pygame.init()
    Sounds.whiff = load_sound('whiff.wav')
    Sounds.punch = load_sound('punch.wav')
    Sounds.boom = load_sound('boom.wav')
    Sounds.cosmic = load_sound('secosmic_lo.wav')

    screen = pygame.display.set_mode(GRIDDIM * FIELDSIZE + Vec2d(2,2)
            )#, pygame.FULLSCREEN)
    pygame.display.set_caption('Open Real Time Chess')
    #pygame.mouse.set_visible(0)

#Create The Backgound
    background = pygame.Surface(screen.get_size())
    background = background.convert()

#Prepare Game Objects
    clock = pygame.time.Clock()
    board, allsprites, ai = new_game(background)

#Main Loop
    while True:
        clock.tick(60)

    #Handle Input Events
        for event in pygame.event.get():
            if event.type == QUIT:
                return
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                return
            elif event.type == KEYDOWN and event.key == K_r and board.winner is not None:
                board, allsprites, ai = new_game(background, ai)
            elif event.type == MOUSEBUTTONDOWN:
                board.handle_click(pygame.mouse.get_pos())

        allsprites.update(board)

    #Draw Everything
        screen.blit(background, (0, 0))
        board.redraw()
        allsprites.draw(screen)
        if board.winner is not None:
            draw_outlined_text(screen, background.get_rect().center,
                    "Player %s wins" % COLORNAMES[board.winner], 64,
                    3, (0,0,0), (255,0,0))
            draw_outlined_text(screen, Vec2d(0, 64) + background.get_rect().center,
                    "Press 'R' to continue or 'Esc' to quit", 24,
                    1, (255,255,255), (0,0,0))

        pygame.display.flip()

#Game Over
    ai.keep_running = False
Beispiel #3
0
 def __init__(me, title="Tetris", res=(800, 600)):
     pygame.display.set_caption(title)
     me.screen = pygame.display.set_mode(res)
     me.w, me.h = res
     me.font = resources.load_font(resources.font_menu)
     me.gameFont = resources.load_font(resources.font_game)
     me.eventkeys = {K_LEFT: 0, K_RIGHT: 0, K_UP: 0, K_DOWN: 0, K_RETURN: 0, K_ESCAPE: 0}  # used for one tap events
     me.keymap = {K_DOWN: 0}  # used for keys that can be held down
     me.sounds = {
         "ROT": resources.load_sound(resources.sound_rot, 0.5),
         "TOUCH": resources.load_sound(resources.sound_touch, 0.7),
         "CLEAR": resources.load_sound(resources.sound_clear, 0.8),
     }
     me.fullscreen = 0
     me.running = True
     me.states = []
     me.pushState(menu.Menu(me))
    def __init__(self, diameter=32, left=80, top=80):
        BasePowerup.__init__(self, diameter=diameter, left=left, top=top, maxduration=5.0)
        self.type = 'shield'
        self.gamerect = pygame.Rect(left, top, diameter, diameter)
        self.update_rect()
        self.image = load_image(
            'shield.png',
            (self.rect.width, self.rect.height),
            convert_alpha=True)
        self.image = pygame.transform.smoothscale(
            self.image, (self.rect.width, self.rect.height))

        self.sound_begin = load_sound('shield start.wav')
        self.sound_end = load_sound('shield end.wav')
        # these let me start the ending sound to end overlapping when the effect ends:
        self.sound_end_duration = self.sound_end.get_length() - 1.0
        self.sound_end_started = False
    def __init__(self, diameter=32, left=100, top=100):
        BasePowerup.__init__(self, diameter=diameter, left=left, top=top, maxduration=5.0)
        self.type = 'slow'
        self.gamerect = pygame.Rect(left, top, diameter, diameter)
        self.update_rect()
        self.image = load_image(
            'clock.png',
            (self.rect.width, self.rect.height),
            convert_alpha=True)

        self.sound_begin = load_sound('slow start.wav')
        self.sound_end = load_sound('slow end.wav')
        # these let me start the ending sound to end overlapping when the effect ends:
        self.sound_end_duration = self.sound_end.get_length() - 0.5
        self.sound_end_started = False

        self.speedfactor = 0.25
 def __init__(self, diameter=32, left=20, top=20):
     VirtualGameSprite.__init__(self)  # call Sprite initializer
     self.gamediameter = diameter
     self.gamerect = pygame.Rect(left, top, diameter, diameter)
     self.update_rect()
     self.image = load_image(
         'crystal.png',
         (self.rect.width, self.rect.height),
         convert_alpha=True)
     self.pickup_sound = load_sound('ring_inventory.wav')
    def __init__(
            self,
            diameter=64,
            position_list=[[20, 20]],
            sound='tone440.wav',
            image='triangle.png',
            input_key='K_1',
            showtimes_millis=[],
            showtimes_trigger_counts=[],
            timeout_millis=5000,
            stay_visible=False,
            score_pass=None,
            score_fail=None,
            score_miss=None,
            fail_on_wrong_key=False,
            pass_fail_sounds=False,
            **kwargs_extra):
        # if kwargs_extra: print 'extra arguments:', kwargs_extra
        VirtualGameSprite.__init__(self)  # call Sprite initializer
        self.gamediameter = diameter
        self.position_list = position_list
        self.position_index = -1
        left, top = self.position_list[self.position_index]
        self.gamerect_visible = pygame.Rect(left, top, diameter, diameter)
        self.gamerect_hidden = pygame.Rect(-9999, -9999, diameter, diameter)
        self.gamerect = self.gamerect_hidden
        self.update_rect()

        if not image or image == 'none':
            image = 'transparent.png'
        self.image = load_image(
            image,
            (self.rect.width, self.rect.height),
            convert_alpha=True)
        self.image_name = image

        if sound and sound != 'none':
            self.prompt_sound = load_sound(sound, mixing_group='reaction')
            self.sound_name = sound
        else:
            self.prompt_sound = NoneSound()
            self.sound_name = 'none'

        if pass_fail_sounds:
            self.pass_sound = load_sound('prompt_correct.wav', mixing_group='reaction')
            self.fail_sound = load_sound('prompt_error.wav', mixing_group='reaction')
        else:
            self.pass_sound = NoneSound()
            self.fail_sound = NoneSound()

        self.showtimes_millis = showtimes_millis
        # todo: implement trigger showing
        self.showtimes_trigger_counts = showtimes_trigger_counts
        if isinstance(timeout_millis, str) or isinstance(timeout_millis, str):
            timeout_millis = None
        self.timeout_millis = timeout_millis
        self.stay_visible = stay_visible
        self.score_pass = score_pass
        self.score_fail = score_fail
        self.score_miss = score_miss
        self.fail_on_wrong_key = fail_on_wrong_key
        self.active = False
        self.visible = False
        self.total_elapsed = 0
        self.showtime_last = 0  # millis when shown
        self.step_trigger_count_last = 0
        if input_key.startswith('K_MOUSE'):
            mousebutton_index = 0
            if input_key == 'K_MOUSE1':
                mousebutton_index = 0  # left mouse
            elif input_key == 'K_MOUSE2':
                mousebutton_index = 1  # middle mouse
            elif input_key == 'K_MOUSE3':
                mousebutton_index = 2  # right mouse
            else:
                raise QuitGame('mouse button for input_key for reaction prompt of %s is not recognized' % input_key)
                raise QuitGame()

            self.dismiss_test = lambda evt: evt.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[
                mousebutton_index]
        else:
            # input_key should correspond to actual key
            pygame_key_constant = getattr(pygame, input_key, None)
            if not pygame_key_constant:
                print('input_key of "%s" not found. Please use one of the following' % input_key)
                print(', '.join(['"' + s + '"' for s in list(CODE_BY_PYGAME_CONSTANT.keys())] + ['K_MOUSE1', 'K_MOUSE2',
                                                                                                 'K_MOUSE3']))
                raise QuitGame('input_key of "%s" not found. ' % input_key)
            self.dismiss_test = lambda evt: evt.type == pygame.KEYDOWN and evt.key == pygame_key_constant
Beispiel #8
0
def main():
    # Initialise constants
    leadTime = 2.0
    loadTime = 0.2
    thrustTime = 1.8
    torpedoTime = 2.0
    torpedoSpeed = 600

    # Initialise mixer
    pygame.mixer.pre_init(44100, -16, 2, 4096)

    # Initialise screen
    pygame.init()
    screen = pygame.display.set_mode((800,600))
    pygame.display.set_caption('Holy Diver')
    screenRect = screen.get_rect()
    
    # Initialise joysticks
    joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]
    map(lambda x: x.init(), joysticks)

    # Initialise game objects
    layers = world.Layers([1, 2, 3, 4, 5], [150,250,400,500,600])
    player1 = diver.Diver("right", "crescent", layers)
    player2 = diver.Diver("left", "cross", layers)
    
    # Initialise sounds
    pygame.mixer.init()
    bloopsound = resources.load_sound('bluop.wav')
    pewsound = resources.load_sound('PEW.wav')
    explodesound = resources.load_sound('PCHRR.wav')
    startsound = resources.load_sound('BADAM.wav')
    winsound = resources.load_sound('daDUN.wav')
    losesound = resources.load_sound('wawow.wav')

    pewChannel = pygame.mixer.find_channel()

    # Initialise sprites
    playersprite = pygame.sprite.Group((player1,player2))
    scoresprite = pygame.sprite.Group((player1.scorepanel,player2.scorepanel))
    torpedos1 = pygame.sprite.Group()
    torpedos2 = pygame.sprite.Group()
    torpedos = [None, None]
    torpedoPool = []
    explosions = pygame.sprite.Group()

    def newTorpedo(velocity, player):
        if len(torpedoPool) == 0:
            return torpedo.Torpedo(velocity,player,layers)
        else:
            t = torpedoPool.pop()
            t.reinit(velocity,player)
            return t

    # Fill background
    background = pygame.Surface(screen.get_size())
    background = background.convert()
    background.fill((0,0,0))
    layers.draw(background)

    splash, _ = resources.load_png("OpeningSplash.png")
    win_screen = {}
    win_screen['cross'], _ = resources.load_png("WinCross.png")
    win_screen['crescent'], _ = resources.load_png("WinCrescent.png")
    win_screen['draw'], _ = resources.load_png("Draw.png")

    # Blit everything to the screen
    screen.blit(background, (0, 0))
    pygame.display.flip()

    # Initialise clock
    clock = pygame.time.Clock()

    # Initialise torpedo timer
    timer = [-leadTime] # Length one array so it can be captured by closure

    def reset():
        player1.reinit()
        player2.reinit()
        torpedoPool.extend(torpedos1)
        torpedos1.empty()
        torpedoPool.extend(torpedos2)
        torpedos2.empty()
        explosions.empty()
        torpedos[0] = None
        torpedos[1] = None
        timer[0] = -leadTime

    state = "start"
    cinematic = False
    cin_timer = 0

    startsound.play()

    while 1:
        dt = clock.tick(1000) / 1000.0
        if state == "start":
            for event in pygame.event.get():
                if event.type == QUIT:
                    return
                elif event.type == KEYDOWN or event.type == JOYBUTTONDOWN:
                    state = "run"
            player1.setLife(3)
            player2.setLife(3)
            screen.blit(splash, (0,0))
        elif state == "run":
            if dt > 0.1:
                dt = 0.1

            if cinematic:
                cin_timer -= dt
                dt *= 0.05
                if cin_timer <= 0:
                    cinematic = False
                    reset()
                    if player2.lives <= 0:
                        if player1.lives > 0:
                            winner = player1.faction
                            winsound.play()
                            state = "end"
                        else:
                            winner = "draw"
                            losesound.play()
                            state = "end"
                    elif player1.lives <= 0:
                        winner = player2.faction
                        winsound.play()
                        state = "end"
                    continue
            else:
                mindist = 1000**2
                for t in torpedos1:
                    d = (t.rect.left - player2.rect.centerx - 23)**2 + (t.rect.centery - player2.rect.centery - 15)**2
                    if d < mindist:
                        mindist = d
                    d = (t.rect.left - player2.rect.centerx + 8)**2 + (t.rect.centery - player2.rect.centery - 15)**2
                    if d < mindist:
                        mindist = d
                for t in torpedos2:
                    d = (t.rect.right - player1.rect.centerx + 23)**2 + (t.rect.centery - player1.rect.centery - 15)**2
                    if d < mindist:
                        mindist = d
                    d = (t.rect.right - player1.rect.centerx - 8)**2 + (t.rect.centery - player1.rect.centery - 15)**2
                    if d < mindist:
                        mindist = d

                if mindist < 20**2:
                    dt *= 0.05
                elif mindist < 100**2:
                    dt *= 0.05 + 0.95 * (mindist - 20.0**2) / (100.0**2 - 20.0**2)

            for event in pygame.event.get():
                if event.type == QUIT:
                    return
                elif event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        reset()
                        state = "start"
                        continue
                    elif not cinematic:
                        if event.key == K_o:
                            player1.up()
                            #bloopsound.play()
                        elif event.key == K_l:
                            player1.down()
                            #bloopsound.play()
                        elif event.key == K_i:
                            player1.torpedoUp()
                        elif event.key == K_k:
                            player1.torpedoDown()
                        elif event.key == K_w:
                            player2.up()
                            #bloopsound.play()
                        elif event.key == K_s:
                            player2.down()
                            #bloopsound.play()
                        elif event.key == K_q:
                            player2.torpedoUp()
                        elif event.key == K_a:
                            player2.torpedoDown()
                elif event.type == JOYBUTTONDOWN:
                    if event.button == 6:
                        reset()
                        state = "start"
                        continue
                    elif not cinematic:
                        if event.joy == 0:
                            if event.button == 0:
                                player1.down()
                            elif event.button == 1:
                                player1.up()
                            elif event.button == 2:
                                player1.torpedoDown()
                            elif event.button == 3:
                                player1.torpedoUp()
                        elif event.joy == 1:
                            if event.button == 0:
                                player2.down()
                            elif event.button == 1:
                                player2.up()
                            elif event.button == 2:
                                player2.torpedoDown()
                            elif event.button == 3:
                                player2.torpedoUp()

            if not cinematic:
                timer[0] += dt

                if timer[0] >= loadTime or timer[0] < 0:
                    if torpedos[0] == None:
                        torpedos[0] = newTorpedo([-torpedoSpeed,0],player1)
                        torpedos1.add(torpedos[0])
                    if torpedos[1] == None:
                        torpedos[1] = newTorpedo([torpedoSpeed,0],player2)
                        torpedos2.add(torpedos[1])
                    if timer[0] >= thrustTime:
                        torpedos[0].power = 2
                        torpedos[1].power = 2
                        if not pewChannel.get_busy():
                            pewChannel.play(pewsound)
                        if timer[0] > torpedoTime:
                            torpedos[0].locked = False
                            torpedos[0] = None
                            torpedos[1].locked = False
                            torpedos[1] = None
                            timer[0] -= torpedoTime
                    elif timer[0] < 0:
                        torpedos[0].power = 0
                        torpedos[1].power = 0
                    else:
                        power = int((timer[0] - loadTime) * 2.0 / (thrustTime - loadTime))
                        torpedos[0].power = power
                        torpedos[1].power = power

            screen.blit(background, (0,0))

            torpedos1.update(dt)
            torpedos2.update(dt)

            delete = [t for t in torpedos1 if not t.rect.colliderect(screenRect)]
            for t in delete:
                torpedoPool.append(t)
                torpedos1.remove(t)
            delete = [t for t in torpedos2 if not t.rect.colliderect(screenRect)]
            for t in delete:
                torpedoPool.append(t)
                torpedos2.remove(t)

            playersprite.update(dt)

            collisions = pygame.sprite.spritecollide(player1,torpedos2,True,pygame.sprite.collide_mask)
            if collisions:
                for c in collisions:
                    explosions.add(explosion.Explosion(c.rect.midright))
                torpedoPool.extend(collisions)
                player1.markHit()
                if not cinematic:
                    explodesound.play()
                    cinematic = True
                    cin_timer = 2.0

            collisions = pygame.sprite.spritecollide(player2,torpedos1,True,pygame.sprite.collide_mask)
            if collisions:
                for c in collisions:
                    explosions.add(explosion.Explosion(c.rect.midleft))
                torpedoPool.extend(collisions)
                player2.markHit()
                if not cinematic:
                    explodesound.play()
                    cinematic = True
                    cin_timer = 2.0

            explosions.update(dt)

            playersprite.draw(screen)
            torpedos1.draw(screen)
            torpedos2.draw(screen)
            explosions.draw(screen)
            scoresprite.draw(screen)
        elif state == "end":
            for event in pygame.event.get():
                if event.type == QUIT:
                    return
                elif event.type == KEYDOWN or event.type == JOYBUTTONDOWN:
                    state = "start"
                    continue
            screen.blit(win_screen[winner], (0,0))

        pygame.display.flip()