示例#1
0
文件: rock.py 项目: elxw/snowyslopes
def init():
    Penguin.image = load.load_image("penguin")
    Rock.image = load.load_image("rock")
    Rock.explosionImages = []
    Rock.explosionImages.append(load.load_image("destructed rock"))
    Rock.explosionImages.append(load.load_image("destructed rock 1"))
    Rock.explosionImages.append(load.load_image("destructed rock 2"))
示例#2
0
文件: enemies.py 项目: Babulu/Kirby
 def loadImage(self):
     self.bird1 = load.load_image("bird1.png")
     self.bird2 = load.load_image("bird2.png")
     self.bird3 = load.load_image("bird3.png")
     self.bird4 = load.load_image("bird4.png")
     self.bird5 = load.load_image("bird5.png")
     self.bird = [self.bird1, self.bird2, self.bird3,
                  self.bird4, self.bird5]
示例#3
0
    def test_flip_sprite(self):
        surfaces = [load_image("assets/buttons/button1.png"),
                    load_image("assets/buttons/button2.png")]

        sprite_list = Sprite()
        sprite_list.images = [item for item in surfaces]

        sprite_dict = Sprite()
        sprite_dict.images = {key: surfaces[key] for key in
                              range(len(surfaces))}

        sprite_list = flip_sprite(sprite_list, 1, 0)
        self.assertIsInstance(sprite_list, Sprite)
        for image, rect in sprite_list.images:
            index = sprite_list.images.index((image, rect))
            self.assertEqual(rect, surfaces[index][1])

            width, height = image.get_size()
            pixel_array_base = pygame.PixelArray(surfaces[index][0])
            pixel_array_flip = pygame.PixelArray(image)
            for column in range(width - 1, -1, -1):
                for row in range(height):
                    self.assertEqual(pixel_array_base[column, row],
                                     pixel_array_flip[width - 1 - column, row])

        sprite_dict = Sprite()
        sprite_dict.images = {key: surfaces[key]
                              for key in range(len(surfaces))}

        sprite_dict = flip_sprite(sprite_dict, 0, 1)
        self.assertIsInstance(sprite_dict, Sprite)
        for key in sprite_dict.images:
            image, rect = sprite_dict.images[key]
            self.assertEqual(rect, surfaces[key][1])

            width, height = image.get_size()
            pixel_array_base = pygame.PixelArray(surfaces[key][0])
            pixel_array_flip = pygame.PixelArray(image)
            for column in range(width):
                for row in range(height - 1, -1, -1):
                    self.assertEqual(pixel_array_base[column, row],
                                     pixel_array_flip[column,
                                                      height - 1 - row])

        sprite_with_image = Sprite()
        sprite_with_image.image, sprite_with_image.rect = surfaces[0]

        sprite_with_image = flip_sprite(sprite_with_image, 1, 1)
        self.assertIsInstance(sprite_with_image, Sprite)
        self.assertEqual(sprite_with_image.rect, surfaces[0][1])
        width, height = sprite_with_image.image.get_size()
        pixel_array_base = pygame.PixelArray(surfaces[0][0])
        pixel_array_flip = pygame.PixelArray(sprite_with_image.image)
        for column in range(width - 1, -1, -1):
            for row in range(height - 1, -1, -1):
                self.assertEqual(pixel_array_base[column, row],
                                 pixel_array_flip[width - 1 - column,
                                                  height - 1 - row])
示例#4
0
def init():
    Particle.imgs = []
    Particle.imgs.append(load.load_image("glow1"))
    Particle.imgs.append(load.load_image("glow2"))
    Particle.imgs.append(load.load_image("glow4"))
    Particle.imgs.append(load.load_image("squareglow"))

    if Particle.particleList == []: 
        Particle.makeParticles()
示例#5
0
文件: menu.py 项目: Babulu/Kirby
 def __init__(self):
     self.menu1 = load.load_image("menu1.png")
     self.menu2 = load.load_image("menu2.png")
     self.menu3 = load.load_image("menu3.png")
     self.menu = [self.menu1,self.menu2,self.menu3]
     self.instruction = load.load_image("instruction.png")
     self.index = 0
     self.start = False
     self.info = False
     self.menuSound = load.load_sound("menuDing.WAV")
     self.enter = False
示例#6
0
 def __init__(self):
     super().__init__()
     self.image, self.rect = load_image('ship.png', -1)
     self.original = self.image
     self.shield, self.rect = load_image('ship_shield.png', -1)
     self.screen = pygame.display.get_surface()
     self.area = self.screen.get_rect()
     self.rect.midbottom = (self.screen.get_width() // 2, self.area.bottom)
     self.radius = max(self.rect.width, self.rect.height)
     self.alive = True
     self.shieldUp = False
     self.vert = 0
     self.horiz = 0
示例#7
0
    def __init__(self, race, startRow, startCol,index):
        self.index = index
        self.resources = 50
        self.winSound = load.load_sound('Misc/YouWin.wav')
        if race == 'Protoss':
            nexus = ProtossBuildings.Nexus(startRow,startCol)
            Building.building.addTofinishedBuildings(nexus)
            ProtossUnit.Probe(startRow,startCol-1)
            ProtossUnit.Probe(startRow-1,startCol-1)
            ProtossUnit.Probe(startRow+1,startCol-1)
            ProtossUnit.Probe(startRow+2,startCol-1)
            ProtossUnit.Probe(startRow+3,startCol-1)
            self.xPos = 0
            self.yPos = 0
            self.Units = ProtossUnit.ProtossUnit.ProtossUnits
            self.Buildings = ProtossBuildings.ProtossBuilding.protossBuildings
            self.UntCls = ProtossUnit.ProtossUnit
            self.BldCls = ProtossBuildings.ProtossBuilding

            self.NoMineralSound = load.load_sound('Protoss/PAdErr00.wav')
            self.NoMoreSupplySound = load.load_sound('Protoss/PAdErr02.wav')

            MenuFile = 'Other/Menu/Protoss Menu.png'
            self.MenuImage = load.load_image(MenuFile)
        if race == 'Terran':
            cc = TerranBuildings.CommandCenter(startRow,startCol)
            Building.building.addTofinishedBuildings(cc)
            TerranUnit.SCV(startRow,startCol-1)
            TerranUnit.SCV(startRow-1,startCol-1)
            TerranUnit.SCV(startRow+1,startCol-1)
            TerranUnit.SCV(startRow+2,startCol-1)
            TerranUnit.SCV(startRow+3,startCol-1)
            self.xPos = 0
            self.yPos = 0
            self.Units = TerranUnit.TerranUnit.TerranUnits
            self.Buildings = TerranBuildings.TerranBuilding.terranBuildings

            self.UntCls = TerranUnit.TerranUnit
            self.BldCls = TerranBuildings.TerranBuilding

            self.NoMineralSound = load.load_sound('Terran/tadErr00.wav')
            self.NoMoreSupplySound = load.load_sound('Terran/tadErr02.wav')

            MenuFile = 'Other/Menu/Terran Menu.png'
            self.MenuImage = load.load_image(MenuFile)

        self.updateCurrentPopulation()
        self.updateCurrentPopulationAvaliable()
示例#8
0
def init(data):
    data.mode = 'start'
    data.modeCache = 'start'

    data.frameCount = 0


    data.ScreenWidth = data.screen.get_width()
    data.ScreenHeight = data.screen.get_height()
    data.map = map.map('fastest', 64, 64,scale = 1.5)
    data.cellWidth, data.cellHeight = data.map.getCellsize()


    data.buildings = Building.building.buildings
    Building.building.setMap(data.map)
    Unit.Unit.setMap(data.map)
    Unit.Unit.setScreen(data.screen)

    player1 = Player.player('Protoss', 8,9,0)
    player2 = Player.player('Terran', 53,51,1)

    pMPic = 'Other/PauseMenu.png'
    data.pauseMenu = load.load_image(pMPic)

    data.currentPlayer = player1
    data.otherPlayer = player2

    #MenuFile = 'Other/Menu/Protoss Menu.png'
    data.MenuImage = data.currentPlayer.MenuImage #load.load_image(MenuFile)
    Menu_h = data.MenuImage.get_height()
    data.MenuHeight = Menu_h

    PointerFile = 'Other/Pointer.png'
    data.pointerImage = load.load_image(PointerFile)
    #pygame.mouse.set_visible(False)
    data.AutoScrollWidth = 20

    data.ViewBox = Menu.ViewBox(data.map)

    data.buildMode = False
    data.placeMode = False
    data.currentBuildIndex = None
    data.currentBuildClass = None

    data.selected = None
    data.buttonStatus = [0]*9

    data.currentPlayer.drawFogOfWar()
示例#9
0
def test_aegan(aegan, prefix):
    import ipdb
    with ipdb.launch_ipdb_on_exception():
        aegan.load(prefix=prefix)

        from GAN.utils.vis import vis_grid
        vis_grid(inverse_transform(aegan.generator.random_generate(128)), (2, 20), 'random_generate.png')

        paths = map(lambda x: x.strip(), open('protocol/cuhk01-all.txt').readlines())
        from load import load_image
        sample = transform( np.array([load_image(path, (64, 128)) for path in paths[:128]]) )
        
        vis_grid(inverse_transform(sample), (2, 20), 'sample.png')
        vis_grid(inverse_transform(aegan.autoencoder.autoencoder.predict(sample)), (2, 20), 'reconstruct.png')

        import matplotlib
        matplotlib.use('Agg')
        import matplotlib.pyplot as plt
        codes = aegan.autoencoder.encoder.predict(sample)
#       codes = aegan.generator.sample(128)
#       codes = aegan.autoencoder.encoder.predict(aegan.generator.random_generate(128))

        for ind, code in enumerate(codes):
            n, bins, patches = plt.hist(code, 50, normed=1, facecolor='green', alpha=0.75)
            plt.savefig('test/{}.pdf'.format(ind))
            plt.clf()

    ipdb.set_trace()
示例#10
0
文件: powerup.py 项目: Babulu/Kirby
 def __init__(self,x,y):
     pygame.sprite.Sprite.__init__(self)
     self.potion = load.load_image("potion.png")
     self.sprite = block.Block(30,30)
     self.x = x
     self.y = y
     self.dead = False
示例#11
0
 def __init__ (self, position, velocity=(0, 0)):
     pygame.sprite.Sprite.__init__(self)
    
     self.position=pygame.math.Vector2(position)
     self.velocity=pygame.math.Vector2(velocity)
     self.image, self.rect=load.load_image("ball.png", -1)
     self.radius=self.rect.w/2
示例#12
0
def redrawAll(data):

    data.map.resetMap()
    #ProtossBuildings.ProtossBuilding.drawAllBuildings()
    Building.building.drawAllBuildings()
    Unit.Unit.drawAllUnits()
    data.map.draw(data.screen)
    data.map.drawFogOfWar(data.screen,data.currentPlayer.index)
    if isinstance(data.selected,Unit.Unit):
        if data.buildMode == False and data.placeMode == False:
            if data.selected.canMove:
                if data.buttonStatus[0] == 1:
                    data.selected.drawMoves((0,200,0,100))

            if data.selected.canAttack:
                if data.buttonStatus[1] == 1:
                    data.selected.drawAttack((200,0,0,100))
    #drawGrid(data)
    drawMenu(data)
    Menu.drawMenu(data.screen, data.selected, data)
    Menu.drawAllBuildingsOnMiniMap(data.screen,data)
    Menu.drawAllUnitsOnMiniMap(data.screen,data)
    data.map.drawFogOfWarOnMiniMap(data.screen,data.currentPlayer.index)
    data.ViewBox.draw()
    drawSelected(data)

    if data.mode == 'pause':
        data.screen.blit(data.pauseMenu,(180,150))
    elif data.mode == 'help':
        data.screen.blit(load.load_image('Other/Help.png'),(0,0))
    pygame.display.flip()
示例#13
0
文件: hud.py 项目: gshopov/Pyruto
    def __init__(self, type, capacity, player):
        """Initialize the animation images of the bar.
        Raise SystemExit if the bar type is not supported.

        position -- Vec2D variable, holds the topleft coordinates of
        the bar

        """
        pygame.sprite.Sprite.__init__(self)

        self.type = type
        self.capacity = self.value = capacity

        if player not in [1, 2]:
            raise SystemExit("player argument should be either 1 or 2")
        else:
            self.player = player

        self.position = Vec2D(0, 0)
        try:
            self.image, self.rect = load_image("assets/hud/" + self.type +
                                               ".png")
        except SystemExit:
            raise SystemExit("improper Bar type")

        self.update()
示例#14
0
文件: hud.py 项目: gshopov/Pyruto
    def __init__(self, player, character):
        """Initialize the health, mana bar, frame and icon.

        player -- should an integer value: 1 or 2
        character -- defines which icon will be shown

        If player == 2: all the components apart from the icon are flipped.

        """
        SpriteGroup.__init__(self)

        self.health = Bar("health", 1000, player)
        self.health.position = (self.measures[player]['position'] +
                                self.measures[player]['health'])

        self.mana = Bar("mana", 1000, player)
        self.mana.position = (self.measures[player]['position'] +
                              self.measures[player]['mana'])

        self.icon = Icon(character)
        self.icon.rotozoom(self.measures[player]['rotation'], 0.7)
        self.icon.position = (self.measures[player]['position'] +
                              self.measures[player]['icon'])

        self.frame = Sprite()
        self.frame.image, self.frame.rect = load_image("assets/hud/frame.png")
        self.frame.rect.topleft = self.measures[player]['position']

        self.add(self.health, self.mana, self.frame, self.icon)

        if player == 2:
            for sprite in self.sprites():
                if sprite != self.icon:
                    sprite.flip(1, 0)
示例#15
0
文件: menu.py 项目: elxw/snowyslopes
    def __init__(self, screen, gameSelection=False):
        self.screen = screen
        self.gameSelection = gameSelection
        self.font = load.load_font("Nexa Light", 40)
        self.timer = pygame.time.Clock()
        self.selection = 0
        self.bg = Surface((32, 32))
        self.titleImg = load.load_image("title")
        self.offset = 175
        self.mouse = pygame.mouse

        s = random.choice("01")
        self.snowing = int(s)
        if not self.snowing:
            r = random.choice("00000001")
            self.raining = int(r)
        else:
            self.raining = False
        self.rain = Rain()
        self.snow = Snow()

        # random trees
        self.numTrees = random.randint(10, 15)
        self.trees = pygame.sprite.Group()
        increment = SCREEN_WIDTH // self.numTrees
        for t in range(self.numTrees):
            # better random distribution
            x = random.randint(t * increment - 5, (t + 1) * increment + 5)
            img = int(random.choice("111223"))
            y = SCREEN_HEIGHT + random.randint(10, 60)
            tree = Tree(x, y, img)
            self.trees.add(tree)
示例#16
0
文件: icon.py 项目: gshopov/Pyruto
    def __init__(self, character_name=None, facing="RIGHT"):
        """
        Initialize the portray images, set the currently represented character
        to character_name or choose a random one from all available characters
        if character_name is None. Flip the portraits according to the facing
        argument.

        position -- Vec2D varible, holds the center position of the
        representation

        """
        pygame.sprite.Sprite.__init__(self)

        self.images = {character: load_image(path) for character in
                       get_all_characters() for path in
                       glob.glob("assets/characters/" + character +
                                 "/representations/representation0*")}

        self.position = Vec2D(0, 0)
        self.facing = facing

        if character_name is None:
            self.character = random.choice(list(self.images))
        else:
            self.character = character_name

        if self.facing == "LEFT":
            self.flip(1, 0)

        self.update()
示例#17
0
 def __init__(self, color):
     super().__init__()
     self.image, self.rect = load_image('space_invader_' + color + '.png',
                                        -1)
     self.initialRect = self.rect
     screen = pygame.display.get_surface()
     self.area = screen.get_rect()
     self.loc = 0
     self.radius = min(self.rect.width // 2, self.rect.height // 2)
示例#18
0
    def __init__(self, *, folder_name, img_name, pos = ( 0, 0 ) ):
        """
        Button constructor. The button must have graphics in both positions, up and down.

        :param folder_name: name of folder where button image is stored
        :param img_name: name of image
        """

        pg.sprite.Sprite.__init__(self) #call Sprite initializer

        self.img_dir = os.path.join(folder_name, img_name )
        self.image_down = load_image( self.img_dir + "_down.png" )[0]
        self.image_up = load_image( self.img_dir + "_up.png" )[0]

        self.image = self.image_up
        self.rect = self.image.get_rect( center = pos )

        self.pushed = 0
示例#19
0
文件: enemies.py 项目: Babulu/Kirby
 def __init__(self,x,y):
     pygame.sprite.Sprite.__init__(self)
     self.pikey1 = load.load_image("pikey1.png")
     self.pikey2 = load.load_image("pikey2.png")
     self.pikey = [self.pikey1,self.pikey1,self.pikey2,self.pikey2]
     self.frame = 0
     self.sprite = block.Block(19,19)
     self.x = x
     self.y = y
     self.y_i = y
     self.speed_x = 0
     self.speed_y = 3
     self.gravity = 0.3
     self.localGrab = False
     self.air = False
     self.dead = False
     self.v_x = 0
     self.v_y = 0
示例#20
0
    def __init__(self, image_path):
        self.image, self.rect = load_image(image_path)
        self.length = self.rect.width // self.rect.height
        self.tile_side = self.rect.height

        self.images = []
        for tile_index in range(self.length):
            tile_rect = pygame.Rect(tile_index * self.rect.height, 0,
                                    self.rect.height, self.rect.height)
            self.images.append(self.image.subsurface(tile_rect))
示例#21
0
 def __init__(self, kindof):
     super().__init__()
     self.image, self.rect = load_image(kindof + '_powerup.png', -1)
     self.original = self.image
     screen = pygame.display.get_surface()
     self.area = screen.get_rect()
     self.rect.midtop = (random.randint(
         self.area.left + self.rect.width // 2,
         self.area.right - self.rect.width // 2), self.area.top)
     self.angle = 0
示例#22
0
    def browse_photo(self, *args, **kwargs):
        dlg = QtGui.QFileDialog(self)
        dlg.setFileMode(QtGui.QFileDialog.AnyFile)
        self.tab3['img_path'] = str(
            dlg.getOpenFileName(dlg, "Wybierz obraz", '/home/santis/Pictures'))

        self.tab3['img_path'] = load_image(self.tab3['img_path'])
        self.photo_disp.setPixmap(QtGui.QPixmap(self.tab3['img_path']))
        # self.photo_disp.resize(100,100)
        self.photo_disp.show()
示例#23
0
文件: enemies.py 项目: Babulu/Kirby
 def __init__(self,x,y,dir):
     self.bullet = load.load_image("shotzoBullet.png")
     self.x = x+13
     self.y = y+5
     self.sprite = block.Block(6,6)
     # calculate the speed according to the input direction
     self.speed_x = 5*dir[0]/math.hypot(*dir)
     self.speed_y = 5*dir[1]/math.hypot(*dir)
     self.dead = False
     self.frame = 0
示例#24
0
文件: snow.py 项目: elxw/snowyslopes
 def __init__(self, speed, direction):
     super().__init__()
     self.image = pygame.transform.scale(load.load_image("snowflake"),
                                         (6, 6))
     self.yMax = SCREEN_HEIGHT
     self.speed = 3
     self.direction = direction
     self.coords = [random.random() * SCREEN_WIDTH, -10]
     self.rect = Rect(self.coords[0], self.coords[1],
                      self.image.get_width(), self.image.get_height())
示例#25
0
文件: enemies.py 项目: Babulu/Kirby
 def loadImage(self):
     self.waddleDee1 = load.load_image("waddleDee1.png")
     self.waddleDee2 = load.load_image("waddleDee2.png")
     self.waddleDee3 = load.load_image("waddleDee3.png")
     self.waddleDee4 = load.load_image("waddleDee4.png")
     self.waddleDee5 = load.load_image("waddleDee5.png")
     self.waddleDee1i = load.load_image("waddleDee1i.png")
     self.waddleDee2i = load.load_image("waddleDee2i.png")
     self.waddleDee3i = load.load_image("waddleDee3i.png")
     self.waddleDee4i = load.load_image("waddleDee4i.png")
     self.waddleDee5i = load.load_image("waddleDee5i.png")
     self.waddleDee = [self.waddleDee1,self.waddleDee1,
                       self.waddleDee2,self.waddleDee2,
                       self.waddleDee3,self.waddleDee3,
                       self.waddleDee4,self.waddleDee4]
     self.waddleDeei = [self.waddleDee1i,self.waddleDee1i,
                        self.waddleDee2i,self.waddleDee2i,
                        self.waddleDee3i,self.waddleDee3i,
                        self.waddleDee4i,self.waddleDee4i]
示例#26
0
def redrawAllForStartMenu(data,frameCount):
    backGroundName = 'Other/backGround.png'
    buttonName = 'Other/buttons.png'
    exitButtonName = 'Other/exitButton.png'
    backGround = load.load_image(backGroundName)
    buttons = load.load_image(buttonName)
    exitButton = load.load_image(exitButtonName)
    exitX = 960
    exitY = 960
    buttonsX = 960
    buttonsY = 75
    data.screen.blit(backGround,(0,0))
    eX = exitX
    eY = exitY
    bX = buttonsX
    bY = buttonsY
    if frameCount >= 6 :
        eX = exitX - frameCount * 25
        eY = exitY - frameCount * 25
        bX = buttonsX - frameCount * 22

    if eX <= 960 - 379:
        eX = 960 - 379
    if eY <= 960 - 222:
        eY = 960 - 222
    if bX <= 960 - 424:
        bX = 960 - 424
    data.screen.blit(buttons,(bX,bY))
    data.screen.blit(exitButton,(eX,eY))

    if data.mode == 'credits':
        data.screen.blit(load.load_image('Other/credits.png'),(0,0))
    elif data.mode == 'help':
        data.screen.blit(load.load_image('Other/Help.png'),(0,0))

    pygame.display.flip()

    for event in pygame.event.get():
        if (event.type == pygame.QUIT):
            pygame.quit()
            data.mode = 'quit'
示例#27
0
文件: enemies.py 项目: Babulu/Kirby
 def loadImage(self):
     self.waddleDoo1 = load.load_image("waddleDoo1.png")
     self.waddleDoo2 = load.load_image("waddleDoo2.png")
     self.waddleDoo3 = load.load_image("waddleDoo3.png")
     self.waddleDoo4 = load.load_image("waddleDoo4.png")
     self.waddleDoo5 = load.load_image("waddleDoo5.png")
     self.waddleDoo1i = load.load_image("waddleDoo1i.png")
     self.waddleDoo2i = load.load_image("waddleDoo2i.png")
     self.waddleDoo3i = load.load_image("waddleDoo3i.png")
     self.waddleDoo4i = load.load_image("waddleDoo4i.png")
     self.waddleDoo5i = load.load_image("waddleDoo5i.png")
     self.waddleDoo = [self.waddleDoo1,self.waddleDoo1,
                       self.waddleDoo2,self.waddleDoo2,
                       self.waddleDoo3,self.waddleDoo3,
                       self.waddleDoo4,self.waddleDoo4,
                       self.waddleDoo5,self.waddleDoo5]
     self.waddleDooi = [self.waddleDoo1i,self.waddleDoo1i,
                        self.waddleDoo2i,self.waddleDoo2i,
                        self.waddleDoo3i,self.waddleDoo3i,
                        self.waddleDoo4i,self.waddleDoo4i,
                        self.waddleDoo5i,self.waddleDoo5i]
示例#28
0
def feature(aegan, filename):
    import ipdb
    with ipdb.launch_ipdb_on_exception():
        aegan.load(prefix='./samples/reid_aegan/aegan/50')

        paths = map(lambda x: x.strip(),
                    open('protocol/cuhk01-all.txt').readlines())
        x = transform(np.array([load_image(path, (64, 128))
                                for path in paths]))
        code = aegan.autoencoder.encoder.predict(x)

    ipdb.set_trace()
示例#29
0
 def __init__(self, x, y, type):
     Entity.__init__(self)
     self.type = type
     # loads image based on the type of platform
     imgName = "terrain" + str(self.type)
     self.image = pygame.transform.scale(load.load_image(imgName),
                                         (1024, 607))
     self.hitmask = pygame.surfarray.array_alpha(self.image)
     self.mask = pygame.mask.from_surface(self.image)
     self.height = self.image.get_height()
     self.width = self.image.get_width()
     self.rect = Rect(x, y, self.image.get_width(), self.image.get_height())
     self.getPlatformHeight()
示例#30
0
文件: hud.py 项目: gshopov/Pyruto
    def __init__(self):
        """Initialize all attributes and start the timer."""
        SpriteGroup.__init__(self)

        self.time = 0
        self.seconds = 0
        self.position = Vec2D(0, 0)
        self.images = [load_image(path) for path in
                       glob.glob("assets/timer/*")]

        self.first_digit = Sprite()
        self.second_digit = Sprite()
        self.third_digit = Sprite()
        self.add(self.first_digit, self.second_digit, self.third_digit)
示例#31
0
文件: powerup.py 项目: Babulu/Kirby
 def __init__(self,x,y):
     pygame.sprite.Sprite.__init__(self)
     self.spark = load.load_image("powerup.png")
     self.sprite = block.Block(30,30)
     self.x = x
     self.y = y
     self.y_i = y
     self.speed_x = random.random()*2+3
     self.speed_y = random.random()*2+3
     self.dead = False
     self.time = 0
     self.localGrab = False
     self.v_x = 0
     self.v_y = 0
     self.start = False
示例#32
0
文件: kirby.py 项目: Babulu/Kirby
 def loadSpark(self):
     self.spark1 = load.load_image("spark1.png")
     self.spark2 = load.load_image("spark2.png")
     self.spark3 = load.load_image("spark3.png")
     self.sparkle1 = load.load_image("sparkle1.png")
     self.sparkle2 = load.load_image("sparkle2.png")
     self.sparkle3 = load.load_image("sparkle3.png")
     self.spark = [self.spark1,self.spark2,self.spark3]
     self.sprite = block.Block(16,16)
     self.sprite_spark = block.Block(60,60)
示例#33
0
def decoder(input_image, output_file):
    image = load_image(input_image)
    red = image.split()[0]
    width, height = image.size

    decoded_image = Image.new("RGB", (width, height))
    pix_val = decoded_image.load()

    for i in range(width):
        for j in range(height):
            if bin(red.getpixel((i, j)))[-1] == '0':
                pix_val[i, j] = (0, 0, 0)
            else:
                pix_val[i, j] = (255, 255, 255)

    save_image(decoded_image, output_file)
示例#34
0
文件: enemies.py 项目: Babulu/Kirby
 def __init__(self,x,y):
     pygame.sprite.Sprite.__init__(self)
     self.shotzo1 = load.load_image("shotzo1.png")
     self.shotzo2 = load.load_image("shotzo2.png")
     self.shotzo3 = load.load_image("shotzo3.png")
     self.shotzo4 = load.load_image("shotzo4.png")
     self.shotzo5 = load.load_image("shotzo5.png")
     self.shotzo6 = load.load_image("shotzo6.png")
     self.shotzo7 = load.load_image("shotzo7.png")
     self.bullet = load.load_image("shotzoBullet.png")
     self.shotzo = [self.shotzo1, self.shotzo2, self.shotzo6,
                    self.shotzo7, self.shotzo4]
     self.sprite1 = block.Block(20,20)
     self.x = x
     self.y = y
     self.x2 = self.x
     self.y2 = self.y
     self.frame = 0
     self.dir = (0,0)
示例#35
0
def main():
    pygame.init()
    screen = pygame.display.set_mode(DISPLAY, FLAGS, DEPTH)
    pygame.display.set_caption("Snowy Slopes")
    pygame.display.set_icon(load.load_image("sledderFullsize"))

    init()
    timer = pygame.time.Clock()

    while True:
        timer.tick(60)
        selection = Menu(screen).run()
        if selection == Menu.NEWGAME:
            selection = Menu(screen, gameSelection=True).run()
            if selection == Menu.GAME:
                score = Game(screen, timer).run()
            elif selection == Menu.DRAW:
                numPlatforms = Draw(screen).run()
                if isinstance(numPlatforms, list):
                    platformType = numPlatforms
                    score = Game(screen, timer, custom=platformType).run()
                elif isinstance(numPlatforms, int):
                    score = Game(screen, timer, custom=numPlatforms).run()
                else:
                    main()
            elif selection == Menu.BACK:
                main()
        elif selection == Menu.HELP:
            Help(screen, timer).run()
            score = Game(screen, timer).run()
        elif selection == Menu.QUIT:
            pygame.quit()
            sys.exit()

        # runs after game is over
        newSelection = GameOver(screen, score).run()
        if newSelection == GameOver.QUIT:
            pygame.quit()
            sys.exit()
        elif newSelection == GameOver.REPLAY:
            main()  # resets the game
示例#36
0
def encoder (input_file, output_file, message):
    image = load_image(input_file)
    red, green, blue = image.split()
    (width, height) = image.size

    message_image = convert_message_image(message, image.size)
    image_bw = message_image.convert('1')

    encoded_image = Image.new("RGB", (width, height))
    pix_val = encoded_image.load()
    for i in range(width):
        for j in range(height):
            red_pix = bin(red.getpixel((i, j)))
            message_pix = bin(image_bw.getpixel((i, j)))
            if message_pix[-1] == '1':
                red_pix = red_pix[:-1] + '1'
            else:
                red_pix = red_pix[:-1] + '0'
            pix_val[i, j] = (int(red_pix,2), green.getpixel((i, j)), blue.getpixel((i, j)))

    save_image(encoded_image, output_file)
示例#37
0
    def run(self):
        self.done = False
        while not self.done:
            # draw the background
            self.bg.convert()
            self.bg.fill(Color(208, 229, 246))
            for y in range(32):
                for x in range(32):
                    self.screen.blit(self.bg, (x * 32, y * 32))
            # draw the trees
            for tree in self.trees:
                self.screen.blit(tree.image, tree.rect)
            # draw the help screen
            help = (load.load_image("help image"))
            self.screen.blit(help, (0, 0))
            pygame.display.flip()

            self.timer.tick(60)

            for e in pygame.event.get():
                if e.type == KEYDOWN:
                    main()
示例#38
0
文件: sprite.py 项目: gshopov/Pyruto
    def __init__(self, path, update_speed):
        """
        path -- path to the directory, containing the images
        update_speed -- value, which means how many times per secound should
        the sprite be updated

        Initialize images, animation speed and the masks of the images - used
        for pixel collision.

        """
        pygame.sprite.Sprite.__init__(self)

        self.images = [load_image(file_name) for file_name in glob.glob(path)]
        self.masks = [pygame.mask.from_surface(image[0])
                      for image in self.images]

        self.start = pygame.time.get_ticks()
        self.delay = 1000 / update_speed
        self.last_update = 0
        self.current_frame = -1
        self.max_frame = len(self.images) - 1
        self.done = False
示例#39
0
文件: button.py 项目: gshopov/Pyruto
    def __init__(self, label, position=Vec2D(0, 0)):
        """Initialize all attributes and run the initial update.
        Changes in the font may cause a label that was fitting the button
        to not do so anymore.

        """
        pygame.sprite.Sprite.__init__(self)

        self.font = freetype.Font("assets/fonts/real.ttf", 20)
        self.label = label
        self.label_color = (255, 255, 255)
        self.label_rect = self.font.get_rect(self.label)

        self.images = [load_image(path) for path in
                       glob.glob("assets/buttons/button*")]

        self.position = position
        if not isinstance(self.position, Vec2D):
            self.position = Vec2D(self.position)

        self.is_flagged = False

        self.update()
示例#40
0
 def __init__(self, screen, score=0):
     self.screen = screen
     self.font = load.load_font("Nexa Light", 40)
     self.titleFont = load.load_font("Nexa Bold", 50)
     self.score = score
     message = "YOUR SCORE WAS " + str(int(self.score))
     self.gameover = load.load_image("game over")
     self.title = self.titleFont.render(message, True, (255, 255, 255))
     self.done = False
     self.bg = Surface((32,32))
     self.selection = 0
     self.timer = pygame.time.Clock()
      # random trees
     self.numTrees = random.randint(10, 15)
     self.trees = pygame.sprite.Group()
     increment = SCREEN_WIDTH//self.numTrees
     for t in range(self.numTrees):
         # better random distribution
         x = random.randint(t*increment-5, (t+1)*increment+5) 
         img = int(random.choice("11123"))
         y = SCREEN_HEIGHT + random.randint(10, 60)
         tree = Tree(x, y, img)
         self.trees.add(tree)
示例#41
0
文件: icon.py 项目: gshopov/Pyruto
    def __init__(self, character_name):
        """Initialize the icons of the character and the flags:

        p1_flag -- bool varibale, which says if player 1 has
        flagged the icon

        p2_flag -- bool variable, which says if player 2 has
        flagged the icon

        position -- Vec2D variable, holds the topleft coordinates of
        the icon

        """
        pygame.sprite.Sprite.__init__(self)

        self.images = [load_image(file_path) for file_path in
                       glob.glob("assets/characters/" + character_name +
                                 "/icons/*")]
        self.position = Vec2D(0, 0)

        self.p1_flag = False
        self.p2_flag = False

        self.update()
示例#42
0
文件: rock.py 项目: elxw/snowyslopes
 def explode(self, num):
     self.image = load.load_image("destructed penguin1")
示例#43
0
文件: enemies.py 项目: Babulu/Kirby
 def loadImage(self):
     self.flame1 = load.load_image("flame1.png")
     self.flame2 = load.load_image("flame2.png")
     self.flame3 = load.load_image("flame3.png")
     self.flame4 = load.load_image("flame4.png")
     self.flame5 = load.load_image("flame5.png")
     self.flame6 = load.load_image("flame6.png")
     self.flame7 = load.load_image("flame7.png")
     self.flame8 = load.load_image("flame8.png")
     self.flame9 = load.load_image("flame9.png")
     self.flame10 = load.load_image("flame10.png")
     self.flame11 = load.load_image("flame11.png")
     self.flame12 = load.load_image("flame12.png")
     self.flame_a = [self.flame1,self.flame2,self.flame3,self.flame4]
     self.flame_b = [self.flame5,self.flame6,self.flame7,self.flame8]
     self.flame_c = [self.flame9,self.flame10,self.flame11,self.flame12]
示例#44
0
def init():
    Player.image = load.load_image("sledder")
示例#45
0
def init():
    Coin.image = load.load_image("coin")
示例#46
0
 def drawUnfinishedBuilding(self):
     scale = min(self.sizeCol, self.sizeRow)/2.0
     unfinishedBuildingImage = load.load_image('Buildings/Protoss/ProtossCore.png',scale = scale)
     ProtossBuilding.unfinishedBuildingImage = unfinishedBuildingImage
     super(ProtossBuilding, self).drawUnfinishedBuilding(unfinishedBuildingImage)
     ProtossBuilding.protossBuildings.append(self)
示例#47
0
文件: main.py 项目: USMAnss/Pybrawl
def playGame(character1, character2):
    pygame.init()
    pygame.mixer.init()
    pygame.mixer.music.load("Sound/07 - The Raising Fighting Spirit.ogg") #Background music "The Rising Fighting Spirit":http://downloads.khinsider.com/game-soundtracks/album/naruto-original-soundtrack-1
    pygame.mixer.music.play(-1)
    displaysurf = pygame.display.set_mode((WIDTH, HEIGHT))
    clock = pygame.time.Clock()
    player1=Character(PLAYER1_CONTROLS, IMAGES[character1], SOUNDS[character1], PLAYER1_POSITION)
    player2=Character(PLAYER2_CONTROLS, IMAGES[character2], SOUNDS[character2], PLAYER2_POSITION)
    HUD1_IMAGES=HUD_IMAGES.copy()
    HUD1_IMAGES["icon"]=IMAGES[character1]["icon"]
    HUD2_IMAGES=HUD_IMAGES.copy()
    HUD2_IMAGES["icon"]=IMAGES[character2]["icon"]
    player1_hud=Hud(HUD1_IMAGES, LEFT_HUD_POSITION)
    player2_hud=Hud(HUD2_IMAGES, RIGHT_HUD_POSITION)
    player2_hud.flip()
    background=load_image("Background/training_background.png") #http://spritedatabase.net/game/1889
    background=pygame.transform.scale(background, (WIDTH, HEIGHT))
    player1_wins=load_image("Background/player1wins.png") #Used the folowing website to generate the win signs: http://www.dafont.com/ninja-naruto.font
    player2_wins=load_image("Background/player2wins.png")
    pygame.display.set_caption('Pybrawl')
    game_over=False
    while True: # main game loop
        displaysurf.blit(background, (0,0))
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN and event.key == K_RETURN and game_over:
                return

        if player1.health==0:
            game_over=True
            pygame.mixer.music.stop()
            displaysurf.blit(player2_wins, (172, 200))

        if player2.health==0:
            game_over=True
            pygame.mixer.music.stop()
            displaysurf.blit(player1_wins, (172, 200))

        keys_status=pygame.key.get_pressed()
        if game_over:
            keys_status=[False for i in keys_status]

        player1.update(keys_status)
        player2.update(keys_status)

        collide(player1, player2)

        keep_inside(player1)
        keep_inside(player2)

        if player1.rect.centerx < player2.rect.centerx:
            player1.direction="right"
            player2.direction="left"
        else:
            player1.direction="left"
            player2.direction="right"

        player1_hud.update(player1.health/player1.max_health,
                           player1.mana/player1.max_mana)
        player2_hud.update(player2.health/player2.max_health,
                           player2.mana/player2.max_mana)

        player1.draw(displaysurf)
        player2.draw(displaysurf)
        player1_hud.draw(displaysurf)
        player2_hud.draw(displaysurf)
        pygame.display.update()
示例#48
0
    def draw(self):
        self.bg.convert()
        if not self.pause:
            self.bgTime += 1
        if self.bgTime + 1 == self.totalGameTime:
            print(self.player.rect.right // 1024)
            self.exit = False
            self.bgTime += 1  # avoid an endless loop
            self.setGameOver("Time's Up! Press ENTER to exit.")

        if self.bgTime % 5 == 0:
            if self.darkening or self.lightening or self.raining:
                self.bgColor = self.rainSky()
            else:
                self.bgColor = self.getTimeColor()

        color = (self.bgColor[0], self.bgColor[1], self.bgColor[2])
        try:
            self.bg.fill(color)
        except:
            self.bg.fill((59, 82, 119))

        # blit the background
        for y in range(32):
            for x in range(32):
                self.screen.blit(self.bg, (x * 32, y * 32))

        # draw the sun based on "time of day"
        sun = pygame.transform.scale(load.load_image("sun"), (150, 150))
        if 50 + (SCREEN_HEIGHT) * (self.bgTime / self.totalGameTime) <= 400:
            self.screen.blit(sun, (SCREEN_WIDTH - 150 - 50 *
                            (self.bgTime / self.totalGameTime),
                     50 + (SCREEN_HEIGHT) * (self.bgTime / self.totalGameTime)))

        if abs((50 + (SCREEN_HEIGHT) * (self.bgTime / self.totalGameTime))
                - 250) <= 2:
            self.sundownTime = self.bgTime

        # draw game entities
        for tree in self.trees:
            self.screen.blit(tree.image, self.camera.apply(tree))
        for e in self.entities:
            self.screen.blit(e.image, self.camera.apply(e))
        for ice in self.ice:
            self.screen.blit(ice.image, self.camera.apply(ice))
        for rock in self.rocks:
            self.screen.blit(rock.image, self.camera.apply(rock))
        for bird in self.birds:
            self.screen.blit(bird.image, self.camera.apply(bird))
        for coin in self.coins:
            self.screen.blit(coin.image, self.camera.apply(coin))

        self.scoreSprite.draw(self.screen)
        clouds.draw(self.screen)
        player.drawMessage(self.screen)

        if self.snowing:
            self.snow.draw(self.screen)

        self.checkForRain()

        particles.draw(self.screen, self.camera)

        # Draw game info
        font = load.load_font("Nexa Light", 30)
        fps = font.render("FPS: " + str(int(self.timer.get_fps())),
                          True, Game.textColor)
        speed = font.render("Speed: " + str(int(self.groundSpeed)),
                            True, Game.textColor)
        if self.showFPS:
            self.screen.blit(fps, (50, 60))
        self.screen.blit(speed, (SCREEN_WIDTH - 200, 30))
        timeLeft = "Time Left: "
        timer = font.render(timeLeft, True, Game.textColor)
        rect = timer.get_rect()
        rect.right = int(self.screen.get_rect().centerx)
        rect.top = 30
        self.screen.blit(timer, rect)
        time = font.render(str(self.totalGameTime - self.bgTime),
                           True, Game.textColor)
        rect = time.get_rect()
        rect.left = int(self.screen.get_rect().centerx)
        rect.top = 30
        self.screen.blit(time, rect)

        if self.gameover:
            if self.exit == False:  # when time runs out
                self.pause = True
                self.screen.blit(self.gameover_image, self.gameover_rect)
            else:
                self.done = True

        pygame.display.update()
示例#49
0
    def run(self):
        self.done = False
        self.resetScreen()
        while not self.done:
            self.screen.fill(self.bgColor)

            if self.selectionMode:
                title = load.load_image("drawing mode")
                self.screen.blit(title, (0, 20))
                self.makeButtons("NEW DRAWING", Draw.NEW)
                self.makeButtons("LOAD DRAWINGS", Draw.LOAD)
                self.makeButtons("BACK", Draw.BACK)
                for tree in self.trees:
                    self.screen.blit(tree.image, tree.rect)

            if self.drawingMode:
                font = load.load_font("Nexa Bold", 20)
                self.screen.blit(load.load_image("instructions"), (100, 0))

                # guide dots
                pygame.draw.circle(self.screen, (159, 194, 252),
                                   (3, SCREEN_HEIGHT * 2 // 5 + 20), 5)
                # the screen_height*2//5 is used in platform also so change
                pygame.draw.circle(
                    self.screen, (159, 194, 252),
                    (SCREEN_WIDTH - 3, SCREEN_HEIGHT * 2 // 5 + 20), 5)

                pygame.draw.circle(self.screen, (236, 247, 255),
                                   (self.mouse.get_pos()), 5)
                if self.renderLine:
                    self.render()

                self.canvas.convert_alpha()
                self.screen.convert_alpha()
                self.screen.blit(self.canvas, (0, 0))
                if self.numDrawings >= 1:
                    color = Draw.TEXTCOLOR
                else:
                    color = (250, 250, 255)
                self.screen.blit(
                    font.render(
                        str(self.numDrawings) + " drawings saved", True,
                        color), (SCREEN_WIDTH - 200, SCREEN_HEIGHT - 30))

            if self.loadMode:
                if self.findingImages:
                    for drawing in range(1, 10):
                        try:
                            name = "terrain" + str(drawing * 100)
                            img = pygame.transform.scale(
                                load.load_image(str(name)), (200, 119))
                            self.terrains.append(img)
                        except:
                            # no more platform images
                            self.findingImages = False

                for i in range(len(self.terrains)):
                    x = 240 + (245 * (i % 3))
                    y = 200 * (i // 3)
                    width = 200
                    height = 119
                    rect = Rect(x - 200, y, width, height)
                    self.screen.blit(self.terrains[i], rect)

                help = self.font.render("Click to select platforms", True,
                                        Draw.TEXTCOLOR)
                help2 = self.font.render("Press P to play", True,
                                         Draw.TEXTCOLOR)
                self.screen.blit(help, (175, SCREEN_HEIGHT - 150))
                self.screen.blit(help2, (250, SCREEN_HEIGHT - 100))

            pygame.display.update()
            left_pressed, middle_pressed, right_pressed = mouse.get_pressed()

            self.timer.tick(60)
            for e in pygame.event.get():
                if e.type == QUIT:
                    pygame.quit()
                    sys.exit()
                if self.selectionMode:
                    if e.type == KEYDOWN:
                        if e.key == K_UP:
                            self.selection -= 1
                            if self.selection < 0:
                                self.selection = 0
                        if e.key == K_DOWN:
                            self.selection += 1
                            if self.selection > Draw.BACK:
                                self.selection = Draw.BACK
                            if self.selection < 0:
                                self.selction = 0
                        if e.key == K_RETURN:
                            self.selectionMode = False
                            if self.selection == 0:
                                self.drawingMode = True
                            elif self.selection == 1:
                                self.loadMode = True
                            else:
                                self.done = True

                if self.drawingMode:
                    if left_pressed:
                        pygame.draw.circle(self.canvas, self.slopeColor,
                                           pygame.mouse.get_pos(), 2)
                        self.points.append((pygame.mouse.get_pos()[0],
                                            pygame.mouse.get_pos()[1] - 5))

                    elif e.type == KEYDOWN and e.key == K_r:
                        self.renderLine = not self.renderLine
                    elif e.type == KEYDOWN and e.key == K_p:
                        self.done = True
                    elif e.type == KEYDOWN and (e.key == K_s):
                        if self.points != [] and self.renderLine:
                            # can't save empty drawing or dots
                            self.filename = ("terrain%s.png" % (str(
                                (self.numDrawings + 1) * 100)))
                            pygame.image.save(self.canvas, self.filename)
                            self.numDrawings += 1
                            # num drawings only increases after a save
                            print("file %s has been saved" %
                                  str(self.filename))
                    elif e.type == KEYDOWN and e.key == K_n:
                        self.resetScreen()

                if self.loadMode:
                    # this feature is mostly for demo purposes
                    if left_pressed:
                        if 20 < pygame.mouse.get_pos()[1] < 120:
                            if 40 < pygame.mouse.get_pos()[0] < 220:
                                if "1" not in self.platforms:
                                    self.platforms.append("1")
                            elif 240 < pygame.mouse.get_pos()[0] < 460:
                                if "2" not in self.platforms:
                                    self.platforms.append("2")
                            elif pygame.mouse.get_pos()[0] > 520:
                                if "3" not in self.platforms:
                                    self.platforms.append("3")
                        if 220 < pygame.mouse.get_pos()[1] < 320:
                            if 40 < pygame.mouse.get_pos()[0] < 220:
                                if "4" not in self.platforms:
                                    self.platforms.append("4")
                            elif 240 < pygame.mouse.get_pos()[0] < 460:
                                if "5" not in self.platforms:
                                    self.platforms.append("5")
                            elif pygame.mouse.get_pos()[0] > 520:
                                if "6" not in self.platforms:
                                    self.platforms.append("6")
                    elif e.type == KEYDOWN and e.key == K_p:
                        if self.platforms != []:
                            self.done = True

                    for num in self.platforms:
                        if int(num) > len(self.terrains):
                            self.platforms.remove(num)
        if self.drawingMode:
            return self.numDrawings
        elif self.loadMode:
            return self.platforms
        else:
            return None
示例#50
0
def main():
    # Initialize everything
    pygame.mixer.pre_init(11025, -16, 2, 512)
    pygame.init()
    screen = pygame.display.set_mode((500, 500))
    pygame.display.set_caption('Shooting Game')
    pygame.mouse.set_visible(0)

# Create the background which will scroll and loop over a set of different
# size stars
    background = pygame.Surface((500, 2000))
    background = background.convert()
    background.fill((0, 0, 0))
    backgroundLoc = 1500
    finalStars = deque()
    for y in range(0, 1500, 30):
        size = random.randint(2, 5)
        x = random.randint(0, 500 - size)
        if y <= 500:
            finalStars.appendleft((x, y + 1500, size))
        pygame.draw.rect(
            background, (255, 255, 0), pygame.Rect(x, y, size, size))
    while finalStars:
        x, y, size = finalStars.pop()
        pygame.draw.rect(
            background, (255, 255, 0), pygame.Rect(x, y, size, size))

# Display the background
    screen.blit(background, (0, 0))
    pygame.display.flip()

# Prepare game objects
    speed = 1.5
    MasterSprite.speed = speed
    alienPeriod = 60 / speed
    clockTime = 60  # maximum FPS
    clock = pygame.time.Clock()
    ship = Ship()                                       #sprites의 ship 클래스를 넣는다
    initialAlienTypes = (Siney,Oneeye, Spikey,Eye)
    powerupTypes = (BombPowerup, ShieldPowerup)

    # Sprite groups
    alldrawings = pygame.sprite.Group()
    allsprites = pygame.sprite.RenderPlain((ship,))
    MasterSprite.allsprites = allsprites
    Alien.pool = pygame.sprite.Group(
        [alien() for alien in initialAlienTypes for _ in range(5)])
    Alien.active = pygame.sprite.Group()
    Missile.pool = pygame.sprite.Group([Missile() for _ in range(10)])
    Missile.active = pygame.sprite.Group()
    Explosion.pool = pygame.sprite.Group([Explosion() for _ in range(10)])
    Explosion.active = pygame.sprite.Group()
    bombs = pygame.sprite.Group()
    powerups = pygame.sprite.Group()

    # Sounds
    missile_sound = load_sound('missile.ogg')
    bomb_sound = load_sound('bomb.ogg')
    alien_explode_sound = load_sound('alien_explode.ogg')
    ship_explode_sound = load_sound('ship_explode.ogg')
    load_music('music_loop.ogg')

    alienPeriod = clockTime // 2
    curTime = 0
    aliensThisWave, aliensLeftThisWave, Alien.numOffScreen = 10, 10, 10
    wave = 1
    bombsHeld = 3
    score = 0
    missilesFired = 0
    powerupTime = 10 * clockTime
    powerupTimeLeft = powerupTime
    betweenWaveTime = 3 * clockTime
    betweenWaveCount = betweenWaveTime
    font = pygame.font.Font(None, 36)

    inMenu = True
    hiScores = Database.getScores()
    highScoreTexts = [font.render("NAME", 1, RED),
                      font.render("SCORE", 1, RED),
                      font.render("ACCURACY", 1, RED)]
    highScorePos = [highScoreTexts[0].get_rect(
                      topleft=screen.get_rect().inflate(-100, -100).topleft),
                    highScoreTexts[1].get_rect(
                      midtop=screen.get_rect().inflate(-100, -100).midtop),
                    highScoreTexts[2].get_rect(
                      topright=screen.get_rect().inflate(-100, -100).topright)]
    for hs in hiScores:
        highScoreTexts.extend([font.render(str(hs[x]), 1, BLUE)
                               for x in range(3)])
        highScorePos.extend([highScoreTexts[x].get_rect(
            topleft=highScorePos[x].bottomleft) for x in range(-3, 0)])

    
    main_dir = os.path.split(os.path.abspath(__file__))[0]
    data_dir = os.path.join(main_dir, 'data')
    fullname1 = os.path.join(data_dir, 'ship.png')
    fullname2 = os.path.join(data_dir, 'ship2.png')
    fullname3 = os.path.join(data_dir, 'ship3.png')
    fullname4 = os.path.join(data_dir, 'ship4.png')
    image1 = pygame.image.load(fullname1)
    image2 = pygame.image.load(fullname2)
    image3 = pygame.image.load(fullname3)
    image4 = pygame.image.load(fullname4)

    #imageload = [font.render("FIRST SELECT SHIP",1, RED),
     #            font.render("SECOND SELECT SHIP",1,RED),
     #            font.render("THIRD SELECT SHIP",1,RED)
     #           ]
    #imagePos = [(imageload[0].get_rect(topleft=screen.get_rect().inflate(-100, -100).midbottom)),
    #            (imageload[1].get_rect(topleft=screen.get_rect().inflate(-100, -100).midtop)),
     #           (imageload[2].get_rect(topleft=screen.get_rect().inflate(-100, -100).topright))
     #           ]

   
    title, titleRect = load_image('title.png')
    titleRect.midtop = screen.get_rect().inflate(0, -200).midtop
    startText = font.render('START GAME', 1, BLUE)
    startPos = startText.get_rect(midtop=titleRect.inflate(0, 100).midbottom)
    hiScoreText = font.render('HIGH SCORES', 1, BLUE)
    hiScorePos = hiScoreText.get_rect(topleft=startPos.bottomleft)
    fxText = font.render('SOUND FX ', 1, BLUE)
    fxPos = fxText.get_rect(topleft=hiScorePos.bottomleft)
    fxOnText = font.render('ON', 1, RED)
    fxOffText = font.render('OFF', 1, RED)
    fxOnPos = fxOnText.get_rect(topleft=fxPos.topright)
    fxOffPos = fxOffText.get_rect(topleft=fxPos.topright)
    musicText = font.render('MUSIC', 1, BLUE)
    musicPos = fxText.get_rect(topleft=fxPos.bottomleft)
    musicOnText = font.render('ON', 1, RED)
    musicOffText = font.render('OFF', 1, RED)
    musicOnPos = musicOnText.get_rect(topleft=musicPos.topright)
    musicOffPos = musicOffText.get_rect(topleft=musicPos.topright)
    quitText = font.render('QUIT', 1, BLUE)
    quitPos = quitText.get_rect(topleft=musicPos.bottomleft)
    selectText = font.render('*', 1, BLUE)
    selectPos = selectText.get_rect(topright=startPos.topleft)
    menuDict = {1: startPos, 2: hiScorePos, 3: fxPos, 4: musicPos, 5: quitPos}
    selection = 1
    showHiScores = False
    soundFX = Database.getSound()
    music = Database.getSound(music=True)
    if music and pygame.mixer:
        pygame.mixer.music.play(loops=-1)


    
    title1, titleRect1 = load_image('title.png')
    titleRect1.midtop = screen.get_rect().inflate(0, -200).midtop
    image1 = pygame.image.load(fullname1)
    startPos1 = image1.get_rect(midtop=titleRect1.inflate(0, 100).midbottom)
    image2 = pygame.image.load(fullname2)
    hiScorePos1 = image2.get_rect(topleft=startPos1.bottomleft)
    image3 = pygame.image.load(fullname3)
    fxPos1 = image3.get_rect(topleft=hiScorePos1.bottomleft)
    image4 = pygame.image.load(fullname4)
    fxOnPos1 = image4.get_rect(topleft=fxPos1.bottomleft)

    selectText1 = font.render('*', 1, BLUE)
    selectPos1 = selectText.get_rect(topright=startPos1.topleft)
    menuDict1 = {1: startPos1, 2: hiScorePos1, 3: fxPos1, 4: fxOnPos1}
    selection1 = 1

    
    is_end = True
    while inMenu:
        clock.tick(clockTime)
            

        screen.blit(
            background, (0, 0), area=pygame.Rect(
                0, backgroundLoc, 500, 500))
        backgroundLoc -= speed
        if backgroundLoc - speed <= speed:
            backgroundLoc = 1500

        for event in pygame.event.get():
            if (event.type == pygame.QUIT):
                return
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_RETURN):
                if showHiScores:
                    showHiScores = False
                elif selection == 1:
                    while is_end:
                        clock.tick(clockTime)
                        screen.blit(
                            background, (0, 0), area=pygame.Rect(
                                0, backgroundLoc, 500, 500))
                        backgroundLoc -= speed
                        if backgroundLoc - speed <= speed:
                            backgroundLoc = 1500

                        for event1 in pygame.event.get():
                            if (event1.type == pygame.QUIT):
                                return
                            elif(event1.type == pygame.KEYDOWN
                                 and event1.key == pygame.K_RETURN):
                                if selection1 ==1:
                                    abcd = 'ship.png'
                                    ship.abc(abcd)
                                    is_end = False
                                    inMenu = False 
                                    ship.initializeKeys()
                                    
                                elif selection1 ==2:
                                    abcd = 'ship2.png'
                                    ship.abc(abcd)
                                    is_end = False
                                    inMenu = False 
                                    ship.initializeKeys()
                                    
                                elif selection1 ==3:
                                    abcd = 'ship3.png'
                                    ship.abc(abcd)
                                    is_end = False
                                    inMenu = False 
                                    ship.initializeKeys()
                                    
                                elif selection1 ==4:
                                    abcd = 'ship4.png'
                                    ship.abc(abcd)
                                    is_end = False
                                    inMenu = False 
                                    ship.initializeKeys()
                                    
                            elif (event1.type == pygame.KEYDOWN
                                  and event1.key == pygame.K_w
                                  and selection1 > 1):
                                selection1 -= 1
                            elif (event1.type == pygame.KEYDOWN
                                  and event1.key == pygame.K_s
                                  and selection1 < len(menuDict1)):
                                selection1 += 1
                        selectPos1 = selectText1.get_rect(topright=menuDict1[selection1].topleft)
                        textOverlays1 = zip([image1, image2, image3, image4,selectText1],
                                       [startPos1, hiScorePos1, fxPos1, fxOnPos1,selectPos1])
                        screen.blit(title, titleRect)
                        for txt1, pos1 in textOverlays1:
                            screen.blit(txt1, pos1)
                        pygame.display.flip()
                               
                elif selection == 2:
                    showHiScores = True
                elif selection == 3:
                    soundFX = not soundFX
                    if soundFX:
                        missile_sound.play()
                    Database.setSound(int(soundFX))
                elif selection == 4 and pygame.mixer:
                    music = not music
                    if music:
                        pygame.mixer.music.play(loops=-1)
                    else:
                        pygame.mixer.music.stop()
                    Database.setSound(int(music), music=True)
                elif selection == 5:
                    return
                elif selection ==6:
                    return
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_w
                  and selection > 1
                  and not showHiScores):
                selection -= 1
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_s
                  and selection < len(menuDict)
                  and not showHiScores):
                selection += 1

        selectPos = selectText.get_rect(topright=menuDict[selection].topleft)
        

        if showHiScores:
            textOverlays = zip(highScoreTexts, highScorePos)
       
        else:
            textOverlays = zip([startText, hiScoreText, fxText,
                                musicText, quitText, selectText,
                                fxOnText if soundFX else fxOffText,
                                musicOnText if music else musicOffText],
                               [startPos, hiScorePos, fxPos,
                                musicPos, quitPos, selectPos,
                                fxOnPos if soundFX else fxOffPos,
                                musicOnPos if music else musicOffPos])
            screen.blit(title, titleRect)
        for txt, pos in textOverlays:
            screen.blit(txt, pos)
        pygame.display.flip()

            

       

    while ship.alive:
        clock.tick(clockTime)

        if aliensLeftThisWave >= 20:
            powerupTimeLeft -= 1
        if powerupTimeLeft <= 0:
            powerupTimeLeft = powerupTime
            random.choice(powerupTypes)().add(powerups, allsprites)

    # Event Handling
        for event in pygame.event.get():
            if (event.type == pygame.QUIT
                or event.type == pygame.KEYDOWN
                    and event.key == pygame.K_ESCAPE):
                return
            elif (event.type == pygame.KEYDOWN
                  and event.key in direction.keys()):
                ship.horiz += direction[event.key][0] * speed
                ship.vert += direction[event.key][1] * speed
            elif (event.type == pygame.KEYUP
                  and event.key in direction.keys()):
                ship.horiz -= direction[event.key][0] * speed
                ship.vert -= direction[event.key][1] * speed
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_SPACE):
                Missile.position(ship.rect.midtop)
                missilesFired += 1
                if soundFX:
                    missile_sound.play()
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_b):
                if bombsHeld > 0:
                    bombsHeld -= 1
                    newBomb = ship.bomb()
                    newBomb.add(bombs, alldrawings)
                    if soundFX:
                        bomb_sound.play()

    # Collision Detection
        # Aliens
        for alien in Alien.active:
            for bomb in bombs:
                if pygame.sprite.collide_circle(
                        bomb, alien) and alien in Alien.active:
                    alien.table()
                    Explosion.position(alien.rect.center)
                    missilesFired += 1
                    aliensLeftThisWave -= 1
                    score += 1
                    if soundFX:
                        alien_explode_sound.play()
            for missile in Missile.active:
                if pygame.sprite.collide_rect(
                        missile, alien) and alien in Alien.active:
                    alien.table()
                    missile.table()
                    Explosion.position(alien.rect.center)
                    aliensLeftThisWave -= 1
                    score += 1
                    if soundFX:
                        alien_explode_sound.play()
            if pygame.sprite.collide_rect(alien, ship):
                if ship.shieldUp:
                    alien.table()
                    Explosion.position(alien.rect.center)
                    aliensLeftThisWave -= 1
                    score += 1
                    missilesFired += 1
                    ship.shieldUp = False
                else:
                    ship.alive = False
                    ship.remove(allsprites)
                    Explosion.position(ship.rect.center)
                    if soundFX:
                        ship_explode_sound.play()

        # PowerUps
        for powerup in powerups:
            if pygame.sprite.collide_circle(powerup, ship):
                if powerup.pType == 'bomb':
                    bombsHeld += 1
                elif powerup.pType == 'shield':
                    ship.shieldUp = True
                powerup.kill()
            elif powerup.rect.top > powerup.area.bottom:
                powerup.kill()

    # Update Aliens
        if curTime <= 0 and aliensLeftThisWave > 0:
            Alien.position()
            curTime = alienPeriod
        elif curTime > 0:
            curTime -= 1

    # Update text overlays
        waveText = font.render("Wave: " + str(wave), 1, BLUE)
        leftText = font.render("Aliens Left: " + str(aliensLeftThisWave),
                               1, BLUE)
        scoreText = font.render("Score: " + str(score), 1, BLUE)
        bombText = font.render("Bombs: " + str(bombsHeld), 1, BLUE)

        wavePos = waveText.get_rect(topleft=screen.get_rect().topleft)
        leftPos = leftText.get_rect(midtop=screen.get_rect().midtop)
        scorePos = scoreText.get_rect(topright=screen.get_rect().topright)
        bombPos = bombText.get_rect(bottomleft=screen.get_rect().bottomleft)

        text = [waveText, leftText, scoreText, bombText]
        textposition = [wavePos, leftPos, scorePos, bombPos]

    # Detertmine when to move to next wave
        if aliensLeftThisWave <= 0:
            if betweenWaveCount > 0:
                betweenWaveCount -= 1
                nextWaveText = font.render(
                    'Wave ' + str(wave + 1) + ' in', 1, BLUE)
                nextWaveNum = font.render(
                    str((betweenWaveCount // clockTime) + 1), 1, BLUE)
                text.extend([nextWaveText, nextWaveNum])
                nextWavePos = nextWaveText.get_rect(
                    center=screen.get_rect().center)
                nextWaveNumPos = nextWaveNum.get_rect(
                    midtop=nextWavePos.midbottom)
                textposition.extend([nextWavePos, nextWaveNumPos])
                if wave % 4 == 0:
                    speedUpText = font.render('SPEED UP!', 1, RED)
                    speedUpPos = speedUpText.get_rect(
                        midtop=nextWaveNumPos.midbottom)
                    text.append(speedUpText)
                    textposition.append(speedUpPos)
            elif betweenWaveCount == 0:
                if wave % 4 == 0:
                    speed += 0.5
                    MasterSprite.speed = speed
                    ship.initializeKeys()
                    aliensThisWave = 10
                    aliensLeftThisWave = Alien.numOffScreen = aliensThisWave
                else:
                    aliensThisWave *= 2
                    aliensLeftThisWave = Alien.numOffScreen = aliensThisWave
                if wave == 1:
                    Alien.pool.add([Fasty() for _ in range(5)])
                    Alien.pool.add([F() for _ in range(5)])#새로운 외계인 F 1페이즈 출현
                if wave == 2:
                    Alien.pool.add([Roundy() for _ in range(5)])
                    Alien.pool.add([Oak() for _ in range(5)])#오크 2페이즈 출현
                if wave == 3:
                    Alien.pool.add([Crawly() for _ in range(5)])
                wave += 1
                betweenWaveCount = betweenWaveTime

        textOverlays = zip(text, textposition)

    # Update and draw all sprites and text
        screen.blit(
            background, (0, 0), area=pygame.Rect(
                0, backgroundLoc, 500, 500))
        backgroundLoc -= speed
        if backgroundLoc - speed <= speed:
            backgroundLoc = 1500
        allsprites.update()
        allsprites.draw(screen)
        alldrawings.update()
        for txt, pos in textOverlays:
            screen.blit(txt, pos)
        pygame.display.flip()

    accuracy = round(score / missilesFired, 4) if missilesFired > 0 else 0.0
    isHiScore = len(hiScores) < Database.numScores or score > hiScores[-1][1]
    name = ''
    nameBuffer = []

    while True:
        clock.tick(clockTime)

    # Event Handling
        for event in pygame.event.get():
            if (event.type == pygame.QUIT
                or not isHiScore
                and event.type == pygame.KEYDOWN
                    and event.key == pygame.K_ESCAPE):
                return False
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_RETURN
                  and not isHiScore):
                return True
            elif (event.type == pygame.KEYDOWN
                  and event.key in Keyboard.keys.keys()
                  and len(nameBuffer) < 8):
                nameBuffer.append(Keyboard.keys[event.key])
                name = ''.join(nameBuffer)
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_BACKSPACE
                  and len(nameBuffer) > 0):
                nameBuffer.pop()
                name = ''.join(nameBuffer)
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_RETURN
                  and len(name) > 0):
                Database.setScore(hiScores, (name, score, accuracy))
                return True

        if isHiScore:
            hiScoreText = font.render('HIGH SCORE!', 1, RED)
            hiScorePos = hiScoreText.get_rect(
                midbottom=screen.get_rect().center)
            scoreText = font.render(str(score), 1, BLUE)
            scorePos = scoreText.get_rect(midtop=hiScorePos.midbottom)
            enterNameText = font.render('ENTER YOUR NAME:', 1, RED)
            enterNamePos = enterNameText.get_rect(midtop=scorePos.midbottom)
            nameText = font.render(name, 1, BLUE)
            namePos = nameText.get_rect(midtop=enterNamePos.midbottom)
            textOverlay = zip([hiScoreText, scoreText,
                               enterNameText, nameText],
                              [hiScorePos, scorePos,
                               enterNamePos, namePos])
        else:
            gameOverText = font.render('GAME OVER', 1, BLUE)
            gameOverPos = gameOverText.get_rect(
                center=screen.get_rect().center)
            scoreText = font.render('SCORE: {}'.format(score), 1, BLUE)
            scorePos = scoreText.get_rect(midtop=gameOverPos.midbottom)
            textOverlay = zip([gameOverText, scoreText],
                              [gameOverPos, scorePos])

    # Update and draw all sprites
        screen.blit(
            background, (0, 0), area=pygame.Rect(
                0, backgroundLoc, 500, 500))
        backgroundLoc -= speed
        if backgroundLoc - speed <= 0:
            backgroundLoc = 1500
        allsprites.update()
        allsprites.draw(screen)
        alldrawings.update()
        for txt, pos in textOverlay:
            screen.blit(txt, pos)
        pygame.display.flip()
示例#51
0
文件: main.py 项目: USMAnss/Pybrawl
def menu():
    # colors
    white = 255,255,255
    black =   0,  0,  0
    orange = 255,165, 0
    ### We found the numbers for different colors on: http://www.discoveryplayground.com/computer-programming-for-kids/rgb-colors/

    size = width, height = WIDTH,HEIGHT
    pygame.display.set_caption('Pybrawl')

    while True:
        screen = pygame.display.set_mode(size)
        pygame.key.set_repeat(500,30)
        background = load_image("Background/main_menu.png")
        background=pygame.transform.scale(background, (WIDTH, HEIGHT))
        screen.blit(background, (0, 0))
        pygame.display.update()

        selection = dm.dumbmenu(screen, [
                                'Start Game',
                                'Help',
                                'Quit Game'], 325,375,None,32,1.4,white,white)

        if selection == 1:
            screen.fill(black)
            font = pygame.font.Font(None, 40)
            text = font.render("Player 1 Controls:", True, white)
            screen.blit(text, (50, 50))
            text = font.render("WAD - Move", True, white)
            screen.blit(text, (50, 100))
            text = font.render("T - basic attack", True, white)
            screen.blit(text, (50, 140))
            text = font.render("Y - throw attack", True, white)
            screen.blit(text, (50, 180))
            text = font.render("U - special attack", True, white)
            screen.blit(text, (50, 220))
            text = font.render("Back - block if being hit", True, white)
            screen.blit(text, (50, 260))
            text = font.render("Player 2 Controls:", True, white)
            screen.blit(text, (450, 50))
            text = font.render("Arrow keys - Move", True, white)
            screen.blit(text, (450, 100))
            text = font.render("NUM4 - basic attack", True, white)
            screen.blit(text, (450, 140))
            text = font.render("NUM5 - throw attack", True, white)
            screen.blit(text, (450, 180))
            text = font.render("NUM6 - special attack", True, white)
            screen.blit(text, (450, 220))
            text = font.render("Back - block if being hit", True, white)
            screen.blit(text, (450, 260))
            text = font.render("Enter - go back to Main Menu when the fight ends", True, white)
            screen.blit(text, (60, 300))
            text = font.render("Escape - back to Main Menu", True, white)
            screen.blit(text, (200, 500))
            pygame.display.update()
            ok=True
            while ok:
                for event in pygame.event.get():
                    if event.type == QUIT:
                        print("You choose 'Quit'")
                        pygame.quit()
                        exit()
                    if event.type == KEYDOWN and event.key==K_ESCAPE:
                        ok=False
            continue

        if selection == 0:
            screen.blit(background, (0, 0))
            pygame.display.update()
            pygame.key.set_repeat(500,30)
            selectionTwo = dm.dumbmenu(screen, [
                            'Naruto',
                            'Sasuke',
                            'Suigetsu',
                            'Itachi',
                            'Jiraiya',
                            'To Main Menu'], 325,375,None,32,1.4,white,white)
            characters=["naruto", "sasuke", "suigetsu", "itachi", "jiraiya"]

            if selectionTwo==-1:
                print("You choose 'Quit'")
                pygame.quit()
                exit()

            if selectionTwo==5:
                continue

            screen.blit(background, (0, 0))
            pygame.display.update()
            pygame.key.set_repeat(500,30)
            selectionThree = dm.dumbmenu(screen, [
                            'Naruto',
                            'Sasuke',
                            'Suigetsu',
                            'Itachi',
                            'Jiraiya',
                            'To Main Menu'], 325,375,None,32,1.4,white,white)
            if selectionThree==-1:
                print("You choose 'Quit'")
                pygame.quit()
                exit()

            if selectionThree==5:
                continue

            playGame(characters[selectionTwo], characters[selectionThree])

        elif selection == 2 or selection == -1:
            print("You choose 'Quit'")
            pygame.quit()
            exit()
示例#52
0
文件: birds.py 项目: elxw/snowyslopes
def init():
    Bird.images = []
    Bird.images.append(load.load_image("standing"))
    Bird.images.append(load.load_image("flying1"))
    Bird.images.append(load.load_image("flying2"))
示例#53
0
文件: tree.py 项目: elxw/snowyslopes
def init():
    Tree.images = []
    Tree.images.append(load.load_image("tree1"))
    Tree.images.append(load.load_image("tree2"))
    Tree.images.append(load.load_image("tree3"))
示例#54
0
def main():

    #mindwaveDataPointReader = MindwaveDataPointReader()
    #mindwaveDataPointReader.start()
    #if not (mindwaveDataPointReader.isConnected()):
    #print((textwrap.dedent("""\
    #Exiting because the program could not connect
    #to the Mindwave Mobile device.""").replace("\n", " ")))
    #sys.exit()

    # Initialize everything
    pygame.mixer.pre_init(11025, -16, 2, 512)
    pygame.init()
    screen = pygame.display.set_mode((500, 500))
    pygame.display.set_caption('Shooting Game')
    pygame.mouse.set_visible(0)

    # Create the background which will scroll and loop over a set of different
    # size stars
    background = pygame.Surface((500, 2000))
    background = background.convert()
    background.fill((0, 0, 0))
    backgroundLoc = 1500
    finalStars = deque()
    for y in range(0, 1500, 30):
        size = random.randint(2, 5)
        x = random.randint(0, 500 - size)
        if y <= 500:
            finalStars.appendleft((x, y + 1500, size))
        pygame.draw.rect(background, (255, 255, 0),
                         pygame.Rect(x, y, size, size))
    while finalStars:
        x, y, size = finalStars.pop()
        pygame.draw.rect(background, (255, 255, 0),
                         pygame.Rect(x, y, size, size))


# Display the background
    screen.blit(background, (0, 0))
    pygame.display.flip()

    # Prepare game objects
    speed = 1.5
    MasterSprite.speed = speed
    alienPeriod = 60 / speed
    clockTime = 60  # maximum FPS
    clock = pygame.time.Clock()
    ship = Ship()
    initialAlienTypes = (Siney, Spikey)
    powerupTypes = (BombPowerup, ShieldPowerup)

    # Sprite groups
    alldrawings = pygame.sprite.Group()
    allsprites = pygame.sprite.RenderPlain((ship, ))
    MasterSprite.allsprites = allsprites
    Alien.pool = pygame.sprite.Group(
        [alien() for alien in initialAlienTypes for _ in range(5)])
    Alien.active = pygame.sprite.Group()
    Missile.pool = pygame.sprite.Group([Missile() for _ in range(10)])
    Missile.active = pygame.sprite.Group()
    Explosion.pool = pygame.sprite.Group([Explosion() for _ in range(10)])
    Explosion.active = pygame.sprite.Group()
    bombs = pygame.sprite.Group()
    powerups = pygame.sprite.Group()

    # Sounds
    missile_sound = load_sound('missile.ogg')
    bomb_sound = load_sound('bomb.ogg')
    alien_explode_sound = load_sound('alien_explode.ogg')
    ship_explode_sound = load_sound('ship_explode.ogg')
    load_music('music_loop.ogg')

    alienPeriod = clockTime // 2
    curTime = 0
    aliensThisWave, aliensLeftThisWave, Alien.numOffScreen = 10, 10, 10
    wave = 1
    bombsHeld = 3
    score = 0
    missilesFired = 0
    powerupTime = 10 * clockTime
    powerupTimeLeft = powerupTime
    betweenWaveTime = 3 * clockTime
    betweenWaveCount = betweenWaveTime
    font = pygame.font.Font(None, 36)

    inMenu = True
    hiScores = Database.getScores()
    highScoreTexts = [
        font.render("NAME", 1, RED),
        font.render("SCORE", 1, RED),
        font.render("ACCURACY", 1, RED)
    ]
    highScorePos = [
        highScoreTexts[0].get_rect(
            topleft=screen.get_rect().inflate(-100, -100).topleft),
        highScoreTexts[1].get_rect(
            midtop=screen.get_rect().inflate(-100, -100).midtop),
        highScoreTexts[2].get_rect(
            topright=screen.get_rect().inflate(-100, -100).topright)
    ]
    for hs in hiScores:
        highScoreTexts.extend(
            [font.render(str(hs[x]), 1, BLUE) for x in range(3)])
        highScorePos.extend([
            highScoreTexts[x].get_rect(topleft=highScorePos[x].bottomleft)
            for x in range(-3, 0)
        ])

    title, titleRect = load_image('title.png')
    titleRect.midtop = screen.get_rect().inflate(0, -200).midtop

    startText = font.render('START GAME', 1, BLUE)
    startPos = startText.get_rect(midtop=titleRect.inflate(0, 100).midbottom)
    hiScoreText = font.render('HIGH SCORES', 1, BLUE)
    hiScorePos = hiScoreText.get_rect(topleft=startPos.bottomleft)
    fxText = font.render('SOUND FX ', 1, BLUE)
    fxPos = fxText.get_rect(topleft=hiScorePos.bottomleft)
    fxOnText = font.render('ON', 1, RED)
    fxOffText = font.render('OFF', 1, RED)
    fxOnPos = fxOnText.get_rect(topleft=fxPos.topright)
    fxOffPos = fxOffText.get_rect(topleft=fxPos.topright)
    musicText = font.render('MUSIC', 1, BLUE)
    musicPos = fxText.get_rect(topleft=fxPos.bottomleft)
    musicOnText = font.render('ON', 1, RED)
    musicOffText = font.render('OFF', 1, RED)
    musicOnPos = musicOnText.get_rect(topleft=musicPos.topright)
    musicOffPos = musicOffText.get_rect(topleft=musicPos.topright)
    quitText = font.render('QUIT', 1, BLUE)
    quitPos = quitText.get_rect(topleft=musicPos.bottomleft)
    selectText = font.render('*', 1, BLUE)
    selectPos = selectText.get_rect(topright=startPos.topleft)
    menuDict = {1: startPos, 2: hiScorePos, 3: fxPos, 4: musicPos, 5: quitPos}
    selection = 1
    showHiScores = False
    soundFX = Database.getSound()
    music = Database.getSound(music=True)
    if music and pygame.mixer:
        pygame.mixer.music.play(loops=-1)

    while inMenu:
        clock.tick(clockTime)

        screen.blit(background, (0, 0),
                    area=pygame.Rect(0, backgroundLoc, 500, 500))
        backgroundLoc -= speed
        if backgroundLoc - speed <= speed:
            backgroundLoc = 1500

        for event in pygame.event.get():
            if (event.type == pygame.QUIT):
                return
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_RETURN):
                if showHiScores:
                    showHiScores = False
                elif selection == 1:
                    inMenu = False
                    ship.initializeKeys()
                elif selection == 2:
                    showHiScores = True
                elif selection == 3:
                    soundFX = not soundFX
                    if soundFX:
                        missile_sound.play()
                    Database.setSound(int(soundFX))
                elif selection == 4 and pygame.mixer:
                    music = not music
                    if music:
                        pygame.mixer.music.play(loops=-1)
                    else:
                        pygame.mixer.music.stop()
                    Database.setSound(int(music), music=True)
                elif selection == 5:
                    return
            elif (event.type == pygame.KEYDOWN and event.key == pygame.K_w
                  and selection > 1 and not showHiScores):
                selection -= 1
            elif (event.type == pygame.KEYDOWN and event.key == pygame.K_s
                  and selection < len(menuDict) and not showHiScores):
                selection += 1

        selectPos = selectText.get_rect(topright=menuDict[selection].topleft)

        if showHiScores:
            textOverlays = zip(highScoreTexts, highScorePos)
        else:
            textOverlays = zip([
                startText, hiScoreText, fxText, musicText, quitText,
                selectText, fxOnText if soundFX else fxOffText,
                musicOnText if music else musicOffText
            ], [
                startPos, hiScorePos, fxPos, musicPos, quitPos, selectPos,
                fxOnPos if soundFX else fxOffPos,
                musicOnPos if music else musicOffPos
            ])
            screen.blit(title, titleRect)
        for txt, pos in textOverlays:
            screen.blit(txt, pos)
        pygame.display.flip()

    medVal = 0
    attVal = 0
    while medVal == 0 and attVal == 0:
        dataPoint = mindwaveDataPointReader.readNextDataPoint()
        if (not dataPoint.__class__ is RawDataPoint):
            if dataPoint.__class__.__name__ == 'MeditationDataPoint':
                medVal = dataPoint.meditationValue
                print("Meditaion Value: ", medVal)
            elif dataPoint.__class__.__name__ == 'AttentionDataPoint':
                attVal = dataPoint.attentionValue
                print("Attention Value: ", attVal)

    while ship.alive:
        clock.tick(clockTime)

        dataPoint = mindwaveDataPointReader.readNextDataPoint()
        if (not dataPoint.__class__ is RawDataPoint):
            if dataPoint.__class__.__name__ == 'MeditationDataPoint':
                medVal = dataPoint.meditationValue
                print("Meditaion Value: ", medVal)
            elif dataPoint.__class__.__name__ == 'AttentionDataPoint':
                attVal = dataPoint.attentionValue
                print("Attention Value: ", attVal)

        if aliensLeftThisWave >= 20:
            powerupTimeLeft -= 1
        if powerupTimeLeft <= 0:
            powerupTimeLeft = powerupTime
            random.choice(powerupTypes)().add(powerups, allsprites)

    # Event Handling
        for event in pygame.event.get():
            if (event.type == pygame.QUIT or event.type == pygame.KEYDOWN
                    and event.key == pygame.K_ESCAPE):
                return
            elif (event.type == pygame.KEYDOWN
                  and event.key in direction.keys()):
                ship.horiz += direction[event.key][0] * speed  #*medVal
                ship.vert += direction[event.key][1] * speed  #*medVal
            elif (event.type == pygame.KEYUP
                  and event.key in direction.keys()):
                ship.horiz -= direction[event.key][0] * speed  #*medVal
                ship.vert -= direction[event.key][1] * speed  #*medVal
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_SPACE):
                Missile.position(ship.rect.midtop)
                missilesFired += 1
                if soundFX:
                    missile_sound.play()
            elif (event.type == pygame.KEYDOWN and event.key == pygame.K_b):
                if bombsHeld > 0:
                    bombsHeld -= 1
                    newBomb = ship.bomb()
                    newBomb.add(bombs, alldrawings)
                    if soundFX:
                        bomb_sound.play()

    # Collision Detection
    # Aliens
        for alien in Alien.active:
            for bomb in bombs:
                if pygame.sprite.collide_circle(
                        bomb, alien) and alien in Alien.active:
                    alien.table()
                    Explosion.position(alien.rect.center)
                    missilesFired += 1
                    aliensLeftThisWave -= 1
                    score += 1
                    if soundFX:
                        alien_explode_sound.play()
            for missile in Missile.active:
                if pygame.sprite.collide_rect(missile,
                                              alien) and alien in Alien.active:
                    alien.table()

                    #Peiercing bullets
                    if medVal < 40:
                        missile.table()
                    Explosion.position(alien.rect.center)
                    aliensLeftThisWave -= 1
                    score += 1
                    if soundFX:
                        alien_explode_sound.play()
            if pygame.sprite.collide_rect(alien, ship):
                if ship.shieldUp:
                    alien.table()
                    Explosion.position(alien.rect.center)
                    aliensLeftThisWave -= 1
                    score += 1
                    missilesFired += 1
                    ship.shieldUp = False
                else:
                    ship.alive = False
                    ship.remove(allsprites)
                    Explosion.position(ship.rect.center)
                    if soundFX:
                        ship_explode_sound.play()

        # PowerUps
        for powerup in powerups:
            if pygame.sprite.collide_circle(powerup, ship):
                if powerup.pType == 'bomb':
                    bombsHeld += 1
                elif powerup.pType == 'shield':
                    ship.shieldUp = True
                powerup.kill()
            elif powerup.rect.top > powerup.area.bottom:
                powerup.kill()

    # Update Aliens
        if curTime <= 0 and aliensLeftThisWave > 0:
            Alien.position()
            curTime = alienPeriod
        elif curTime > 0:
            curTime -= 1

    # Update text overlays
        waveText = font.render("Wave: " + str(wave), 1, BLUE)
        leftText = font.render("Aliens Left: " + str(aliensLeftThisWave), 1,
                               BLUE)
        scoreText = font.render("Score: " + str(score), 1, BLUE)

        dataText = font.render("(A): " + str(attVal) + " (M): " + str(medVal),
                               1, RED)
        bombText = font.render("Bombs: " + str(bombsHeld), 1, BLUE)

        wavePos = waveText.get_rect(topleft=screen.get_rect().topleft)
        leftPos = leftText.get_rect(midtop=screen.get_rect().midtop)
        scorePos = scoreText.get_rect(topright=screen.get_rect().topright)
        bombPos = bombText.get_rect(bottomleft=screen.get_rect().bottomleft)
        dataPos = dataText.get_rect(bottomright=screen.get_rect().bottomright)

        text = [waveText, leftText, scoreText, bombText, dataText]
        textposition = [wavePos, leftPos, scorePos, bombPos, dataPos]

        # Detertmine when to move to next wave
        if aliensLeftThisWave <= 0:
            if betweenWaveCount > 0:
                betweenWaveCount -= 1
                nextWaveText = font.render('Wave ' + str(wave + 1) + ' in', 1,
                                           BLUE)
                nextWaveNum = font.render(
                    str((betweenWaveCount // clockTime) + 1), 1, BLUE)
                text.extend([nextWaveText, nextWaveNum])
                nextWavePos = nextWaveText.get_rect(
                    center=screen.get_rect().center)
                nextWaveNumPos = nextWaveNum.get_rect(
                    midtop=nextWavePos.midbottom)
                textposition.extend([nextWavePos, nextWaveNumPos])
                if wave % 4 == 0:
                    speedUpText = font.render('SPEED UP!', 1, RED)
                    speedUpPos = speedUpText.get_rect(
                        midtop=nextWaveNumPos.midbottom)
                    text.append(speedUpText)
                    textposition.append(speedUpPos)
            elif betweenWaveCount == 0:
                if wave % 4 == 0:
                    speed += 0.5
                    MasterSprite.speed = speed
                    ship.initializeKeys()
                    aliensThisWave = 10
                    aliensLeftThisWave = Alien.numOffScreen = aliensThisWave
                else:
                    aliensThisWave *= 2
                    aliensLeftThisWave = Alien.numOffScreen = aliensThisWave
                if wave == 1:
                    Alien.pool.add([Fasty() for _ in range(5)])
                if wave == 2:
                    Alien.pool.add([Roundy() for _ in range(5)])
                if wave == 3:
                    Alien.pool.add([Crawly() for _ in range(5)])
                wave += 1
                betweenWaveCount = betweenWaveTime

        textOverlays = zip(text, textposition)

        # Update and draw all sprites and text
        screen.blit(background, (0, 0),
                    area=pygame.Rect(0, backgroundLoc, 500, 500))
        backgroundLoc -= speed
        if backgroundLoc - speed <= speed:
            backgroundLoc = 1500
        allsprites.update()
        allsprites.draw(screen)
        alldrawings.update()
        for txt, pos in textOverlays:
            screen.blit(txt, pos)
        pygame.display.flip()

    accuracy = round(score / missilesFired, 4) if missilesFired > 0 else 0.0
    isHiScore = len(hiScores) < Database.numScores or score > hiScores[-1][1]
    name = ''
    nameBuffer = []

    while True:
        clock.tick(clockTime)

        # Event Handling
        for event in pygame.event.get():
            if (event.type == pygame.QUIT
                    or not isHiScore and event.type == pygame.KEYDOWN
                    and event.key == pygame.K_ESCAPE):
                return False
            elif (event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN
                  and not isHiScore):
                return True
            elif (event.type == pygame.KEYDOWN
                  and event.key in Keyboard.keys.keys()
                  and len(nameBuffer) < 8):
                nameBuffer.append(Keyboard.keys[event.key])
                name = ''.join(nameBuffer)
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_BACKSPACE and len(nameBuffer) > 0):
                nameBuffer.pop()
                name = ''.join(nameBuffer)
            elif (event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN
                  and len(name) > 0):
                Database.setScore(hiScores, (name, score, accuracy))
                return True

        if isHiScore:
            hiScoreText = font.render('HIGH SCORE!', 1, RED)
            hiScorePos = hiScoreText.get_rect(
                midbottom=screen.get_rect().center)
            scoreText = font.render(str(score), 1, BLUE)
            scorePos = scoreText.get_rect(midtop=hiScorePos.midbottom)
            enterNameText = font.render('ENTER YOUR NAME:', 1, RED)
            enterNamePos = enterNameText.get_rect(midtop=scorePos.midbottom)
            nameText = font.render(name, 1, BLUE)
            namePos = nameText.get_rect(midtop=enterNamePos.midbottom)
            textOverlay = zip(
                [hiScoreText, scoreText, enterNameText, nameText],
                [hiScorePos, scorePos, enterNamePos, namePos])
        else:
            gameOverText = font.render('GAME OVER', 1, BLUE)
            gameOverPos = gameOverText.get_rect(
                center=screen.get_rect().center)
            scoreText = font.render('SCORE: {}'.format(score), 1, BLUE)
            scorePos = scoreText.get_rect(midtop=gameOverPos.midbottom)
            textOverlay = zip([gameOverText, scoreText],
                              [gameOverPos, scorePos])

    # Update and draw all sprites
        screen.blit(background, (0, 0),
                    area=pygame.Rect(0, backgroundLoc, 500, 500))
        backgroundLoc -= speed
        if backgroundLoc - speed <= 0:
            backgroundLoc = 1500
        allsprites.update()
        allsprites.draw(screen)
        alldrawings.update()
        for txt, pos in textOverlay:
            screen.blit(txt, pos)
        pygame.display.flip()
示例#55
0
 def __init__(self, image_path):
     """Initialize the image of the sprite."""
     pygame.sprite.Sprite.__init__(self)
     self.image, self.rect = load_image(image_path)
示例#56
0
	def __init__(self, image_path):
		super(Background, self).__init__()
		self.image, self.rect = load_image(image_path)
示例#57
0
 def __init__(self):
     super().__init__()
     self.image, self.rect = load_image('explosion.png', -1)
     self.linger = MasterSprite.speed * 3
示例#58
0
 def __init__(self):
     super().__init__()
     self.image, self.rect = load_image('missile.png', -1)
     screen = pygame.display.get_surface()
     self.area = screen.get_rect()
示例#59
0
 def drawUnfinishedBuilding(self):
     scale = min(self.sizeCol,self.sizeRow)/2.0
     unfinishedBuildingImage = load.load_image('Buildings/Terran/TerranCore.png',scale = scale)
     TerranBuilding.unfinishedBuildingImage = unfinishedBuildingImage
     super(TerranBuilding,self).drawUnfinishedBuilding(unfinishedBuildingImage)
     TerranBuilding.terranBuildings.append(self)