Exemple #1
0
    def bottom_collision(self):
        Sound.play_SE('humi')

        # 甲羅になる場合
        if self.list_number == 0:
            self.list_number = 1
            self.kill_text = "ざまぁw"

            self.enemy.direction = 0
            self.enemy.x += 4
            self.enemy.x_speed = 4.0
            self.enemy.width = self.enemy.img_left[
                self.list_number].get_width()
            self.enemy.height = self.enemy.img_left[
                self.list_number].get_height()

        # 甲羅を蹴る場合
        elif self.list_number == 1:
            if self.enemy.direction == 0:
                self.kick_koura()
            elif not self.player.isDeath:
                self.enemy.direction = 0

        # 踏んだ勢いでジャンプ
        self.player.isGrounding = True
        self.player.isJump = True
        self.player.y_speed = self.player.JUMP_SPEED + 1
        self.player.y -= 10
        self.player.limit_air_speed()
Exemple #2
0
	def afficher(self,signal,nom,title='',xlabel='',ylabel=''):
		"""
		Affiche la courbe du signal "signal" et la stocke dans le fichier
		"nom".png.
		"""
		sound = Sound()
		sound.plot(signal,display=True,saveas='../ressources/generated/'+nom+'.png',title=title,xlabel=xlabel,ylabel=ylabel)
Exemple #3
0
    def __init__(self):
        super().__init__()
        Player2.this = self
        self.load_img('img/stair_move.png')
        self.anim2 = Animator()
        self.anim2.load('img/ping.png', 1, 2, np.array([0, 0]))
        self.size[0], self.size[1] = 1, 1
        self.anim = Animator()
        self.anim.load('img/user_idle.png', 1, 5, np.array([80, 0]))  # 0
        self.anim.load('img/user_walk.png', 1, 8, np.array([80, 0]))  # 1
        self.anim.load('img/user_run.png', 1, 4, np.array([80, 0]))  # 2
        self.anim.load('img/user_active.png', 3, 3, np.array([80, 0]))  # 3
        self.anim.load('img/user_die1.png', 2, 9, np.array([80,
                                                            0]))  # 4 플레이어한테 죽음
        self.anim.load('img/user_movebody.png', 1, 7, np.array([0,
                                                                0]))  # 5 시체유기
        self.anim.load('img/user_attack.png', 3, 7, np.array([0, 0]))  # 6 공격
        self.anim.load('img/user_hit.png', 3, 1, np.array([80, 0]))  # 7 아야
        self.anim.anim_arr[7].delayTime = 1 / 2.0

        self.attack_sound = Sound.load('sound/Attack2.wav', 100)
        self.interact_sound = Sound.load('sound/빰.wav', 100)
        self.hurt_sound = Sound.load('sound/영훈_아야.wav', 100)
        self.movebody_sound = Sound.load('sound/GetBody.wav', 100)
        self.die_sound = Sound.load('sound/Die.wav', 100)

        self.init()
Exemple #4
0
 def sniffing(self):
     self.positionVector.x += self.movementSpeed
     if self.positionVector.x > 300:
         Sound.play(Sounds.SzczekTwo)
         self.dogState = DogState.JUMPING
         self.currentImageSet = self.spriteMap[DogAnimationState.JUMP]
     return None
Exemple #5
0
    def __init__(self, screen, block, img_name, data=0):
        Sound.play_SE('brockkinoko')
        self.screen = screen
        self.block = block
        self.player = Stage.player_object

        # ブロックデータの置き換え
        block.name = 'block3'
        block.data = 5
        block.image = LoadImage.image_list[block.name]

        self.isSuccess = False  # アニメーションが完了したかどうか
        self.isAppear = False  # 出現アニメーション中か
        self.isGenerate = False  # 新たに生成するか

        self.sprite = SpriteObject(screen, img_name, data, -30, -30)

        self.sprite.direction = -1  # アイテムが動く向き
        self.list_number = -1  # 画像の切り替え

        # オブジェクトの座標
        self.sprite.x = block.rect.left + int(
            block.width / 2 - self.sprite.width / 2) + SpritePlayer.scroll_sum
        self.sprite.rect.top = block.rect.top + 2
        self.start_y = self.sprite.rect.top

        # 描画範囲
        self.START_RANGE_X = -50
Exemple #6
0
    def __init__(self, width, height):
        # We create the window
        self.width = width
        self.height = height
        FULLSCREEN = 0
        self.dimension = (self.width, self.height)
        self.screen = pygame.display.set_mode(self.dimension, FULLSCREEN, 32)
        pygame.display.set_caption("TuxleTriad")

        elemText = ["Play", "Options", "Rules", "About", "Quit Game"]
        self.menu = []
        for elem in elemText:
            self.menu.append(Button(elem, "Dearest.ttf", white))

        posx = 400
        posy = 400 - (60 * len(elemText))

        for elem in self.menu:
            elem.rect.center = ((posx, posy))
            posy += 100

        self.bkgrnd, self.bkgrndRect = loadImage("background.jpg")
        self.bkgrndRect = self.bkgrnd.get_rect()

        # The Clock of the game, to manage the frame-rate
        self.clock = pygame.time.Clock()
        self.fps = 60

        # We start the Sound object, playing music and sounds.
        self.sound = Sound()

        # Needed to keep track of the game if we do a pause during the game.
        self.app = None

        self.main()
Exemple #7
0
    def tick(self):
        super().tick()
        if self.start:
            Sound.play(Sounds.DogSniff)
            self.start = False

        if self.dogState == DogState.SNIFFING:
            self.sniffing()
            return None

        if self.dogState == DogState.JUMPING:
            self.jumping()
            return None

        if self.dogState == DogState.HIDDEN:
            self.hidden()
            return None

        if self.dogState == DogState.HOLD_ONE:
            self.holdone()
            return None

        if self.dogState == DogState.HOLD_TWO:
            self.holdtwo()
            return None

        if self.dogState == DogState.LAUGHING:
            self.laughing()
            return None
Exemple #8
0
    def __init__(self, fileName, keys, stick, stones, helps, ball, bar, rightBall, level, game):
        """
        Initialize a challenge

	        @param self -- the challenge
            @param fileName -- a string that contains the sound name 
            @param keys -- the key vector
            @param stick -- the stick
            @param stones -- the stones
            @param helps -- the helps
            @param ball -- the left ball that it is used in the animation
            @param bar -- the grey bar that it is used in the animation
            @param rightBall -- the right ball that it is used in the animation
            @param level -- the challenge level
            @param game -- the game
	    
		"""
		
        self.fileName = fileName
        self.music = Sound()
        self.music.setFileName("sound/music/" + fileName)
        self.section = Section()
        self.section.setFileName("sound/section/" + fileName)
        self.section.setKeys(keys)
        self.stick = stick
        self.animation = Animation(stones, keys, helps, ball, rightBall, bar, game)
        self.ball = ball
        self.level = level
        self.attempts = 0
        self.game = game
Exemple #9
0
 def __init__(self, imgs, pos, remain_time=1.0):
     super().__init__(pos, remain_time)
     self.imgs = imgs
     if remain_time > 2:
         self.victory_sound = Sound.load('sound/EndVictory.wav', 100)
     else:
         self.victory_sound = Sound.load('sound/Victory.wav', 100)
     self.victory_sound.play()
Exemple #10
0
 def shot(self):
     if self.stoper.getCurrentTicks() - self.lastStateChanged > 500:
         self.duckState = DuckState.FALLING
         self.currentImageSet = self.spriteMap[DuckAnimationState.FALLING]
         self.setDirectionFromAngle(90)
         self.movementSpeed = 0.15
         Sound.play(Sounds.Falling)
     return None
Exemple #11
0
    def __init__(self):
        self.Stage = Stage(screen, 1, '1-1')
        self.Player = Player(screen, self.Stage)
        self.Enemy = Enemy(screen)

        remain_show()
        Sound.play_BGM('titerman')

        self.main()
def handle_full_lines(playground, points, sound: Sound.Sound):
    line_numbers = playground.fullrow()
    line_count = len(line_numbers)

    if line_count > 0:
        playground.delete_line(line_numbers)
        points.lines(line_count)
        sound.play_sound_for_lines(line_count)
    return line_count
Exemple #13
0
 def __init__(self):
     self.vec_active = (0.3, -0.5)
     self.vec_passive = (0.4, -0.6)
     super().__init__(parent=camera.ui,
                      model='assets/arm',
                      texture=Textures.creat_texture('arm'),
                      scale=0.2,
                      rotation=Vec3(150, -10, 0),
                      position=Vec2(self.vec_active))
     self.sound = Sound()
Exemple #14
0
    def goal_animation(self):
        if not (self.player.isDeath or self.player.goal is None):
            # 初期化
            if self._goal_init:
                self._goal_init = False
                Sound.stop_BGM()
                Sound.play_SE('goal')
                self._goal_count = 0

                # プレイヤー座標のセット
                self.player.x_speed = self.player.y_speed = 0
                self.player.x = self.player.goal.rect.left - self.player.width + 7

                # ポール下の地面の座標を格納
                goal_block_list = [
                    block for block in Stage.block_object_list
                    if block.data == 7
                ]
                for block in goal_block_list:
                    if block.rect.left == self.player.goal.rect.left - 3:
                        self._goal_scene_y = block.rect.top - 1

            # 一定の時間が経過したら次の面へ
            self._goal_count += 1
            if self._goal_count > 400:
                return True

            # ゴール塔に入った場合
            if self._inGoal_tower:
                self.bg_update()

            # 強制移動中
            elif self.goal_isMove:
                self.player.x_speed = 1.5

            # ポール掴み中
            else:
                # 一定の時間が経過したら移動モード切り替え
                if self._goal_count > 100 and self._goal_scene_y != 500:
                    self.goal_isMove = True
                    self._goal_count = 0

                # 地面に着いたらそのまま停止
                if not self.player.rect.bottom > self._goal_scene_y:
                    self.player.y += 3

                    # 画面外に出たら死
                    if self.player.y > 450:
                        self.player.isDeath = True

                self.bg_update()
                self.player.update(self.player.img_right[2])
        return False
Exemple #15
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__()

        self.parent = parent

        self.tcp = parent.tcp
        self.tcp.recvAns.connect(self.parseAns)
        self.tcp.ConError.connect(self.tcpError)

        self.UID = parent.UID
        self.sound = Sound()
        self.initUI()
    def save_sound(self):
        ret = QMessageBox.question(self, "Confirmation", "Are you sure?", QMessageBox.Yes, QMessageBox.No)
        if(ret == QMessageBox.No):
            return

        thisSound = Sound(self.soundNumber.text(), self.soundDescription.text(), self.soundAbreviation.text(), self.filePath)
        if not self.editing:
            thisSound.write_sound()
        else:
            thisSound.update_sound()

        self.start_key_edition()
Exemple #17
0
    def setSound(self, id):
        """
        Set a stone sound

		    @param self -- the stone
		    @param id -- a number that represents the ball note
	    
		"""

        self.id = id
        self.sound = Sound()
        self.sound.setFileName("sound/notes/T" + str(self.id + 3))
 def __init__(self,name,hp=8,taunt=0,defense=10,cover=0,aimPen=0):
     self.name=name
     self.hp=hp
     self.playerTaunt=taunt
     self.alive=1
     self.defense=defense
     self.cover=cover
     self.aimPenalty=aimPen
     self.coverPosition=0
     self.wepSound=Sound().weaponSounds("Laser")
     self.deathSound=Sound().deathSounds("Sectoid")
     self.tauntSound=Sound().abilitySounds("Taunt")
     self.uponHit=Sound().enemyPainSounds("Sectoid")
Exemple #19
0
 def flying(self):
     self.performTimeSynchronizedMove()
     self.checkForCollisionWithWall()
     # make duck flying pattern more random
     if self.stoper.getCurrentTicks(
     ) - self.lastDirectionChange > self.flyingDirectionChangeThreshold:
         self.setRandomAngle()
         self.lastDirectionChange = self.stoper.getCurrentTicks()
         self.flyingDirectionChangeThreshold = randint(1000, 5000)
     if self.stoper.getCurrentTicks(
     ) - self.lastQuacked > self.quackingThreshold:
         Sound.play(Sounds.Quack)
         self.quackingThreshold = randint(1000, 8000)
         self.lastQuacked = self.stoper.getCurrentTicks()
def getWave(arr):
    sample = Sound(
        arr[0] * featureCoefs['Amplitude'], arr[1] * featureCoefs['Pitch'],
        arr[2] * featureCoefs['Decay'], arr[3] * featureCoefs['Type'],
        arr[4] * featureCoefs['Shift'], arr[5] * featureCoefs['Height'],
        arr[6] * featureCoefs['Slope']).getWave()
    for i in range(numFeatures, len(arr), numFeatures):
        sample += Sound(arr[i] * featureCoefs['Amplitude'],
                        arr[i + 1] * featureCoefs['Pitch'],
                        arr[i + 2] * featureCoefs['Decay'],
                        arr[i + 3] * featureCoefs['Type'],
                        arr[i + 4] * featureCoefs['Shift'],
                        arr[i + 5] * featureCoefs['Height'],
                        arr[i + 6] * featureCoefs['Slope']).getWave()
    return sample
Exemple #21
0
    def __init__(self, frame, size):
        self.size = size
        # make a new camera based on the size of the frame, then create the frame and add a start button.
        self.camera = Camera((0, 0), self.size[0] // Unit.UNIT,
                             self.size[1] // Unit.UNIT, Unit.UNIT)
        self.player = Player(100, 100, Unit.UNIT, Unit.UNIT)
        self.keyboard = Keyboard()
        self.result = States.STATES[1]

        frame.set_keydown_handler(self.keyboard.key_down)
        frame.set_keyup_handler(self.keyboard.key_up)

        sound = Sound()
        self.tiles = Mapper.get_start_tiles(self.camera)
        sound.play_death()
Exemple #22
0
    def __init__(self, screen, block):
        Sound.play_SE('brockbreak')
        super().__init__()
        self.screen = screen

        self.SPECIFIC_FALL_ACCELERATION = 0.5  # 落下加速度

        # 破壊ブロックの座標
        self.x = block.rect.left + int(block.width / 2)
        self.y_top = block.rect.top
        self.y_bottom = block.rect.top + 5

        # 速度
        self.x_top_speed = self.x_bottom_speed = 0.0
        self.y_top_speed = 8.0
        self.y_bottom_speed = self.y_top_speed - 1.0
Exemple #23
0
    def __init__(self, width, height):
        # We create the window
        self.width = width
        self.height = height
        FULLSCREEN = 0
        self.dimension = (self.width, self.height)
        self.screen = pygame.display.set_mode(self.dimension,  FULLSCREEN, 32)
        pygame.display.set_caption("TuxleTriad")

        elemText = ["Play", "Options", "Rules", "About", "Quit Game"]
        self.menu = []
        for elem in elemText:
            self.menu.append(Button(elem, "Dearest.ttf", white))

        posx = 400
        posy = 400 - (60 * len(elemText))

        for elem in self.menu:
            elem.rect.center = ((posx, posy))
            posy += 100

        self.bkgrnd, self.bkgrndRect = loadImage("background.jpg")
        self.bkgrndRect = self.bkgrnd.get_rect()

        # The Clock of the game, to manage the frame-rate
        self.clock = pygame.time.Clock()
        self.fps = 60

        # We start the Sound object, playing music and sounds.
        self.sound = Sound()

        # Needed to keep track of the game if we do a pause during the game.
        self.app = None

        self.main()
Exemple #24
0
    def __init__(self, width, height):
        self.FONT = "Playball.ttf"
    
        # We create the window
        self.width = width
        self.height = height
        fullscreen = pygame.NOFRAME
        self.dimension = (self.width, self.height)
        self.screen = pygame.display.set_mode(self.dimension,  fullscreen)
        pygame.display.set_caption("TuxleTriad")

        self._load_translation()


        self.bkgrnd, self.bkgrndRect = loadImage("background.jpg")
        self.bkgrndRect = self.bkgrnd.get_rect()

        # The Clock of the game, to manage the frame-rate
        self.clock = pygame.time.Clock()
        self.fps = 30

        # We start the Sound object, playing music and sounds.
        self.sound = Sound()

        # Needed to keep track of the game if we do a pause during the game.
        self.app = None
        

        self.main()
Exemple #25
0
def main():
    try:
        logger = Logger()
        sound = Sound(logger)
        #start the game
        aleph = Aleph(logger, sound, letters_gpios_pins_dict,
                      start_button_gpio_pin, blink_record_gpio_pin,
                      Config.lives).run_game()

    except (EnvironmentError, IOError) as err:
        sound.play_audio_file(Config.audio_fatal_error).play()
        logger.log_exception(err, locals())
        for key in letters_gpios_pins_dict.keys():
            GPIO.setup(key, GPIO.LOW)

    finally:
        GPIO.cleanup()
Exemple #26
0
    def __init__(self, argv, client, debugging_mqtt=False):

        super().__init__(argv, client, debugging_mqtt)

        self.logger.info(_("Props started"))

        if platform.system() != 'Windows':
            if self.logger.level != logging.DEBUG:
                self._gui.full_screen = True  # exit fullscreen with Esc (so for props without a keyboard)
        else:
            self._gui.width = 592
            self._gui.height = 333

        self._gui.bg = 'black'
        self._gui.tk.config(cursor="none")

        self._texte = Text(
            self._gui,
            "")  # "" value is translated to "-" for MQTT_DISPLAY_TOPIC
        self._texte.height = 1080
        self._texte.text_color = 'green'
        self._texte.font = "Helvetica"

        if platform.system() != 'Windows':
            self._texte.size = "90"
        else:
            self._texte.size = "28"

        self._sound = Sound(self._logger)

        if platform.system() != 'Windows':
            os.system("amixer cset numid=3 1")  # audio jack
            os.system("amixer set 'PCM' -- -1000")

        if self._mqttConnected:
            try:
                (result, mid) = self._mqttClient.publish(MQTT_DISPLAY_TOPIC,
                                                         "-",
                                                         qos=MQTT_DEFAULT_QoS,
                                                         retain=True)
            except Exception as e:
                self._logger.error("{0} '{1}' on {2}".format(
                    _("MQTT API : failed to call publish() for"), "-",
                    MQTT_DISPLAY_TOPIC))
                self._logger.debug(e)
 def __init__(self):
     self.connected = False
     self.gui_init = False
     self.msg_send = False
     self.run = True
     self.parent = None
     self.total_msg = 0
     self.messages = []
     self.hashlist = []
     self.colors = []
     self.total_msg_display = 6
     self.mw_status = [None] * self.total_msg_display
     self.status = [None] * self.total_msg_display
     self.buffer = 1024
     self.ore = 0
     self.qty_cargo = 0
     self.sound = Sound()
     self.load_config()
Exemple #28
0
    def __init__(self):
        super().__init__(1)
        self.anim = Animator()
        self.target_cam_pos = np.array([0, 0])
        self.mouse_pos = [0, 0]

        self.anim.load('img/cursor.png', 1, 1, np.array([0, 0]))
        self.anim.load('img/cursor_attack_start.png', 3, 4, np.array([0, 0]))
        self.anim.load('img/cursor_attack_doing.png', 1, 2, np.array([0, 0]))
        self.anim.load('img/cursor_attack_shot.png', 3, 1, np.array([0, 0]))
        self.interact_sound = Sound.load('sound/Pop.wav', 100)
        self.shot_sound = Sound.load('sound/Duck Toy.wav', 100)

        detect_limit = 20
        self.leftLimit = detect_limit
        self.rightLimit = View.views[0].w - detect_limit
        self.topLimit = View.views[0].h - detect_limit
        self.bottomLimit = detect_limit
Exemple #29
0
 def __init__(self, x, y, w, h, image=ResourcePaths.character_sprite_sheet):
     self.pos = Vector(x, y)
     self.dv = Vector(0, 0)
     self.direction = self.LEFT
     self.grounded = False
     self.w = w
     self.h = h
     self.tick_count = 0
     self.state = self.IDLE
     self.live_image = simplegui.load_image(ResourcePaths.heart)
     self.image = simplegui.load_image(image)
     self.cols = self.image.get_width() // self.w
     self.rows = self.image.get_height() // self.h
     self.sprite_index = 22
     self.last_point_standing = self.pos
     self.lives = 2#50
     self.player_sound = Sound()
     self.ui = UI()
Exemple #30
0
    def __init__(self):
        self.config = Config()
        pygame.init()
        pygame.display.set_caption("ISN ILIES")

        self.fond = self.config.getBlue()

        self.fenetre = pygame.display.set_mode(
            (self.config.getSurfaceW(), self.config.getSurfaceH()),
            pygame.FULLSCREEN)  #pygame.display.set_mode((surfaceW,surfaceH))

        self.sound = Sound()
        self.sound.inAcceuil()
        # Groupe de sprites utilisé pour l'affichage
        self.groupeGlobal = pygame.sprite.Group()
        self.statut = True
        self.listBullet = ListBullet(self.config)
        self.vaisseau = Vaisseau(self.config, self.listBullet)
Exemple #31
0
    def __init__(self):
        pygame.init()
        pygame.mixer.init()
        pygame.display.set_caption("Sokoben")

        self.asset = Asset()
        self.background = self.asset.createBackground()
        self.sound = Sound(self.asset)

        self.asset.loadImages()
        self.asset.loadLevels()
        self.asset.loadSounds()
        self.asset.loadFonts()
        self.asset.loadControls()

        self.levelIndex = 0
        self.level = None

        Controls.add('sound_enabled', self.asset.controls['sound_enabled'],
                     (const.MAPWIDTH * const.TILEWIDTH) - ((1 * 64) + 64), 10,
                     self.sound.enabled)
        Controls.add('sound_disabled', self.asset.controls['sound_disabled'],
                     (const.MAPWIDTH * const.TILEWIDTH) - ((1 * 64) + 64), 10,
                     not self.sound.enabled)
        Controls.add('reset', self.asset.controls['reset'],
                     (const.MAPWIDTH * const.TILEWIDTH) - ((2 * 64) + 64), 10,
                     True)
        Controls.add('undo', self.asset.controls['undo'],
                     (const.MAPWIDTH * const.TILEWIDTH) - ((3 * 64) + 64), 10,
                     True)
        Controls.add('next', self.asset.controls['next'],
                     (const.MAPWIDTH * const.TILEWIDTH) - ((4 * 64) + 64), 10,
                     True)
        Controls.add('back', self.asset.controls['back'],
                     (const.MAPWIDTH * const.TILEWIDTH) - ((5 * 64) + 64), 10,
                     True)
        Controls.add('solution', self.asset.controls['solution'],
                     (const.MAPWIDTH * const.TILEWIDTH) - ((6 * 64) + 64), 10,
                     False)

        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode(
            (const.MAPWIDTH * const.TILEWIDTH,
             (const.MAPHEIGHT - 1) * const.TILEANGLEHEIGHT + const.TILEHEIGHT))
Exemple #32
0
def readMusic(f):
    F = open(f, 'r')
    sounds = []
    for line in F:
        if (line[0] == "#"):
            continue
        l = line.split()
        for i in drange(0, len(l), 3):
            s = Sound(getNote(l[i]), float(l[i + 1]), float(l[i + 2]))
            sounds.append(s)

    return sounds
Exemple #33
0
    def __init__(self, screen, block, isLot=False):
        Sound.play_SE('coin')
        super().__init__()
        self.screen = screen
        self.block = block

        self.isLot = isLot  # 大量に生成させるか
        self.GENERATE_MAX = 20  # 生成する個数

        # ブロックデータの置き換え
        block.name = 'block3'
        block.image = LoadImage.image_list[block.name]

        # 画像の読み込み
        self.image = LoadImage.image_list['item1']

        # コインの座標
        self.x = self.block.x - SpritePlayer.scroll_sum
        self.y = block.rect.top - 8
        self.start_y = self.y
        self.y_speed = 4.0
    def createWeaponList(self):
        weaponList=[]
        rifleMag=Magazine(4,"normal","Standard Rifle Magazine")
        smgMag=Magazine(6,"normal","Standard SMG Magazine")
        shotgunMag=Magazine(2,"normal","Standard Shotgun Magazine")
        handgunMag=Magazine(8,"normal","Standard Handgun Magazine")
        knifeMag=Magazine(1000,"normal","fake Knife Mag")
        
        rifleSound=Sound().weaponSounds("Rifle")
        rifleSound.set_volume(.75)
        smgSound=Sound().weaponSounds("SMG")
        smgSound.set_volume(.5)
        shotgunSound=Sound().weaponSounds("Shotgun")
        handgunSound=Sound().weaponSounds("Handgun")
        knifeSound=Sound().weaponSounds("Knife")
        
        rifleReloadSound=Sound().reloadSounds("Rifle")
        smgReloadSound=Sound().reloadSounds("SMG")
        shotgunReloadSound=Sound().reloadSounds("Shotgun")
        handgunReloadSound=Sound().reloadSounds("Handgun")


        Rifle=Weapons(80,3,4,10,rifleMag,rifleSound,rifleReloadSound,"Rifle")
        SMG=Weapons(70,3,6,15,smgMag,smgSound,smgReloadSound,"SMG")
        Shotgun=Weapons(70,6,2,10,shotgunMag,shotgunSound,shotgunReloadSound,"Shotgun")
        Handgun=Weapons(80,2,8,15,handgunMag,handgunSound,handgunReloadSound,"Handgun")
        Knife=Weapons(100,20,1000,40,knifeMag,knifeSound,None,"Knife")
        weaponList.append(Rifle),weaponList.append(SMG),weaponList.append(Shotgun),weaponList.append(Handgun),weaponList.append(Knife)
        return weaponList
Exemple #35
0
    def death_animation(self):
        if self.player.isDeath:
            # 初期化
            if self._death_init:
                self._death_init = False

                Sound.stop_SE()
                Sound.stop_BGM()
                Sound.play_SE('death')

                self.player.x_speed = 0.0
                SpritePlayer.scroll = 0

                self._img_number = 3
                self._jump_time = 0
                self.player.y_speed = self.JUMP_SPEED

            self._jump_time += 1

            # 20フレーム後に落下
            if self._jump_time > 20:
                self.player.y_speed += SpritePlayer.FALL_ACCELERATION
                self.player.y += self.player.y_speed

            # 時間が経過したら戻って残機表示
            if self._jump_time >= 190:
                return True

            self.bg_update()
            if not self._inGoal_tower:
                self.player.update(self._direction(self._img_number))

        return False
Exemple #36
0
    def __init__(self, gid, senderID=None, msg=None, parent=None):
        super(QChatWindow, self).__init__()

        self.parent = parent
        self.tcp = parent.tcp
        self.tcp.recvAns.connect(self.parseAns)
        self.msgTimer = QTimer()
        self.GID = gid
        self.SID = parent.parent.SID
        self.UID = parent.UID
        self.members = []
        self.sound = Sound()
        self.initUI()

        if senderID:
            if type(senderID) == type(['list']):
                i = 0
                for UID in senderID:
                    self.appendText(UID,msg[i])
                    i += 1
            else:
                self.appendText(senderID,msg)
Exemple #37
0
	def afficheInfos(self,filename):
		"""
		Affiche les informations sur le fichier Wave "filename",
		ainsi que le spectre et le spectrogramme du	signal.
		Le spectre et le spectrogramme sont également enregistrés
		dans le même dossier que le fichier wave.
		ATTENTION : le fichier Wave doit bien avoir l'extension .wav
		(pourrait être amélioré)
		"""
		from Sound import Sound
		print '#####################################'
		print '# Informations sur le fichier écrit #'
		print '#####################################'
		sound = Sound(filename)
		print sound
		sound.displaySpectrum()
		sound.saveSpectrum(filename[:-4] + '_spectrum.png')
		sound.displaySpectrogram(title='Spectrogramme du signal')
		sound.saveSpectrogram(filename[:-4] + '_spectrogram.png',title='Spectrogramme du signal')
 def __init__(self,weapons=[],hp=20,imparement=0,defense=30,buff=0):
     self.name="Trooper"
     self.hp=hp
     self.imparement=imparement
     
     self.inventory=[Grenade(),Grenade(),Grenade(),Grenade(),Healing("Medkit",10),Healing("Medkit",10)]
     self.ammoBelt=None
     self.seconaryAmmoBelt=None
     self.defense=defense
     self.aimPenalty=0
     self.coverPosition=0
     self.buff=buff
     self.weapons=weapons
     self.cover=0
     self.currentWeapon=None
     self.deathSound=Sound().deathSounds("Player")
class Grenade(object):
    def __init__(self,damage=4):
        self.name="Grenade"
        self.damage=damage
        self.boomSound=Sound().weaponSounds("Grenade")

#*************************************
#RETURN CLASS VARIABLES
#*************************************

    def playSound(self):
        return self.boomSound.play()

    def explode(self):
        return self.damage

    def getName(self):
        return self.name
Exemple #40
0
class LoginWindow(QWidget):
   
    def __init__(self, ip=None, port=None, parent=None):
        super(LoginWindow, self).__init__()

        # Perform Tcp Connection
        self.tcp = TcpClient(ip, port)
        self.tcp.recvAns.connect(self.parseAns)
        # Connect errorhandling
        self.tcp.ConError.connect(self.tcpError)
        self.tcp.connected.connect(self.tcpConnected)
        # Setup reconnect Timer
        self.rconTimer = QTimer(self)
        self.rconTimer.timeout.connect(self.tryReconnect)
        # Create Sound Object
        self.sound = Sound()

        # init userData
        self.userName = None
        self.passwd = None
        self.StatusUSER = False
        self.StatusPASS = False
        self.conStat=False
        self.SID = None
        self.UID = None

        # Adjust Window ----------------------------------------------
        # Set Title
        self.setWindowTitle('PySIMS')
        # Set Windwo Icon
        self.setWindowIcon(QIcon('img/pysims_icon_16.png')) 
        self.setFixedSize(200,350)

        # Create widgets ---------------------------------------------
        # Create Logo
        self.logo = QPixmap('img/pysims_logo.png')
        self.logoLabel = ClickableLabel(self)
        self.logoLabel.setPixmap(self.logo)

        # Create Forgot Password
        self.forgotPassLabel = ClickableLabel("<font size=10px>Passwort vergessen?</font>")
        #self.forgotPassLabel.set
        # Create Sign Up
        self.SignUpLabel = ClickableLabel("<font size=10px>Registrieren</font>")

        # Create Message Label
        self.messageLabel = QLabel()

		# Create Username Input
        self.usernameEdit = QLineEdit("")
        self.usernameLabel = QLabel("Benutzername:")

        # Create Password Input
        self.passwordEdit = QLineEdit("")
        self.passwordLabel = QLabel("Passwort:")
        # Set Password Input to not readable
        self.passwordEdit.setEchoMode(QLineEdit.Password)

        # Create Login Button
        self.loginBtn = QPushButton("Login")

        # Create layout and add widgets ------------------------------
        # Build Logo Layout
        hboxLogo = QHBoxLayout()
        hboxLogo.addStretch(1)
        hboxLogo.addWidget(self.logoLabel)
        hboxLogo.addStretch(1)

        # Build Lower Layout
        hboxReg = QHBoxLayout()
        hboxReg.addWidget(self.forgotPassLabel)
        hboxReg.addStretch(1)
        hboxReg.addWidget(self.SignUpLabel)

        # Build Main Layout
        layout = QVBoxLayout()
        layout.addLayout(hboxLogo)
        layout.addWidget(self.messageLabel)
        layout.addWidget(self.usernameLabel)
        layout.addWidget(self.usernameEdit)
        layout.addWidget(self.passwordLabel)
        layout.addWidget(self.passwordEdit)
        layout.addWidget(self.loginBtn)
        layout.addLayout(hboxReg)
        # Set dialog layout
        self.setLayout(layout)

        # Signals and Slots ------------------------------------------
        # Add button signal to sendLogin slot
        self.loginBtn.clicked.connect(self.sendUser)
        self.usernameEdit.returnPressed.connect(self.jumpFunction1)
        self.passwordEdit.returnPressed.connect(self.jumpFunction2)
        
        # Add mouseReleaseEvent to forgotPass Slot
        self.connect(self.forgotPassLabel, SIGNAL('clicked()'),self.forgotPass)
        # Add mouseReleaseEvent to register Slot
        self.connect(self.SignUpLabel, SIGNAL('clicked()'),self.register)

        self.connect(self.logoLabel, SIGNAL('clicked()'),self.logoClick)  

    def jumpFunction1(self):
        self.passwordEdit.setFocus()

    def jumpFunction2(self):
        
        if(self.conStat==True):
            self.sendUser()

    # Send Username to Server
    def sendUser(self):
        self.userName = self.usernameEdit.text()
        self.passwd = self.passwordEdit.text()
        if self.userName and self.passwd:     
            print ("Send Username")#: %s" % self.userName)
            
            # Show loader animation
            self.loader = QMovie('img/loader.gif')
            self.logoLabel.setMovie(self.loader)
            self.loader.start()

            req = 'USER ' + self.userName + '\r\n'
            self.tcp.sendReq(req)
        elif not self.userName:
            self.wrongData('USER')
        elif not self.passwd: 
            self.wrongData('PASS')

    # Send Password to Server
    def sendPass(self):
        self.passwd = self.passwordEdit.text()
        if self.passwd:
            print ("Send Password")#: %s" % self.passwd)

            req = 'PASS ' + self.passwd + '\r\n'
            self.tcp.sendReq(req)

    # If all Data is correct the user will be logged in
    def login(self):
        self.sound.login()
        self.window = MainWindow(parent=self)
        self.window.setAttribute(Qt.WA_DeleteOnClose)
        self.window.show()

        self.close()

    # If there is wrong Data the Labels are colored Red
    def wrongData(self, data):
        self.logoLabel.setPixmap(self.logo)
        if data == 'USER':
            self.usernameLabel.setText("<font color=red>Benutzername:</font>")

        elif data == 'PASS':
            self.passwordLabel.setText("<font color=red>Passwort:</font>")


    # Send ForgotPass to Server
    def forgotPass(self):
        #print ("Username: %s" % self.usernameEdit.text())   
        #pass
        self.ForgetPwWindow=ForgetPwWindow(parent=self)
        self.ForgetPwWindow.show()

    # Call register Routine
    def register(self):

        self.RegWindow = RegisterWindow(parent=self)
        #RegWindow.setAttribute(Qt.WA_DeleteOnClose)
        self.RegWindow.exec_()

        #print ("Username: %s" % self.usernameEdit.text())

    # Abbort Login (TODO)
    def logoClick(self):
        print ("Logo geklickt!")
        # Show normal Logo
        self.logoLabel.setPixmap(self.logo)

    # Parse Answer from Server
    @Slot(str, str)
    def parseAns(self, lastReq, ServerAns):
        #print ('--------LastReq: ', lastReq, ' Ans: ', ans)
        lastCommand = lastReq.split()

        for ans in ServerAns.split('\r\n\r\n'):
            ans = ans.split('\r\n')
            #print (lastCommand)
            #print (ans)
            
            # Answer = USER?
            if ans[0] == 'USER OK':
                # USER is accepted
                print ('USER accepted')
                self.StatusUSER = True
                self.usernameLabel.setText("<font color=black>Benutzername:</font>")
                self.sendPass()
                
            elif ans[0] == 'USER ERR':
                self.wrongData('USER')
                self.StatusUSER = False
                print ('USER denied')

            # Answer = PASS? and USER was allready accepted              
            elif ans[0] == 'PASS OK' and self.StatusUSER:
                # PASS is accepted
                print ('PASS accepted')
                self.passwordLabel.setText("<font color=black>Passwort:</font>")
                self.StatusPASS = True
                UID = ans[1].split(':')
                SID = ans[2].split(':')

                if UID[0] == 'UID':
                    self.UID = UID[1]

                if SID[0] == 'SID':
                    self.SID = SID[1]
                    self.login()

            elif ans[0] == 'PASS ERR':
                self.wrongData('PASS')
                self.StatusPASS = False
                print ('PASS denied')

            elif ans[0] == '':
                pass

    def tcpError(self, err):
        # React to connectionerror
        if err == 'ConnectionRefused' or err == 'ConnectionClosed':
            # Show Error Mesasge to User
            self.messageLabel.setText("<font color=red>Server nicht erreichbar!</font>")
            # Close Failed Connection
            self.tcp.abort()
            # Disable Buttons
            self.loginBtn.setEnabled(False)
            self.conStat=False
            # Start timer
            self.rconTimer.start(5000)
        print(err)

    def tryReconnect(self):
        # Try to reach the Server
        self.rconTimer.stop()
        self.messageLabel.setText("<font color=red>Verbinung wird aufgebaut...</font>")
        self.tcp.con()

    def tcpConnected(self):
        # TCP Connection was successful
        # Stop timer
        self.rconTimer.stop()
        self.logoLabel.setPixmap(self.logo)
        # Enable Login Funktions again
        self.messageLabel.setText('')
        self.loginBtn.setEnabled(True)
        self.conStat=True
Exemple #41
0
class QChatWindow(QWidget):

    def __init__(self, gid, senderID=None, msg=None, parent=None):
        super(QChatWindow, self).__init__()

        self.parent = parent
        self.tcp = parent.tcp
        self.tcp.recvAns.connect(self.parseAns)
        self.msgTimer = QTimer()
        self.GID = gid
        self.SID = parent.parent.SID
        self.UID = parent.UID
        self.members = []
        self.sound = Sound()
        self.initUI()

        if senderID:
            if type(senderID) == type(['list']):
                i = 0
                for UID in senderID:
                    self.appendText(UID,msg[i])
                    i += 1
            else:
                self.appendText(senderID,msg)

    def initEditForm(self):
        
        self.editFormContainer = QWidget()

        # Layout for the Edit Form
        self.editForm = QHBoxLayout()

        # Create Control Section
        controlSect = QVBoxLayout()

        # Text Field
        self.TextEdit = QTextEdit()
        self.TextEdit.setMaximumSize(390,70)

        # Send Buttoen
        self.SendBtn = QPushButton()
        self.SendBtn.setIcon(QIcon('img/chat/send.png'))
        self.SendBtn.setShortcut('Ctrl+Return')
        #self.SendBtn.setIconSize(QSize(20,20))

        # Emoticons Button
        self.EmotBtn = QPushButton()
        self.EmotBtn.setIcon(QIcon('img/chat/emot.png'))
        #self.EmotBtn.setIconSize(QSize(20,20))

        # Add Widget to Control Section
        controlSect.addWidget(self.SendBtn)
        controlSect.addWidget(self.EmotBtn)
        controlSect.addStretch(1)

        # Add Widgets to Main Form
        self.editForm.addWidget(self.TextEdit)
        self.editForm.addLayout(controlSect)

        # Add the Main Form to Container Widget
        self.editFormContainer.setLayout(self.editForm)

    def initShowChat(self):

        self.showChatContainer = QWidget()

        ContainerLayout = QVBoxLayout()

        self.showChat = QTextBrowser()
        #self.showChat.setStyleSheet("background: rgb(255,255,255); color: black")
        self.showChat.setMinimumSize(359,20)

        policy = self.showChat.sizePolicy()
        policy.setHorizontalStretch(1)
        self.setSizePolicy(policy)

        ContainerLayout.addLayout(self.MemberControl)
        ContainerLayout.addWidget(self.showChat)

        self.showChatContainer.setLayout(ContainerLayout)

    def initMemberControl(self):
        self.MemberControl = QHBoxLayout()

        self.MemberBtn = QPushButton()
        self.MemberBtn.setIcon(QIcon('img/chat/group.png'))
        self.MemberBtn.setToolTip('Mitglieder des Chats auswaehlen')
        self.MemberBtn.clicked.connect(self.openAddWindow)

        #self.RemoveUserBt = QPushButton()
        #self.RemoveUserBt.setIcon(QIcon('img/chat/rem.png'))

        self.MemberControl.addWidget(self.MemberBtn)
        #self.MemberControl.addWidget(self.RemoveUserBt)
        self.MemberControl.addStretch(1)

    def initUI(self):

        self.requestMembers()

        # Adjust Window ----------------------------------------------
        self.resize(400, 300)
        self.setFixedWidth(400)
        self.setWindowTitle('GID: ' + self.GID)
        StatusImgPath = path.join('img/chat/chat.png')
        self.setWindowIcon(QIcon(StatusImgPath)) 

        self.initMemberControl()
        self.initEditForm()
        self.initShowChat()
        
        # Build Main Layout
        layout = QHBoxLayout(self)
        # Splitter Layout
        splitter = QSplitter(Qt.Vertical)
        splitter.setSizes([300,50])

        #splitter.addLayout(self.Control)
        splitter.addWidget(self.showChatContainer)
        splitter.addWidget(self.editFormContainer)
        # Add Splitter to Main Layout
        layout.addWidget(splitter)
        self.setLayout(layout)
        #QApplication.setStyle(QStyleFactory.create('Cleanlooks'))

        self.SendBtn.clicked.connect(self.sendMsg)
        

    def appendText(self, senderID, text, sendtime=None):

        if not sendtime:
            sendtime = time.time()

        #print('MSG from ID:', senderID)
        #print('Time:', sendtime)
        #for user in self.parent.contactList:
            #print (user)

        if senderID in self.parent.contactList and senderID != self.UID:
            senderName = self.parent.contactList[senderID]['name']
        elif senderID == self.UID:
            senderName = 'Ich'
        else:
            senderName = 'Unbekannt'

        self.showChat.append(TextTools.newMsg(senderName,text,sendtime))
        

    def sendMsg(self):
        
        text = self.TextEdit.toPlainText()

        if text:
            req = 'SENDMSG\r\n'
            req += 'SID:' + self.SID + '\r\n'
            req += 'GID:' + self.GID + '\r\n'
            req += text + '\r\n\r\n'
            self.tcp.sendReq(req)

            self.appendText(self.UID,text)

    def sendAck(self):
        #self.tcp.sendReq('ACK\r\n')
        #print('ACK sent')
        pass

    def requestMembers(self):
        req = "GETGRPMBRS\r\n"
        req += "GID:"
        req += self.GID
        req += "\r\n\r\n"
        self.tcp.sendReq(req)

    def updateMembers(self, memberList):
        self.members = memberList
        title = "Chat mit: "
        for uid in memberList:
            if not uid == self.UID:
                title += self.parent.contactList[uid]['name'] + " | "
        self.setWindowTitle(title[:-2])

    def lostCon(self):
        print('Hilfe')

    @Slot(str, str)
    def newMsg(self, senderID, msg):
        pass

    @Slot(str, str)
    def parseAns(self, lastReq, ServerAns):
        for ans in ServerAns.split('\r\n\r\n'):
            ans = ans.split('\r\n')
            print('------  Chat Window Recived: -----')
            print(ans)
            print('----------------------------------')

            if ans[0] == 'DLVMSG':
                GID = ans[1].split(':')
                UID = ans[2].split(':')
                msg = ans[3]
                #print('GID:', GID)
                #print('UID:', UID)
                if GID[0] == 'GID':
                    if GID[1] == self.GID:
                        if UID[0] == 'UID':
                            senderID = UID[1]
                            print('Display new Message')
                            self.appendText(senderID,msg)
                            self.sendAck()
                            self.sound.newMsg()

            elif ans[0] == 'MEMBERS':
                GID = ans[1].split(':')
                if GID[0] == 'GID' and GID[1] == self.GID:

                    members = []
                    for member in ans[1:]:
                        if member:
                            m = member.split(':')
                            if m[0] == 'UID':
                                members.append(m[1])
                    print('Updating Userlist')
                    self.updateMembers(members)

            elif ans[0] == 'MSG OK':
                GID = ans[1].split(':')
                if GID[0] == 'GID' and GID[1] == self.GID: 
                    print('Message delivered')
                    self.TextEdit.setText('')

    def openAddWindow(self):
        self.editWindow = chatControl.chatEditWindow(parent = self)
        self.editWindow.show()

    def closeEvent(self, ev):
        del self.parent.ChatWindows[self.GID]
        try:
            self.editWindow.close()
        except:
            pass
        finally:
            print('Chat closed!')
Exemple #42
0
# -*- coding:cp850 -*-

# http://matplotlib.sourceforge.net/
# http://docs.scipy.org/doc/scipy/reference/

import numpy as np
import scipy as sp
import scipy.fftpack as fftpack
import matplotlib as mpl
import matplotlib.pyplot as plt


from Sound import Sound

from Gamme import Gamme

if __name__ == '__main__':
	
	son = Sound('../ressources/NOTEguitare.wav')
	print son
	son.displaySpectrum()
	son.displaySpectrogram(title='Spectrogramme du signal original')
	son.saveSpectrum('spectre.png')
	son.saveSpectrogram('spectrogramme.png',title='Spectrogramme du signal original')
Exemple #43
0
class Application():
    """Main class of the game, manage the window"""
    def __init__(self, width, height, screen=None, soundInstance=None,
                  boss=None):
        # We create the window
        self.width = width
        self.height = height
        if screen == None:
            self.screen = pygame.display.set_mode((self.width, self.height))
        else:
            self.screen = screen

        if soundInstance == None:
            self.Sound = Sound()
        else:
            self.Sound = soundInstance
            print self.Sound.soundVolume

        self.background, self.backgroundRect = loadImage("background.jpg")

        # We keep the Menu instance if we are running TuxleTriad from Menu.py
        if boss != None:
            self.boss = boss
            self.boss.app = self
        else:
            self.boss = None

        # The Clock of the game, to manage the frame rate
        self.clock = pygame.time.Clock()
        self.fps = 60
        Cards1 = []
        Cards2 = []

        # We generate two  and draw 5 cards from each
        # to have an entire Hand of Card
        list1 = [i for i in range(len(allCards))]
        random.shuffle(list1)
        list2 = [i for i in range(len(allCards))]
        random.shuffle(list2)
        for i in range(5):
            number = list1[0]
            Cards1.append(Card(number, 1))
            list1.remove(number)
        for i in range(5):
            number = list2[0]
            Cards2.append(Card(number, -1))
            list2.remove(number)

        # We create the Hands to manage the lists of cards
        self.player1Hand = Hand(Cards1, 1)
        self.player2Hand = Hand(Cards2, -1)

        # We create the Score
        self.scorePlayer1 = Score("5", 1, self.width, self.height)
        self.scorePlayer2 = Score("5", -1, self.width, self.height)

        # With this variable, we cannot do anything until the animation
        #played is finished.
        self.animation = 0

        # If we have to play the animation in different directions
        self.sensAnimation = 0
        self.player = 1

        #self.Sound = Sound()
        self.position = None
        self.CARD = None

        # We create the field of the game, 3x3.
        sizeCard = self.player1Hand.cards[0].image.get_size()
        self.field = Field(self.width, self.height, sizeCard)
        self.alphaAnimation = 255
        self.emptyCase = 9

        # Manage the winner congratulations font
        self.winner = None
        self.winnerFont = pygame.font.Font(None, 60)

        # Manage the display of the name of the card selected
        self.cardFont = pygame.font.Font(None, 40)
        self.cardFontSurf = None

        # Manage the background for the name of the card selected
        self.backCard, self.backCardRect = loadImage("name.png")

        self.main()

    def update(self):
        self.screen.blit(self.background, self.background.get_rect())
        for card in self.player1Hand.cards:
            self.screen.blit(card.image, card.rect)
            if card == self.CARD:
                name = self.CARD.name
                self.cardFontSurf = self.cardFont.render(name, True, white)
                self.cardFontRect = self.cardFontSurf.get_rect()
                self.cardFontRect.midbottom = self.backgroundRect.midbottom
                self.cardFontRect.y -= 10
                self.backCardRect.center = self.cardFontRect.center
                self.backCardRect.centery -= 0

        for card in self.player2Hand.cards:
            if card == self.CARD:
                name = self.CARD.name
                self.cardFontSurf = self.cardFont.render(name, True, white)
                self.cardFontRect = self.cardFontSurf.get_rect()
                self.cardFontRect.midbottom = self.backgroundRect.midbottom
                self.cardFontRect.y -= 10
            self.screen.blit(card.image, card.rect)

        self.scorePlayer1.update()
        self.scorePlayer2.update()
        self.screen.blit(self.scorePlayer1.surface, self.scorePlayer1.rect)
        self.screen.blit(self.scorePlayer2.surface, self.scorePlayer2.rect)
        if self.winner != None:
            self.screen.blit(self.winnerSurface, self.winnerRect)

        if self.cardFontSurf != None:
            self.screen.blit(self.backCard, self.backCardRect)
            self.screen.blit(self.cardFontSurf, self.cardFontRect)
            self.cardFontSurf = None

        pygame.display.flip()
        self.clock.tick(self.fps)

    def main(self):
        self.cardsOwner()
        self.update()
        while 1:
            if self.animation == 1:
                # We continue the animation
                self.putCard()
                self.update()
            else:
                # We over the animation and now the next player have to play.
                if self.sensAnimation == 1:
                    self.player = self.player * -1
                    self.sensAnimation = 0

            for event in pygame.event.get():
                if event.type == MOUSEBUTTONUP and self.animation == 0:
                    if self.winner == None:
                        self.playCard()
                elif event.type == QUIT:
                    audio = [self.Sound.soundVolume, self.Sound.musicVolume]
                    setConfig("config.txt", audio)
                    pygame.quit()
                    sys.exit()
                else:
                    # We get the status of all key on keyboard.
                    # Then we select the one at place 27: Escape.
                    # We can do this only if we ran the game
                    # with Menu.py and not directly from main.py
                    if pygame.key.get_pressed()[27] and self.boss != None:
                        self.boss.main()

            pygame.display.flip()
            self.clock.tick(self.fps)

    def playCard(self):
        """When player has to play a card"""

        coords = pygame.mouse.get_pos()

        if self.player == 1:
        # Player 1
            for card in self.player1Hand.cards:
                if card.rect.collidepoint(coords) and card.inHand:
                    self.CARD = card
                    self.selectedCard()
                    break
            if not self.CARD == None:
            # If we clicked on a card.
            # We wait for the event 'MOUSEBUTTONUP', so first we clean the
            #queue event. Then we deactivate the MOUSEMOTION event, because
            #it causes the card to be put randomly on the field!
            #We wait an event, for example a touch on the keyboard
            #pressed, or MOUSEBUTTONUP, but not only, and we reactivate
            #MOUSEMOTION, we could need it later.
                self.deactivate()
                if not self.animation:
                    pygame.event.wait()
                while pygame.event.peek(MOUSEBUTTONUP) and not self.animation:
                    pass
                self.reactivate()
                # If the player clicked on the field this time, we test
                #each cases of the Field.
                if self.field.rect.collidepoint(pygame.mouse.get_pos()):
                    for case in self.field.fieldRects:
                        if case.collidepoint(pygame.mouse.get_pos()):
                            self.position = case.topleft
                            if not self.caseFilled():
                                self.animation = 1
                                self.putCard()
                                self.cardsOwner()
                            return
                else:
                    self.deselectedCard()
                    self.CARD = None

        if self.player == -1:
        # Player -1...I mean Player 2
            for card in self.player2Hand.cards:
                if (card.rect.collidepoint(coords) and card.inHand):
                    self.CARD = card
                    self.selectedCard()
                    break
            if not self.CARD == None:
                # Same as before
                self.deactivate()
                if not self.animation:
                    pygame.event.wait()
                while pygame.event.peek(MOUSEBUTTONUP) and not self.animation:
                    pass
                self.reactivate()
                if self.field.rect.collidepoint(pygame.mouse.get_pos()):
                    for case in self.field.fieldRects:
                        if case.collidepoint(pygame.mouse.get_pos()):
                            self.position = case.topleft
                            if not self.caseFilled():
                                self.animation = 1
                                self.putCard()
                                self.cardsOwner()
                            return
                else:
                    self.deselectedCard()
                    self.CARD = None

    def putCard(self):
            """Animation of a card put on the field"""

            if self.CARD.inHand == 1:
            # We check if self..CARD is in the player's Hand
                self.Sound.playPutCard()

            # We drop the card off the Hand
            if self.CARD.inHand == 1:
                self.CARD.inHand = 0

            # Depending of the direction of the animation, we make the card
            # being invisible or visible again.
            if self.sensAnimation == 0:
                self.alphaAnimation -= 25
                self.CARD.image.set_alpha(self.alphaAnimation)
            elif self.sensAnimation == 1:
                self.alphaAnimation += 25
                self.CARD.image.set_alpha(self.alphaAnimation)

            # We change the position of the card and the animation's direction
            if self.CARD.image.get_alpha() == 5:
                self.CARD.rect.topleft = self.position
                self.sensAnimation = 1

            if self.CARD.image.get_alpha() == 255 and self.sensAnimation == 1:
                # We have put the card on the field and the animation is over
                #Now we have to look if that card captured some of the ennemy's
                self.animation = 0
                adjacentCards = self.getAdjacent()
                capturedCard = adjacent(self.CARD, adjacentCards)
                self.changeOwner(capturedCard)
                self.emptyCase -= 1
                self.CARD = None

            if self.emptyCase == 0:
                self.winAnimation()

    def selectedCard(self):
        """Player has selected a card
        But not yet a place on the field"""
        for i in range(5):
            self.CARD.rect.centerx += 4 * self.player
            self.update()

    def deselectedCard(self):
        """Finally, the player wants an other card"""
        for i in range(5):
            self.CARD.rect.centerx -= 4 * self.player
        self.CARD = None
        self.update()

    def deactivate(self):
        """Deactivate MOUSEMOTION event and clean the queue"""
        pygame.event.set_blocked(MOUSEMOTION)
        pygame.event.clear()

    def reactivate(self):
        """Get back MOUSEMOTION"""
        pygame.event.set_allowed(MOUSEMOTION)

    def caseFilled(self):
        """Say if there is already a card in the case"""
        for card in self.player1Hand.cards:
            if card.rect.topleft == self.position:
                return 1
        for card in self.player2Hand.cards:
            if card.rect.topleft == self.position:
                return 1
        return 0

    def cardsOwner(self):
        """Which cards is owned by who?"""
        cardPlayer = 0
        for card in self.player1Hand.cards:
            if card.owner == self.player:
                cardPlayer += 1
        for cards in self.player2Hand.cards:
            if cards.owner == self.player:
                cardPlayer += 1
        if self.player == 1:
            self.scorePlayer1.updateScore(cardPlayer)
            self.scorePlayer2.updateScore(10 - cardPlayer)
        elif self.player == -1:
            self.scorePlayer1.updateScore(10 - cardPlayer)
            self.scorePlayer2.updateScore(cardPlayer)

    def getAdjacent(self):
        """Get all the adjacent cards of the first one put"""
        posx, posy = self.CARD.rect.topleft
        adjacentCards = [None, None, None, None]
        if self.player == 1:
            for card in self.player2Hand.cards:
                if card.inHand == 0:
                    if card.rect.collidepoint((posx, posy - 144)):
                        # We first look at the card on the top
                        adjacentCards[0] = card

                    if card.rect.collidepoint((posx + 113, posy)):
                        # We look at the card on the right
                        adjacentCards[1] = card

                    if card.rect.collidepoint((posx, posy + 144)):
                        # We look at the card on the bottom
                        adjacentCards[2] = card

                    if card.rect.collidepoint((posx - 113, posy)):
                        # We look at the card on the left
                        adjacentCards[3] = card
        elif self.player == -1:
            for card in self.player1Hand.cards:
                if card.inHand == 0:
                    if card.rect.collidepoint((posx, posy - 144)):
                        # We first look at the card on the top
                        adjacentCards[0] = card

                    if card.rect.collidepoint((posx + 113, posy)):
                        # We look at the card on the right
                        adjacentCards[1] = card

                    if card.rect.collidepoint((posx, posy + 144)):
                        # We look at the card on the bottom
                        adjacentCards[2] = card

                    if card.rect.collidepoint((posx - 113, posy)):
                        # We look at the card on the left
                        adjacentCards[3] = card
        return adjacentCards

    def changeOwner(self, cards):
        for card in cards:
            if card.owner == 1:
                self.player1Hand.cards.remove(card)
                self.player2Hand.cards.append(card)
            if card.owner == -1:
                self.player2Hand.cards.remove(card)
                self.player1Hand.cards.append(card)
            self.capturedAnimation(card)
        self.cardsOwner()

    def capturedAnimation(self, card):
        # We want the sound of the card put played before doing anything more
        self.update()
        while (pygame.mixer.get_busy()):
            pass

        # self.Sound.capturedCard.play()
        width = card.rect.width  # we expect 113. If not please change format.
        height = card.image.get_rect().height  # Here we expect 139.
        topleft = list(card.rect.topleft)
        print height, "\t", topleft
        step = 16

        while(width != 1):
            width -= step
            topleft[0] += step / 2
            getCard(card)
            card.image = pygame.transform.scale(card.image, (width, height))
            card.rect = card.image.get_rect()
            card.rect.topleft = topleft
            self.update()

        card.owner *= -1
        card.changeOwner(card.rect.center)

        while (width != 113):
            width += step
            topleft[0] -= step / 2
            getCard(card)
            card.image = pygame.transform.scale(card.image, (width, height))
            card.rect = card.image.get_rect()
            card.rect.topleft = topleft
            self.update()

    def winAnimation(self):
        if self.scorePlayer1.score > self.scorePlayer2.score:
            self.winner = u"Blue win!"
        elif self.scorePlayer2.score > self.scorePlayer1.score:
            self.winner = u"Red win!"
        else:
            self.winner = u"Equality!"
        self.winnerSurface = self.winnerFont.render(self.winner, True, white)
        self.winnerRect = self.winnerSurface.get_rect()
        self.winnerRect.midtop = self.backgroundRect.midtop
        self.winnerRect.y += 10
Exemple #44
0
    def __init__(self, ip=None, port=None, parent=None):
        super(LoginWindow, self).__init__()

        # Perform Tcp Connection
        self.tcp = TcpClient(ip, port)
        self.tcp.recvAns.connect(self.parseAns)
        # Connect errorhandling
        self.tcp.ConError.connect(self.tcpError)
        self.tcp.connected.connect(self.tcpConnected)
        # Setup reconnect Timer
        self.rconTimer = QTimer(self)
        self.rconTimer.timeout.connect(self.tryReconnect)
        # Create Sound Object
        self.sound = Sound()

        # init userData
        self.userName = None
        self.passwd = None
        self.StatusUSER = False
        self.StatusPASS = False
        self.conStat=False
        self.SID = None
        self.UID = None

        # Adjust Window ----------------------------------------------
        # Set Title
        self.setWindowTitle('PySIMS')
        # Set Windwo Icon
        self.setWindowIcon(QIcon('img/pysims_icon_16.png')) 
        self.setFixedSize(200,350)

        # Create widgets ---------------------------------------------
        # Create Logo
        self.logo = QPixmap('img/pysims_logo.png')
        self.logoLabel = ClickableLabel(self)
        self.logoLabel.setPixmap(self.logo)

        # Create Forgot Password
        self.forgotPassLabel = ClickableLabel("<font size=10px>Passwort vergessen?</font>")
        #self.forgotPassLabel.set
        # Create Sign Up
        self.SignUpLabel = ClickableLabel("<font size=10px>Registrieren</font>")

        # Create Message Label
        self.messageLabel = QLabel()

		# Create Username Input
        self.usernameEdit = QLineEdit("")
        self.usernameLabel = QLabel("Benutzername:")

        # Create Password Input
        self.passwordEdit = QLineEdit("")
        self.passwordLabel = QLabel("Passwort:")
        # Set Password Input to not readable
        self.passwordEdit.setEchoMode(QLineEdit.Password)

        # Create Login Button
        self.loginBtn = QPushButton("Login")

        # Create layout and add widgets ------------------------------
        # Build Logo Layout
        hboxLogo = QHBoxLayout()
        hboxLogo.addStretch(1)
        hboxLogo.addWidget(self.logoLabel)
        hboxLogo.addStretch(1)

        # Build Lower Layout
        hboxReg = QHBoxLayout()
        hboxReg.addWidget(self.forgotPassLabel)
        hboxReg.addStretch(1)
        hboxReg.addWidget(self.SignUpLabel)

        # Build Main Layout
        layout = QVBoxLayout()
        layout.addLayout(hboxLogo)
        layout.addWidget(self.messageLabel)
        layout.addWidget(self.usernameLabel)
        layout.addWidget(self.usernameEdit)
        layout.addWidget(self.passwordLabel)
        layout.addWidget(self.passwordEdit)
        layout.addWidget(self.loginBtn)
        layout.addLayout(hboxReg)
        # Set dialog layout
        self.setLayout(layout)

        # Signals and Slots ------------------------------------------
        # Add button signal to sendLogin slot
        self.loginBtn.clicked.connect(self.sendUser)
        self.usernameEdit.returnPressed.connect(self.jumpFunction1)
        self.passwordEdit.returnPressed.connect(self.jumpFunction2)
        
        # Add mouseReleaseEvent to forgotPass Slot
        self.connect(self.forgotPassLabel, SIGNAL('clicked()'),self.forgotPass)
        # Add mouseReleaseEvent to register Slot
        self.connect(self.SignUpLabel, SIGNAL('clicked()'),self.register)

        self.connect(self.logoLabel, SIGNAL('clicked()'),self.logoClick)  
 def __init__(self,damage=4):
     self.name="Grenade"
     self.damage=damage
     self.boomSound=Sound().weaponSounds("Grenade")
Exemple #46
0
class Menu(pygame.sprite.Sprite):
    def __init__(self, width, height):
        self.FONT = "Playball.ttf"
    
        # We create the window
        self.width = width
        self.height = height
        fullscreen = pygame.NOFRAME
        self.dimension = (self.width, self.height)
        self.screen = pygame.display.set_mode(self.dimension,  fullscreen)
        pygame.display.set_caption("TuxleTriad")

        self._load_translation()


        self.bkgrnd, self.bkgrndRect = loadImage("background.jpg")
        self.bkgrndRect = self.bkgrnd.get_rect()

        # The Clock of the game, to manage the frame-rate
        self.clock = pygame.time.Clock()
        self.fps = 30

        # We start the Sound object, playing music and sounds.
        self.sound = Sound()

        # Needed to keep track of the game if we do a pause during the game.
        self.app = None
        

        self.main()

    def main(self):
        elemText = [_("Play"), _("Options"), _("Rules"), _("About"),
                         _("Quit Game")]
        self.menu = []
        for elem in elemText:
            self.menu.append(Text(elem, self.FONT, white, 40))
        posx = 400
        posy = 400 - (60 * len(elemText))
        for elem in self.menu:
            elem.rect.center = ((posx, posy))
            posy += 100
        pygame.event.clear()
        self.updateMenu()
        while 1:
            pygame.display.flip()
            deactivate()
            event = pygame.event.wait()
            if event.type == MOUSEBUTTONUP:
                self.clicked()
            elif event.type == QUIT:
                self.quitGame()
            self.clock.tick(self.fps)

    def updateMenu(self):
        self.screen.blit(self.bkgrnd, self.bkgrndRect)
        for i in range(len(self.menu)):
            self.screen.blit(self.menu[i].surface, self.menu[i].rect)
        self.clock.tick(self.fps)

    def quitGame(self):
        setConfig(self.sound.volume)
        pygame.quit()
        sys.exit()
    
    def oldMenu(self):
        while(1):
            for button in self.menu:
                button.rect.centerx -= 100 - self.fps
                if (button.rect.centerx <= - 500):
                    return;
            self.updateMenu()
            pygame.display.flip()

    def clicked(self):
        for button in self.menu:
            if button.rect.collidepoint(pygame.mouse.get_pos()):
                self.sound.clicMenu.play()
                if button.text == _(u"Quit Game"):
                    self.quitGame()
                self.oldMenu()
                if button.text == _(u"Play"):
                    self.play()
                elif button.text == _(u"Options"):
                    self.options()
                elif button.text == _(u"Rules"):
                    self.rules()
                elif button.text == _(u"About"):
                    self.about()
                self.main()
         

    def play(self):
        """User clicked on "Play" """
        if self.app != None:
            texts = [_("Continue"),_("Adventure"), _("Solo"),
                        _("Hot Seat"), _("Back")]
        else:
            texts = [_("Adventure"), _("Solo"),  _("Hot Seat"), _("Back")]    
        length = len(texts)
        if self.app != None:
            textPos = [(250, 100), (250,200), (250, 300), (250,400),
                        (550, 500)]
        else:
            textPos = [(250, 100), (250,200), (250, 300), (550, 500)]
        self.menu = []
        for i in range(length):
            self.menu.append(Text(texts[i], self.FONT, white, 45))
            self.menu[i].rect.topleft = textPos[i]
        self.updateMenu()          
        pygame.display.flip()
        self.clock.tick(self.fps)
        while 1:
            event = pygame.event.wait()
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == MOUSEBUTTONUP:
                coordinates = pygame.mouse.get_pos()
                for i in range(length):
                    if self.menu[i].rect.collidepoint(coordinates):
                        self.sound.clicMenu.play()
                        self.oldMenu()
                        if self.menu[i].text == _("Adventure"):
                            return
                        elif self.menu[i].text == _("Solo"):
                            return
                        elif self.menu[i].text == _("Hot Seat"):
                            self.hotSeat()
                        elif self.menu[i].text == _("Back"):
                            return
                        elif self.menu[i].text == _("Continue"):
                            self.app.main()
                    
    def options(self):
        texts = [_("Audio"), _("Sounds"), _("Music"), _("Back")]
        length = len(texts)
        textsPos = [(320, 100), (100, 200), (100, 300), (550, 500)]
        self.menu = []

        for i in range(length):
            self.menu.append(Text(texts[i], self.FONT, white, 50))
            self.menu[i].rect.topleft = textsPos[i]

        bar1, bar1Rect = loadImage("barSound.jpg")
        bar2, bar2Rect = loadImage("barSound.jpg")
        bar1Rect.topleft = (300, 220)
        bar2Rect.topleft = (300, 320)
        bars = [bar1Rect, bar2Rect]

        # X coordinates, relative to the bar's, of beginning and ending
        # of each volume cursor.
        MIN_VOLUME = 15
        MAX_VOLUME = 240

        # X absolute coordinates of the volume cursor.
        MIN = bars[0].x + MIN_VOLUME
        MAX = bars[0].x + MAX_VOLUME

        cursor1, cursor1Rect = loadImage("cursorSound.png")
        cursor2, cursor2Rect = loadImage("cursorSound.png")
        cursor1Rect.topleft = \
          (bar1Rect.x + 225 * self.sound.soundVolume, bar1Rect.y - 23)
        cursor2Rect.topleft = \
          (bar2Rect.x + 225 * self.sound.musicVolume, bar2Rect.y - 23)
        cursors = [cursor1Rect, cursor2Rect]
        self.screen.blit(self.bkgrnd, self.bkgrndRect)
        self.screen.blit(bar1, bar1Rect)
        self.screen.blit(bar2, bar2Rect)
        self.screen.blit(cursor1, cursors[0])
        self.screen.blit(cursor2, cursors[1])
        for i in range(length):
            self.screen.blit(self.menu[i].surface, self.menu[i].rect)
        pygame.display.update()
        move = 0
        while 1:
            event = pygame.event.wait()
            mousex, mousey = pygame.mouse.get_pos()
            if event.type == QUIT:
                self.quitGame()
            elif event.type == MOUSEBUTTONDOWN:
                move = 1
                reactivate()
            elif event.type == MOUSEBUTTONUP:
                move = 0
                deactivate()
            for i in range(len(bars)):
                if move == 1 and bars[i].collidepoint((mousex, mousey)):
                    if MIN <= mousex <= MAX:
                        cursors[i].centerx = mousex
                    elif mousex > bars[i].x + MAX_VOLUME:
                        cursors[i].centerx = bars[i].x + MAX_VOLUME
                    else:
                        cursors[i].centerx = bars[i].x + MIN_VOLUME
                    volume = cursors[i].centerx - MIN
                    if volume != 0:
                        volume = (volume / 2.25) / 100.0
                    assert (0.0 <= volume <= 1.0)

                    if i == 0:
                        self.sound.soundVolume = volume
                        self.sound.playPutCard()
                        self.sound.update()
                    elif i == 1:
                        self.sound.musicVolume = volume
                        self.sound.update()
                    self.screen.blit(self.bkgrnd, self.bkgrndRect)
                    self.screen.blit(bar1, bar1Rect)
                    self.screen.blit(bar2, bar2Rect)
                    self.screen.blit(cursor1, cursors[0])
                    self.screen.blit(cursor2, cursors[1])
                    for j in range(4):
                        self.screen.blit(self.menu[j].surface,\
                                          self.menu[j].rect)
                    pygame.display.update()
                    self.clock.tick(self.fps)
                if move and self.menu[3].rect.collidepoint((mousex, mousey)):
                    del bar1, bar2, bars, cursor1, cursor2, cursors
                    self.oldMenu()
                    self.sound.clicMenu.play()
                    return
                
    def about(self):
        page = 1
        allPage = []
        pageList = []
        index = 0
        for number in range(len(allCards)):
            pageList.append(Card(number, 1))
            index += 1
            if index == 3 or number == (len(allCards) or len(allCards)-1):
                allPage.append(pageList)
                del pageList
                pageList = []
                index = 0

        maxPage = len(allPage)
        txtPage = str(page) + "/" + str(maxPage)

        navigation = [_("Back"), _("Next"), _("Quit"),
                    "Programming:", "Kevin \"Ilphrin\" Pellet",
                    "Graphics:", "Yunero Kisapsodos",
                    txtPage]
        navigationPos = [(80,550), (650,550), (660,40), (630, 100),
                    (640, 130), (630, 200), (640, 230), (350,550)]
        self.menu = []
        for i in range(len(navigation)):
            if 2 < i < 7:
                size = 12
                font = "rimouski sb.ttf"
            else:
                font = self.FONT
                size = 30
            self.menu.append(Text(navigation[i], font, white, size))
            self.menu[i].rect.topleft = navigationPos[i]

        cardPos = [(50,50), (50,200), (50, 350)]
        self.screen.blit(self.bkgrnd, self.bkgrndRect)
        for element in self.menu:
            self.screen.blit(element.surface,element.rect)
        for elem in range(len(allPage[page-1])):
            card = allPage[page-1][elem]
            card.rect.topleft = cardPos[elem]
            card.About.rect.topleft = card.rect.topright
        
        for elem in allPage[page-1]:
            self.screen.blit(elem.image, elem.rect)
            self.screen.blit(elem.About.surface, elem.About.rect)
        while 1:
            self.clock.tick(self.fps)
            pygame.display.flip()
            event = pygame.event.wait()
            if event.type == MOUSEBUTTONUP:
                coords = pygame.mouse.get_pos()
                
                for button in self.menu:
                    if button.rect.collidepoint(coords):
                        if button.text == _("Back"):
                            if page > 1:
                                page -= 1
                                self.sound.putcard.play()
                        if button.text == _("Next"):
                            if page < maxPage:
                                page += 1
                                self.sound.putcard.play()
                        if button.text == _("Quit"):
                            self.oldMenu()
                            return
                        txtPage = str(page) + "/" + str(maxPage)
                        self.menu[7] = Text(txtPage, self.FONT, white, 30)
                        self.menu[7].rect.topleft = navigationPos[7]
                        self.screen.blit(self.bkgrnd, self.bkgrndRect)
                        for element in self.menu:
                            self.screen.blit(element.surface,element.rect)
                        for elem in range(len(allPage[page-1])):
                            card = allPage[page-1][elem]
                            card.rect.topleft = cardPos[elem]
                            card.About.rect.topleft = card.rect.topright
                        for elem in allPage[page-1]:
                            self.screen.blit(elem.image, elem.rect)
                            self.screen.blit(elem.About.surface,
                              elem.About.rect)
            if event.type == QUIT:
                self.quitGame()
            
    def rules(self):
        tutorialButton = Button(_(u"Tutorial"), self.FONT, white)
        howtoButton = Button(_(u"How To"), self.FONT, white)
        backButton = Button(_(u"Back"), self.FONT, white)
        
        tutorialButton.rect.topleft = (250, 100)
        howtoButton.rect.topleft = (250, 200)
        backButton.rect.topleft = (550, 500)
        self.menu = []
        self.menu.append(tutorialButton)
        self.menu.append(howtoButton)
        self.menu.append(backButton)
        self.updateMenu()
        while (1):
            self.clock.tick(self.fps)
            pygame.display.flip()
            event = pygame.event.wait()
            if event.type == MOUSEBUTTONUP:
                coords = pygame.mouse.get_pos()
                for i in range(len(self.menu)):
                    if self.menu[i].rect.collidepoint(coords):
                        self.oldMenu()
                        if self.menu[i].text == _(u"Tutorial"):
                            self.main()
                        elif self.menu[i].text == _(u"How To"):
                            self.HowTo()
                            return
                        elif self.menu[i].text == _(u"Back"):
                            self.main()
            elif event.type == QUIT:
                self.quitGame()
             
    def HowTo(self):
        backButton = Button(_("Back"), self.FONT, white)
        prevButton = Button(_("Prev"), self.FONT, white)
        nextButton = Button(_("Next"), self.FONT, white)
        page = 1
        maxPage = 2
        pageList = []
        for i in range(maxPage):
            pageList.append(pygame.image.load(getHowTo(i)))
        
        pageRect = pageList[i - 1].get_rect()
        pageRect.topleft = (-20, 0)
        backButton.rect.topleft = (600, 40)
        prevButton.rect.topleft = (80, 550)
        nextButton.rect.topleft = (660, 550)
        self.menu = []
        self.menu.append(backButton)
        self.menu.append(prevButton)
        self.menu.append(nextButton)
        self.updateMenu()
        self.screen.blit(pageList[page - 1], pageRect)        
        while (1):
            self.clock.tick(self.fps)
            pygame.display.flip()
            event = pygame.event.wait()
            if event.type == MOUSEBUTTONUP:
                coords = pygame.mouse.get_pos()
                if backButton.rect.collidepoint(coords):
                    self.oldMenu()
                    return
                elif prevButton.rect.collidepoint(coords) and page > 1:
                    page -= 1
                elif nextButton.rect.collidepoint(coords) and page < maxPage:
                    page += 1
                self.updateMenu()
                self.screen.blit(pageList[page - 1], pageRect)  
            elif event.type == QUIT:
                self.quitGame()

    def _load_translation(self):
        base_path = os.getcwd()
        directory = os.path.join(base_path, 'translations')
        print "Loading translations at: ", directory

        params = {
                    'domain': 'tuxle-triad',
                    'fallback': True
                 }
        
        if os.path.isdir(directory):
            params.update({'localedir': directory})
        
        translation = gettext.translation(**params)
        
        translation.install("ngettext")

    def solo(self):
        """1vsIA mode"""
        print "Solo!"
        
    def adventure(self):
        """Adventure mode against IA"""
        print "Adventure!"
        
    def hotSeat(self):
        """1vs1 mode"""
        if self.app != None:
            del self.app
            Application(800, 600, self.screen, self.sound, self).main()
        else:
            Application(800, 600, self.screen, self.sound, self).main()
 def userPainSound():
     painRNG=random.randrange(1,9)
     pain=Sound().userPainSounds(painRNG)
     pain.play()
Exemple #48
0
class MainWindow(QMainWindow):
    """ This class builds the main window pf PySIMS. It is able to
        open the chat windows. Chat windows are opend when the Server
        pushes new messages or the user wants to start a chat."""
    # Signal to make a new ChatWindo with a message
    openChat = Signal(str)
    # Incoming new message
    newMsg = Signal(str, str)

    # Cunstructor of MainWindow ##############################################

    def __init__(self, parent=None):
        super(MainWindow, self).__init__()

        self.parent = parent

        self.tcp = parent.tcp
        self.tcp.recvAns.connect(self.parseAns)
        self.tcp.ConError.connect(self.tcpError)

        self.UID = parent.UID
        self.sound = Sound()
        self.initUI()
        
    # Init Functions #########################################################
    def initUI(self):

        # Write all Stylsheets
        self.setStyle()
        # Init the Profile Groupbox
        self.Profile()
        # Init the Contro Groupbox
        #self.Control()
        # Init the Contact Groupbox
        self.Contacts()
        # Request Contact List from Server
        #self.requestList()
        # Requste Stored Messages from Server
        self.requestMsg()
        # Init List of Chatwindows
        self.ChatWindows = {}


        # Adjust Window ------------------------------------------------------
        # Set Title
        self.setWindowTitle('PySIMS')
        # Set Windwo Icon
        self.setWindowIcon(QIcon('img/pysims_icon_16.png')) 
        # Set Window Position and Size
        self.setGeometry(10, 50, 250, 400)
        self.setFixedWidth(250)

        # Show Statusbar
        self.statusBar().showMessage('Verbinung hergestellt')

        # MenuBar ------------------------------------------------------------
        # Create Exit
        exitAction = QAction(QIcon('img/main/exit.png'), 'Beenden', self)
        exitAction.setStatusTip('Beenden')
        exitAction.setShortcut('Ctrl+Q')
        exitAction.triggered.connect(self.close)

        # Create Profil
        profileAction = QAction(QIcon('img/main/profile.png'), 'Profil', self)
        profileAction.setStatusTip('Benutzer Profil')
        profileAction.setShortcut('Ctrl+P')
        #profileAction.triggered.connect(self.close)

        # Create Settings
        settingsAction = QAction(QIcon('img/main/settings.png'), 'Einstellungen', self)
        settingsAction.setStatusTip('Einstellungen')
        settingsAction.setShortcut('Ctrl+E')
        #settingsAction.triggered.connect(self.close)

        # Create About
        aboutAction = QAction(QIcon('img/main/about.png'), 'Ueber PySIMS', self)
        aboutAction.setStatusTip('Ueber PySIMS')
        aboutAction.triggered.connect(self.openAboutWindow)

        # Create Help
        helpAction = QAction(QIcon('img/main/help.png'), 'Hilfe', self)
        helpAction.setStatusTip('Hilfe')
        #settingsAction.triggered.connect(self.close)

        # Create MenuBar
        menubar = self.menuBar()
        # Add File Menu
        fileMenu = menubar.addMenu('&Datei')
        fileMenu.addAction(exitAction)
        # Add Options Menu
        optMenu = menubar.addMenu('&Optionen')
        optMenu.addAction(profileAction)
        optMenu.addAction(settingsAction)
        # Add Help Menu
        helpMenu = menubar.addMenu('&Hilfe')
        helpMenu.addAction(helpAction)
        helpMenu.addAction(aboutAction)


        # Create layout and add widgets --------------------------------------
        widget = QWidget()
        self.setCentralWidget(widget)

        # Build Main Layout, Add all Widgets
        layout = QVBoxLayout()
        #layout.addWidget(scroll)
        layout.addWidget(self.ProfileGroup)
        #layout.addWidget(self.ControlGroup)
        layout.addWidget(self.ContactGroup)
        layout.addStretch(1)

        widget.setLayout(layout)

    # Style ##################################################################
    def setStyle(self):

        # Set the Syle for all classes
        self.setStyleSheet( """
                            QLabel[labelClass='Username'] 
                            {font-size: 16px;

                            }
                            """)

    # Contact List ###########################################################
    def Contacts(self):

        # Create Contact Group Box
        self.ContactGroup = QGroupBox('Kontakte')
        # Create Main Layout
        layout = QVBoxLayout()
        # Create Scroll Area
        self.ContactScroll = QScrollArea()
        # Scroll Area Properties
        self.ContactScroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.ContactScroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.ContactScroll.setWidgetResizable(False)
        self.ContactScroll.setMinimumSize(30,300)

        # Create a Container Widget for the VBoxLayout
        self.ContactScrollContainer = QWidget()
        # Create the Contactlist
        self.ContactListLayout = QVBoxLayout()
        # Add Scroll Area to Layout
        layout.addWidget(self.ContactScroll)
        # Add Layout to Group
        self.ContactGroup.setLayout(layout)

    # User Profile ###########################################################
    def Profile(self):

        # Create the Profile Groupbox
        self.ProfileGroup = QGroupBox('Profil')

        # Create the Profile Main Layout
        ProfileLayout = QHBoxLayout()

        # Create Profile Information Layout
        ProfileInfoLayout = QVBoxLayout()

        # Create username Label
        self.userNameLabel = QLabel(self.parent.userName)
        self.userNameLabel.setProperty('labelClass', 'Username')

        # Create Status selector
        self.statusSelect = QComboBox(self)
        self.statusSelect.addItem('Online')
        self.statusSelect.addItem('Abwesend')
        self.statusSelect.addItem('Beschaeftigt')
        self.statusSelect.addItem('Offline')

        self.statusSelect.currentIndexChanged[int].connect(self.changeStatus)

        # Create Infotext Label
        self.ProfileinfoLabel = QLabel('<font color=green>Verbunden</font>')

        # Create Profile Picture
        self.UserImgPixmap = QPixmap('img/user/userpic.png')
        self.UserImgLabel = ClickableLabel(self)
        self.UserImgLabel.setPixmap(self.UserImgPixmap)
        
        # Build Profile Info Layout
        ProfileInfoLayout.addWidget(self.userNameLabel)
        ProfileInfoLayout.addWidget(self.statusSelect)
        ProfileInfoLayout.addWidget(self.ProfileinfoLabel)

        # Build Profile Main Layout
        ProfileLayout.addLayout(ProfileInfoLayout)
        ProfileLayout.addStretch(1)
        ProfileLayout.addWidget(self.UserImgLabel)

        # Add to Profile Group
        self.ProfileGroup.setLayout(ProfileLayout)

    # Control Group Box ######################################################
    # For adding addition Features to the main Window
    def Control(self):

        self.ControlGroup = QGroupBox('Control')
        # Create the Control Main Layout
        ControlLayout = QHBoxLayout()


    # Actions and Slots ######################################################

    def updateContacts(self, contactList):

        # Sort contacts by name
        sortedList = sorted(contactList.items(), key= lambda x: x[1]['name'].lower())

        # Empty old Contact list
        self.ContactScrollContainer.deleteLater()
        self.ContactScrollContainer = QWidget()
        self.ContactListLayout = None
        self.ContactListLayout = QVBoxLayout()

        # Add every Contact from the List
        for c in sortedList:

            # exxtract contact
            contact = c[1]
            cLayout = QHBoxLayout()

            # Name
            cLabel = QLabel(contact['name'])
            cLabel.setMinimumSize(QSize(100,24))
            cLabel.setStyleSheet("QLabel {font-size: 14px}")

            # Status
            StatusImgPath = path.join('img/user/',contact['status'] +'.png')
            cStatusPixmap = QPixmap(StatusImgPath)
            cStatus = QLabel()
            cStatus.setToolTip(contact['status'])
            cStatus.setPixmap(cStatusPixmap)

            # Add Chat Button
            cChatPixmap = QPixmap('img/main/chat.png')
            cChat = ClickableChat(self, contact['UID'])
            cChat.setPixmap(cChatPixmap)
            cChat.setToolTip('Chat beginnen')
            cChat.openChat.connect(self.openChat)

            # Build the Contact horizontal Layout
            cLayout.addWidget(cLabel)
            cLayout.addStretch(1)
            cLayout.addWidget(cStatus)
            cLayout.addWidget(cChat)

            # Add contact to the List
            self.ContactListLayout.addLayout(cLayout)
            
        # Add Contactlist to Container
        self.ContactScrollContainer.setLayout(self.ContactListLayout)
        # Add Container to Scroll Area
        self.ContactScroll.setWidget(self.ContactScrollContainer) 

    def openAboutWindow(self):
        # Open the About Window
        self.AboutWindow = AboutWindow(parent=self)
        self.AboutWindow.exec_()

    def requestList(self):
        # Request the userlist from the Server
        req = 'GETLIST'
        self.tcp.sendReq(req)

    def requestMsg(self):
        # Request Messages from the Server
        req = 'PULLMSGS'
        self.tcp.sendReq(req)

    def requestGID(self, members):
        # Request a group ID to open a new Chat
        req = 'MKGRP\r\n'
        req += 'UID:'
        for userID in members:
            if not userID == members[-1]:
                req += userID + ','
            else:
                req += userID + '\r\n'

        req += 'SID:' + self.parent.SID + '\r\n\r\n'

        self.tcp.sendReq(req)

    def sendAck(self):
        # Send ACK to Server
        #self.tcp.sendReq('ACK\r\n')
        #print('ACK sent')
        pass

    def changeStatus(self, status):
        # Change the Status of the online mode
        if status == 0:
            # Online
            print('New Status: Online')
        elif status == 1:
            # Abwesend
            print('New Status: Abwesend')
        elif status == 2:
            # Beschaeftigt
            print('New Status: Beschaeftigt')
        elif status == 3:
            # Offline
            print('New Status: Offline')

    @Slot(str, str)
    def parseAns(self, lastReq, ServerAns):
        # Parse the message from the Server

        dlvmsg = False
        gids = {}

        # Split the different Commands
        for ans in ServerAns.split('\r\n\r\n'):
            ans = ans.split('\r\n')
            print('------  Main Window Recived: -----')
            print(ans)
            print('----------------------------------')

            # Is it a new Userlist?
            if ans[0] == 'USRLIST':
                myContacts = contactList(ans[1:], self.parent.userName)
                self.contactList = myContacts.getList()
                self.updateContacts(self.contactList)

            # Is it a new GroupID for a Chat?
            if ans[0] == 'MKGRP OK':
                GID = ans[1].split(':')
                if GID[0] == 'GID':
                    self.checkChatWindow(GID[1])
            
            # Is it a new Message?
            if ans[0] == 'DLVMSG':
                GID = ans[1].split(':')
                UID = ans[2].split(':')
                if GID[0] == 'GID':
                    if GID[1] in gids:
                        if UID[0] == 'UID':
                            gids[GID[1]]['UIDS'].append(UID[1])
                            gids[GID[1]]['MSGS'].append(ans[3])
                    else:
                        if UID[0] == 'UID':
                            gids[GID[1]] = {'UIDS': [], 'MSGS': []}
                            gids[GID[1]]['UIDS'].append(UID[1])
                            gids[GID[1]]['MSGS'].append(ans[3])
                        

        # If there are more than one message and more groups that got new
        # Messages it is important to give the right Messages to the right
        # chat windows
        if gids:
            for gid in gids:
                print(gids[gid])
                #self.sendAck()
                self.checkChatWindow(gid, gids[gid]['UIDS'], gids[gid]['MSGS'])
                self.sound.newWindow()

                    

    @Slot(str)
    def openChat(self, memberID):
        # Open a new Chat
        print('Open Chat with', memberID)
        members = [self.UID, memberID] 
        self.requestGID(members)

    def checkChatWindow(self, gid, senderID=None, msg=None):
        # Check if the Chat allready exsists or if it is
        # nescessary to open a new window

        #print('SenderID:', senderID)
        if gid in self.ChatWindows:
            pass
            #print (self.ChatWindows[gid])
        else:
            self.ChatWindows[gid] = QChatWindow(gid, senderID, msg, self)
            self.ChatWindows[gid].show()

    @Slot(str)
    def tcpError(self, err):
        # Detect network error and forward the errortype
        if err == 'ConnectionClosed':
            self.statusBar().showMessage('Verbinung unterbrochen!')
            self.ProfileinfoLabel.setText('<font color=red>Verbinung unterbrochen!</font>')
        elif err == 'ConnectionRefused':
            self.statusBar().showMessage('Server nicht erreichbar!')
            self.ProfileinfoLabel.setText('<font color=red>Server nicht erreichbar!</font>')
        self.logout()

    def logout(self):
        # Logout the user and show the login Window
        self.sound.conError()
        self.parent.show()
        #self.Log = login_ui.LoginWindow()
        #self.Log.show()

        self.close()

    def closeEvent(self, ev):

        # When the main Window is closes than all the
        # other windows should close too.

        # It is important to search all open chats because
        # should not change the array while ittarting
        gids = []
        for gid in self.ChatWindows:
            # Find all open Chats
            gids.append(gid)

        for gid in gids:
            # Close all open Chats
            self.ChatWindows[gid].close() 
    def combat(self,pod,user,playerBattleMap,alienBattleMap,playerEquipment,ranAway=0,playerDead=0):
    #taunt and shoot are shorthand for alien action options
        
        if ranAway !=0:
            done=1
        if playerDead!=0:
            done=1
        taunt="taunt"
        shoot="shoot"
        battleTurn=1 #1=Player,2=Alien.
        shotMissed=Sound().weaponSounds("Shot Miss")
        shotMissed.set_volume(1)
        turn=0 #turn ticks when turn passes, allowing for status aliments to fade after turns
        
        Combat.setCombatMusic()
        shotMissed.play()
        
        pygame.mixer.music.set_volume(1)
        pygame.mixer.music.play(-1,0)

    #*****************************************
    #lists holding combat actions/reactions
    #--------------------------------------
        actions=[] #actions holds enemy action choices.
        #totalHealth=[] #pulls hp from enemies in pod for ui purposes
        alienCoverStats=[] #pulls cover stats from enemiesi n pod for ui purposes
        playerCopyAlienCover=[] #copy of aliencoverstats made after they are cleared each turn. For long-term ui storage
    #*****************************************


    #main combat loop
        done=0
        while done==0:
            #At the start of combat, player chooses which cover they'll take.
            print ("You've touched down and found the enemies. Press the coorisponding number key to get into that over point.")
            os.system('cls' if os.name=='nt' else 'clear')
            user.changeCover(playerBattleMap)
            os.system('cls' if os.name=='nt' else 'clear')
    #show pod, make action selection, turn passed and it switches to alien.
            while battleTurn==1:
                ranAway=Combat.playerTurn(self,pod,user,alienBattleMap,playerBattleMap,shotMissed,playerEquipment)
                if ranAway==1:
                    done=1
                    os.system('cls' if os.name=='nt' else 'clear')
                    break
                done=Combat.checkIfVictory(pod,user)
                
                time.sleep(0.5)
                battleTurn=2
#if player chooses to run away, it returns runAway as 1. if 1, then done=1 and loop breaks, running funct again. ranAway, despite being an intitalized variable, stayed 1 and thus done
#also stayed 1. So with done=1, then there's no game loop and it's back to the main screen. Easy-peasy.

    #gets player position,then each alien in pod takes an action and cover. either taunt or shoot. clear results each time but store in sep list 1st
            while battleTurn==2:
                Combat.alienTurn(user,pod,actions,alienCoverStats,playerCopyAlienCover,alienBattleMap,playerBattleMap,shotMissed)
                playerDead=Combat.checkIfVictory(pod,user)
                if playerDead==1:
                    done=1
                    break
                
                input("Enter any key then hit enter to progress to your turn")
                battleTurn=1
class Player(object):
 
    def __init__(self,weapons=[],hp=20,imparement=0,defense=30,buff=0):
        self.name="Trooper"
        self.hp=hp
        self.imparement=imparement
        
        self.inventory=[Grenade(),Grenade(),Grenade(),Grenade(),Healing("Medkit",10),Healing("Medkit",10)]
        self.ammoBelt=None
        self.seconaryAmmoBelt=None
        self.defense=defense
        self.aimPenalty=0
        self.coverPosition=0
        self.buff=buff
        self.weapons=weapons
        self.cover=0
        self.currentWeapon=None
        self.deathSound=Sound().deathSounds("Player")
#************************************************************************************
#ACTIONS PLAYER CAN TAKE
#************************************************************************************
    def changeCover(self,playerBattleMap):
        coverSet=0
        while coverSet==0:
            for each in playerBattleMap:
                print (each+1,": Cover Value:",playerBattleMap[each].getCovValue()," Aim Penalty:",playerBattleMap[each].getAimPen()," Cover HP:",playerBattleMap[each].getHP())
            try:
                chooseCover=(int(input("Which cover do you take?"))-1)
                
            except:
                print ("That's not a valid option, try again.\n\n")
                continue

            if chooseCover in playerBattleMap:
                playerCover=playerBattleMap[chooseCover].getCovValue()
                playerAimPen=playerBattleMap[chooseCover].getAimPen()
                self.cover=playerCover
                playerCovPos=chooseCover
                self.defense=30
                self.defense=self.defense+playerCover
                self.aimPenalty=playerAimPen
                self.coverPosition=playerCovPos
                coverSet=1
            
            else:
                print ("That's not a valid cover option")
                continue
            

    def gunshotAccuracy(self,enemyDef,alienBattleMap,coverPosition):
        #taunted/pissed off is 1. # calculates shot%, factoring in cover and any status ailments

        targetHit=0
        pissedOff=0
        takingAim=0
        #print ("DEBUG*** This is the status element= ",self.imparement)
        #print ("DEBUG*** this is your buff number: ",self.buff)
        if self.imparement==1:
            pissedOff=20
        if self.buff==1:
            takingAim=-50
        print ("BANG!")

        baseHitChance=self.currentWeapon.getAcc()
        #print (baseHitChance,enemyDef,self.aimPenalty,pissedOff,takingAim,"   ",baseHitChance-enemyDef-self.aimPenalty-pissedOff-takingAim)
        adjustedHitChance=baseHitChance-enemyDef-self.aimPenalty-pissedOff
        if adjustedHitChance<0:
            adjustedHitChance=0
        if adjustedHitChance>100:
            adjustedHitChance=100
        adjustedHitChance-=takingAim
        print ("Chance to hit: ", adjustedHitChance)
        hitCoverRNG=random.randint(1,2)
        RNG=random.randint(1,100)
        if RNG <= adjustedHitChance:
            
            print ("Hit Roll: ", RNG,"\n")
            print ("That's a hit!")
            targetHit=1
        else:
            if hitCoverRNG==1:
                print ("Hit Roll: ", RNG,"\n")
                targetHit=3
            else:
                print ("Hit Roll: ", RNG,"\n")
            #print ("Damn, you missed!")"
                targetHit=2
        return targetHit
 #this is some of the oldest code in the program, likely a shitshow.

    def useItem(self):
        for idx,item in enumerate(self.inventory):
            idx+=1
            print(idx,item)
        
        item=(input("Which item do you want to use?"))
        if item=="B" or item=="b":
            print ("Nope")
            os.system('cls' if os.name=='nt' else 'clear')
            return

        else:
            try:
                item=(int(item))
            except:
                print ("not a number")
                os.system('cls' if os.name=='nt' else 'clear')
                return
        
        if item >=1:
            item-=1

        if item not in range(len(self.inventory)):
            print ("Not a valid item number, pick another or hit B to go back:")
            os.system('cls' if os.name=='nt' else 'clear')
            return

        sendItem=self.inventory[item]
        return sendItem,item


    def switchWeapons(self):
        if self.currentWeapon==self.weapons[0]:
            self.currentWeapon=self.weapons[1]
            print (self.currentWeapon)

        elif self.currentWeapon==self.weapons[1]:
            self.currentWeapon=self.weapons[0]
            print(self.currentWeapon)
    #make this adaptable to more than 2 weapons later on
    
    def hunkerDown(self):
        self.defense+=30

    def takeAim(self,playerBuff):
        self.buff+=playerBuff

    def getSpecificAmmoBelt(self):
        if self.currentWeapon==self.weapons[0]:
            return 0

        elif self.currentWeapon==self.weapons[1]:
            return 1        

    def reloadGun(self,pick):
        x=0
        if self.currentWeapon==self.weapons[1]:
            x=1

        newMag=self.ammoBelt[x].removeMag(pick)      
        oldMag=self.currentWeapon.reload(newMag)
        self.ammoBelt[x].changeMag(oldMag)

#**************************************************
#ALTER YOUR STATS (HP/DEF/AIM/STATUS)
#**************************************************

    def setDefense(self,playerCoverBonus):
        self.defense=30
        self.defense=self.defense+playerCoverBonus

    def setAimPen(self,playerAimPen):
        self.aimPenalty=0
        self.aimPenalty=self.aimPenalty+playerAimPen

    def status(self,ailment):
        #status aliments, good and ill, will check here to see if they pass or fail
        #taunt is 1, resisted is 0
        inflicted=0
        checking=ailment
        baseResist=70
        rRNG=random.randint(1,100)
        if rRNG <= baseResist:
            if checking==1:
                self.imparement=1

        return self.imparement
    
    def healing(self,amount):
        self.hp+=amount
        if self.hp >= 20:
            self.hp = 20
        return self.hp

    def damage(self,damage):
        self.hp-=damage
        if self.hp <=0:
            self.hp=0
        return self.hp

    def turnPass(self,turn):
        if self.imparement!=0:
            self.imparement=0
        return self.imparement

    def tickAimTimerDown(self,timeTick):
        self.buff=self.buff-timeTick
        if self.buff<0:
            self.buff=0
#ticks down aiming so it only lasts a certain number of turns.

#*********************************************
# EQUIPS PLAYER ITEMS AND WEAPONS
#*********************************************

    def playerWeapons(self,selectedWeapons):
        self.weapons=selectedWeapons
        self.currentWeapon=self.weapons[0]

    def equipAmmoBelt(self,belts):
        self.ammoBelt=belts


    def removeItem(self,item):
        self.inventory.pop(item)


#***********************************
#RETURN CLASS VARIABLES
#***********************************
    def getName(self):
        return self.name

    def getCoverPosition(self):
        return self.coverPosition

    def getHP(self):
        return self.hp

    def returnDef(self):
        return self.defense

    def playDeathSound(self):
        self.deathSound.play()

    def returnPlayerWeapons(self):
        return self.weapons

#***********************************
#RETURN WEAPON VARIABLES
#***********************************

    def returnWepDamage(self):
        return self.weapons[0].getDamage()

    def returnWeaponNames(self):
        return self.weapons[0].getName(), self.weapons[1].getName()

    def getCurrentPlayerWeapon(self):
        return self.currentWeapon

#***********************************
#RETURN AMMO BELT VARIABLES
#***********************************

    def getBackupMags(self):
        return self.ammoBelt[0].getMags(), self.ammoBelt[1].getMags()
#gets how many magazines there are in each belt

    def getBackupMagAmount(self):
        return self.ammoBelt[0].getMagNumber(), self.ammoBelt[1].getMagNumber()
#gets number of bullets in each magazine in the ammo belt
        
    def getBackupMagsName(self):
        primMagName=self.ammoBelt[0].getMags()
        primMagName=(str(primMagName)[2:-2])

        secMagName=self.ammoBelt[1].getMags()
        secMagName=(str(secMagName)[2:-2])
        
        
        return primMagName,secMagName
#Gets the names of the ammo belts and cuts off list brackets

#***********************************
#RETURN STATUS VARIABLES
#***********************************
    def getCoverValue(self):
        if self.cover==40:
            cover="High cover"
        elif self.cover==20:
            cover="Low cover"
        else:
            cover="No cover"
        return cover

    def getTauntStatus(self):
        if self.imparement==1:
            returnPrint=("taunted")
        else:
            returnPrint=("not taunted")
        return returnPrint

    def getAimStatus(self):
        if self.buff==1:
            returnAim=("taking aim")
        else:
            returnAim=("not taking aim")
        return returnAim

    def getHitChance(self,targetInfo):
#largely copied code. Consolidate gunshot acc and this somehow

        targetHit=0
        pissedOff=0
        takingAim=0
        #print ("DEBUG*** This is the status element= ",self.imparement)
        #print ("DEBUG*** this is your buff number: ",self.buff)
        if self.imparement==1:
            pissedOff=20
        if self.buff==1:
            takingAim=-50
        

        baseHitChance=self.currentWeapon.getAcc()
        adjustedHitChance=baseHitChance-targetInfo-self.aimPenalty-pissedOff
        adjustedHitChance-=takingAim
        if adjustedHitChance<0:
            adjustedHitChance=0
        if adjustedHitChance>100:
            adjustedHitChance=100
        return adjustedHitChance

#***********************************
#RETURN ITEM OBJECT VARIABLES
#***********************************


    def getInventory(self):
        return self.inventory

    def getSpecificInventoryItem(self,item):
        print (self.inventory[item])
        return self.inventory[item]

    def getItemNames(self,itemNum):
        return self.inventory[itemNum].getName()
 def play_sound(self, sound_name):
     sound = Sound(sound_name)
     sound.play()
Exemple #52
0
class Menu(pygame.sprite.Sprite):
    def __init__(self, width, height):
        # We create the window
        self.width = width
        self.height = height
        FULLSCREEN = 0
        self.dimension = (self.width, self.height)
        self.screen = pygame.display.set_mode(self.dimension,  FULLSCREEN, 32)
        pygame.display.set_caption("TuxleTriad")

        elemText = ["Play", "Options", "Rules", "About", "Quit Game"]
        self.menu = []
        for elem in elemText:
            self.menu.append(Button(elem, "Dearest.ttf", white))

        posx = 400
        posy = 400 - (60 * len(elemText))

        for elem in self.menu:
            elem.rect.center = ((posx, posy))
            posy += 100

        self.bkgrnd, self.bkgrndRect = loadImage("background.jpg")
        self.bkgrndRect = self.bkgrnd.get_rect()

        # The Clock of the game, to manage the frame-rate
        self.clock = pygame.time.Clock()
        self.fps = 60

        # We start the Sound object, playing music and sounds.
        self.sound = Sound()

        # Needed to keep track of the game if we do a pause during the game.
        self.app = None

        self.main()

    def main(self):
        pygame.event.clear()
        while 1:
            self.screen.blit(self.bkgrnd, self.bkgrndRect)
            for i in range(len(self.menu)):
                self.screen.blit(self.menu[i].surface, self.menu[i].rect)

            for event in pygame.event.get():
                if event.type == MOUSEBUTTONUP:
                    self.clicked()
                elif event.type == QUIT:
                    self.quitGame()

            pygame.display.flip()
            self.clock.tick(self.fps)

    def play(self):
        """User clicked on "Play" """
        if self.app != None:
            self.app.main()
        else:
            Application(800, 600, self.screen, self.sound, self)

    def options(self):
        pygame.event.clear()
        texts = ["Audio", "Sounds", "Music", "Back"]
        length = len(texts)
        textsPos = [(320, 100), (100, 200), (100, 300), (500, 450)]
        elements = []

        for i in range(length):
            elements.append(Button(texts[i], "Dearest.ttf", white))
            elements[i].rect.topleft = textsPos[i]

        bar1, bar1Rect = loadImage("barSound.jpg")
        bar2, bar2Rect = loadImage("barSound.jpg")
        bar1Rect.topleft = (300, 220)
        bar2Rect.topleft = (300, 320)
        bars = [bar1Rect, bar2Rect]

        # X coordinates, relative to the bar's, of beginning and ending
        # of each volume cursor.
        MIN_VOLUME = 15
        MAX_VOLUME = 240

        # X absolute coordinates of the volume cursor.
        MIN = bars[0].x + MIN_VOLUME
        MAX = bars[0].x + MAX_VOLUME

        cursor1, cursor1Rect = loadImage("cursorSound.png")
        cursor2, cursor2Rect = loadImage("cursorSound.png")
        cursor1Rect.topleft = \
          (bar1Rect.x + 225 * self.sound.soundVolume, bar1Rect.y - 23)
        cursor2Rect.topleft = \
          (bar2Rect.x + 225 * self.sound.musicVolume, bar2Rect.y - 23)
        cursors = [cursor1Rect, cursor2Rect]

        while 1:
            self.screen.blit(self.bkgrnd, self.bkgrndRect)
            self.screen.blit(bar1, bar1Rect)
            self.screen.blit(bar2, bar2Rect)
            self.screen.blit(cursor1, cursors[0])
            self.screen.blit(cursor2, cursors[1])
            for i in range(length):
                self.screen.blit(elements[i].surface, elements[i].rect)

            for event in pygame.event.get():
                if event.type == QUIT:
                    self.quitGame()
                elif event.type == MOUSEBUTTONDOWN:
                    mousex, mousey = pygame.mouse.get_pos()
                    for i in range(len(cursors)):
                        if cursors[i].collidepoint((mousex, mousey)):
                            while pygame.event.poll().type != MOUSEBUTTONUP:
                                mousex, mousey = pygame.mouse.get_pos()
                                if MIN <= mousex <= MAX:
                                    cursors[i].centerx = mousex
                                elif mousex > bars[i].x + MAX_VOLUME:
                                    cursors[i].centerx = bars[i].x + MAX_VOLUME
                                else:
                                    cursors[i].centerx = bars[i].x + MIN_VOLUME
                                volume = cursors[i].centerx - MIN
                                if volume != 0:
                                    volume = (volume / 2.25) / 100.0
                                assert (0.0 <= volume <= 1.0)

                                if i == 0:
                                    self.sound.soundVolume = volume
                                    self.sound.playPutCard()
                                elif i == 1:
                                    self.sound.musicVolume = volume
                                self.sound.update()

                                self.screen.blit(self.bkgrnd, self.bkgrndRect)
                                self.screen.blit(bar1, bar1Rect)
                                self.screen.blit(bar2, bar2Rect)
                                self.screen.blit(cursor1, cursors[0])
                                self.screen.blit(cursor2, cursors[1])
                                for j in range(4):
                                    self.screen.blit(elements[j].surface,\
                                                      elements[j].rect)
                                pygame.display.flip()

                    if elements[3].rect.collidepoint((mousex, mousey)):
                        self.main()

            pygame.display.update()

    def quitGame(self):
        setConfig("config.txt", self.sound.volume)
        pygame.quit()
        sys.exit()

    def clicked(self):
        for button in self.menu:
            if button.rect.collidepoint(pygame.mouse.get_pos()):
                if button.text == "Play":
                    self.play()
                elif button.text == "Options":
                    self.options()
                elif button.text == "Rules":
                    print "Rules!"
                elif button.text == "About":
                    print "About !"
                elif button.text == "Quit Game":
                    self.quitGame()

    def __repr__(self):
        return "<Menu>"
Exemple #53
0
class Application():
    """Main class of the game, manage the window"""
    def __init__(self, width, height, screen=None, soundInstance=None,
                  boss=None):
        # We create the window
        self.width = width
        self.height = height
        if screen == None:
            self.screen = pygame.display.set_mode((self.width, self.height))
        else:
            self.screen = screen

        if soundInstance == None:
            self.Sound = Sound()
        else:
            self.Sound = soundInstance

        self.background, self.backgroundRect = loadImage("background.jpg")

        # We keep the Menu instance if we are running TuxleTriad from Menu.py
        if boss != None:
            self.boss = boss
            self.boss.app = self
            self.FONT = self.boss.FONT
        else:
            self.boss = None
            self.FONT = "Dearest.ttf"

        # The Clock of the game, to manage the frame rate
        self.clock = pygame.time.Clock()
        self.fps = 60
        # Creation of two players
        self.player1 = Player(1)
        self.player2 = Player(-1)
        self.players = {1 : self.player1, -1 : self.player2}
        self.player1Hand = self.player1.hand
        self.player2Hand = self.player2.hand

        # We create the Score
        self.scorePlayer1 = Score("5", 1, self.width, self.height)
        self.scorePlayer2 = Score("5", -1, self.width, self.height)

        # With this variable, we cannot do anything until the animation
        # played is finished.
        self.animation = 0

        # If we have to play the animation in different directions
        self.sensAnimation = 0
        self.player = 1

        self.position = None
        self.CARD = None
        self.infoCARD = None

        # We create the field of the game, 3x3.
        sizeCard = self.player1Hand.cards[0].image.get_size()
        self.field = Field(self.width, self.height, sizeCard, self)
        self.emptySquare = 9

        self.alphaAnimation = 255

        # Manage the winner congratulations font
        self.winner = Text("", self.FONT, white, 60)

        # Manage the display of the name of the card selected
        self.cardName = None

        # Do we show the name of the card selected?
        self.selectedCardName = 1


    def update(self):
        """Updates all the sprites on the window"""
        self.screen.blit(self.background, self.background.get_rect())
        self.screen.blit(self.field.surface, self.field.rect)

        for card in self.player1Hand.cards:
            self.screen.blit(card.image, card.rect)
            if card == self.CARD:
              self.CARD.borderRect.topleft = self.CARD.rect.topleft
              self.screen.blit(self.CARD.border, self.CARD.borderRect)

        for card in self.player2Hand.cards:
            self.screen.blit(card.image, card.rect)
            if card == self.CARD:
              self.CARD.borderRect.topleft = self.CARD.rect.topleft
              self.screen.blit(self.CARD.border, self.CARD.borderRect)

        self.scorePlayer1.update()
        self.scorePlayer2.update()
        self.screen.blit(self.scorePlayer1.surface, self.scorePlayer1.rect)
        self.screen.blit(self.scorePlayer2.surface, self.scorePlayer2.rect)
        if self.winner.text != "":
            self.winner.changeText()
            self.screen.blit(self.winner.surface, self.winner.rect)

        if self.selectedCardName != 0: 
            self.showName(1)
            self.showName(-1)

        if self.cardName != None:
                self.screen.blit(self.backCard, self.backCardRect)
                self.screen.blit(self.cardName.surface, self.cardName.rect)
                self.cardName = None

        if self.infoCARD == None:
        # If we aren't showing the about popup. Because About need to blit one
        # more thing before doing the following commands.
            pygame.display.flip()
            self.clock.tick(self.fps)

    def main(self):
        """Main part handling the game"""
        self.cardsOwner()
        self.update()
        while 1:
            if self.animation == 1:
                # We continue the animation
                self.putCard()
                self.update()
            else:
                # We over the animation and now the next player have to play.
                if self.sensAnimation == 1:
                    self.player = self.player * -1
                    self.sensAnimation = 0

            for event in pygame.event.get():
                if event.type == MOUSEBUTTONUP and self.animation == 0:
                    if event.button == 3 and self.winner.text == "":
                        if self.getCard(0):
                            self.showAbout()
                    if self.winner.text == "" and event.button == 1:
                        self.infoCARD = None
                        self.players[self.player].playCard(self)
                elif event.type == QUIT:
                    audio = [self.Sound.soundVolume, self.Sound.musicVolume]
                    setConfig(audio)
                    self.field.saveState()
                    pygame.quit()
                    sys.exit()
                else:
                    # We get the status of all key on keyboard.
                    # Then we select the one at place 27: Escape.
                    # We can do this only if we ran the game
                    # with Menu.py and not directly from main.py
                    if pygame.key.get_pressed()[27] and self.boss != None:
                        self.boss.main()

            pygame.display.flip()
            self.clock.tick(self.fps)

    def putCard(self):
        """Animation of a card put on the field"""

        if self.CARD.inHand == 1:
        # We check if self..CARD is in the player's Hand
            self.Sound.playPutCard()

        # We drop the card off the Hand
        if self.CARD.inHand == 1:
            self.CARD.inHand = 0

        # Depending of the direction of the animation, we make the card
        # being invisible or visible again.
        if self.sensAnimation == 0:
            self.alphaAnimation -= 25 + (self.fps / 30.0 * 5)
            if self.alphaAnimation < 0:
                self.alphaAnimation = 0
            self.CARD.image.set_alpha(self.alphaAnimation)
            self.CARD.rect.centerx += 2 * self.player
        elif self.sensAnimation == 1:
            self.alphaAnimation += 25 + (self.fps / 30.0 * 5)
            if self.alphaAnimation > 255:
                self.alphaAnimation = 255
            self.CARD.image.set_alpha(self.alphaAnimation)

        # We change the position of the card and the animation's direction
        if self.CARD.image.get_alpha() <= 25:
            self.CARD.rect = self.Square
            self.sensAnimation = 1

        if self.CARD.image.get_alpha() == 255 and self.sensAnimation == 1:
            # We have put the card on the field and the animation is over.
            # We compare the elements to give potential malus/bonus.
            # And we have to look if that card captured some of the
            # ennemy's.
            self.animation = 0
            squareElement = self.field.elementName[self.numberSquare]
            if squareElement != None:
                self.Sound.playElement(squareElement)
            if self.CARD.elementName == squareElement \
            and squareElement != None:
                self.CARD.addModifier(1)
            else:
                if squareElement != None:
                    self.CARD.addModifier(-1)
            adjacentCards = self.getAdjacent()
            capturedCard = adjacent(self.CARD, adjacentCards)
            self.changeOwner(capturedCard)
            self.emptySquare -= 1
            self.CARD = None

        if self.emptySquare == 0:
            self.winAnimation()

    def selectedCard(self):
        """Player has selected a card
        But not yet a place on the field"""
        for i in [1, 2, 3, 4, 5]:
            self.CARD.rect.centerx += 4 * self.player
            self.update()

    def deselectedCard(self):
        """Finally, the player wants an other card"""
        for i in [1, 2, 3, 4, 5]:
            self.CARD.rect.centerx -= 4 * self.player
        self.CARD = None
        self.update()

    def squareFilled(self):
        """Say if there is already a card in the square"""
        for card in self.player1Hand.cards:
            if card.rect == self.Square:
                return 1
        for card in self.player2Hand.cards:
            if card.rect == self.Square:
                return 1
        return 0

    def cardsOwner(self):
        """Which cards is owned by who?"""
        cardPlayer = 0
        cardPlayer += self.player1Hand.cardsOwner()
        self.scorePlayer1.updateScore(cardPlayer)
        self.scorePlayer2.updateScore(10 - cardPlayer)

    def getAdjacent(self):
        """Get all the adjacent cards of the first one put"""
        posx, posy = self.CARD.rect.topleft
        adjacentCards = [None, None, None, None]
        if self.player == 1:
            for card in self.player2Hand.cards:
                if card.inHand == 0:
                    if card.rect.collidepoint((posx, posy - 144)):
                        # We first look at the card on the top
                        adjacentCards[0] = card

                    if card.rect.collidepoint((posx + 113, posy)):
                        # We look at the card on the right
                        adjacentCards[1] = card

                    if card.rect.collidepoint((posx, posy + 144)):
                        # We look at the card on the bottom
                        adjacentCards[2] = card

                    if card.rect.collidepoint((posx - 113, posy)):
                        # We look at the card on the left
                        adjacentCards[3] = card
        elif self.player == -1:
            for card in self.player1Hand.cards:
                if card.inHand == 0:
                    if card.rect.collidepoint((posx, posy - 144)):
                        # We first look at the card on the top
                        adjacentCards[0] = card

                    if card.rect.collidepoint((posx + 113, posy)):
                        # We look at the card on the right
                        adjacentCards[1] = card

                    if card.rect.collidepoint((posx, posy + 144)):
                        # We look at the card on the bottom
                        adjacentCards[2] = card

                    if card.rect.collidepoint((posx - 113, posy)):
                        # We look at the card on the left
                        adjacentCards[3] = card
        return adjacentCards

    def changeOwner(self, cards):
        for card in cards:
            if card.owner == 1:
                self.player1Hand.cards.remove(card)
                self.player2Hand.cards.append(card)
            if card.owner == -1:
                self.player2Hand.cards.remove(card)
                self.player1Hand.cards.append(card)
            self.capturedAnimation(card)
        self.cardsOwner()

    def capturedAnimation(self, card):
        """Shows a little animation when capturing card"""
        # We want the sound of the card put played before doing anything more
        self.update()
        while (pygame.mixer.get_busy()):
            pass

        # self.Sound.capturedCard.play()
        width = card.rect.width  # we expect 113. If not please change format.
        height = card.image.get_rect().height  # Here we expect 139.
        topleft = list(card.rect.topleft)
        step = 30 - (self.fps / 30 * 3)

        while(width != 10):
            width -= step
            if width < 10:
                width = 10
            topleft[0] += step / 2
            getCard(card)
            card.image = pygame.transform.scale(card.image, (width, height))
            card.rect = card.image.get_rect()
            card.rect.topleft = topleft
            self.update()

        card.owner *= -1
        card.changeOwner()

        while (width != 113):
            width += step
            if width > 113:
                width = 113
            topleft[0] -= step / 2
            getCard(card)
            card.image = pygame.transform.scale(card.image, (width, height))
            card.rect = card.image.get_rect()
            card.rect.topleft = topleft
            self.update()

        # If card has a bonus or malus, we have to re-draw it on the card
        if card.modifierValue != 0:
            card.image.blit(card.modifierBack.surface, card.modifierBack.rect)
            card.image.blit(card.modifier.surface, card.modifier.rect)

    def winAnimation(self):
        """Show who won the game"""
        if self.scorePlayer1.score > self.scorePlayer2.score:
            self.winner.text = _("Blue win!")
            self.winner.rect.topleft = self.backgroundRect.midtop
            self.winner.rect.x -= 20
            self.winner.color = blue
        elif self.scorePlayer2.score > self.scorePlayer1.score:
            self.winner.text = _("Red win!")
            self.winner.rect.topright = self.backgroundRect.midtop
            self.winner.rect.x += 20
            self.winner.color = red
        else:
            self.winner.text = _("Equality!")
            self.winner.rect.topleft = self.backgroundRect.midtop
            self.winner.color = white

        self.winner.changeColor()
        self.winner.rect.y += 10

    def getCard(self, player):
        """Return the card at pygame.mouse.get_pos() coordinates """
        coords = pygame.mouse.get_pos()
        if player == 1:
            card = self.player1Hand.getCard(coords)
            if card >= 0:
                if self.CARD != None:
                    self.deselectedCard()
                self.CARD = self.player1Hand.cards[card]
        elif player == -1:
            card = self.player2Hand.getCard(coords)
            if card >= 0:
                if self.CARD != None:
                    self.deselectedCard()
                self.CARD = self.player2Hand.cards[card]
        elif player == 0:
            #If we get a right-click, then we want to print the About
            #popup even if it is an ennemy's card
            card = self.player1Hand.getCard(coords)
            if card != None:
                self.infoCARD = self.player1Hand.cards[card].About
            else:
                card = self.player2Hand.getCard(coords)
                if card != None:
                    self.infoCARD = self.player2Hand.cards[card].About
        if card != None:
            return 1
        return 0

    def showAbout(self):
        """Show some info on the card if we do a right-click on it"""
        width = 0
        quit = 0
        maxWidth = 450
        COLORRED = (200,0,0,125)
        COLORBLUE = (0,0,200,125)
        event = None
        if self.infoCARD.boss.owner == 1:
            COLOR = COLORBLUE
        elif self.infoCARD.boss.owner == -1:
            COLOR = COLORRED

        background = pygame.Surface((width, 140), SRCALPHA)
        rect = background.get_rect()
        background.fill(COLOR)

        if self.infoCARD.boss.owner == 1:
            rect.topleft = self.infoCARD.boss.rect.topright
        elif self.infoCARD.boss.owner == -1:
            rect.topright = self.infoCARD.boss.rect.topleft

        while 1:
            self.update()
            self.screen.blit(background,rect)
            pygame.display.flip()
            self.clock.tick(self.fps)

            if width < maxWidth and quit == 0:
                width += 40 - (self.fps / 30.0 * 5) 
                if width > maxWidth:
                    width = maxWidth
                background = pygame.Surface((width, 140), SRCALPHA)
                rect = background.get_rect()
                background.fill(COLOR)
                if self.infoCARD.boss.owner == 1:
                    rect.topleft = self.infoCARD.boss.rect.topright
                elif self.infoCARD.boss.owner == -1:
                    rect.topright = self.infoCARD.boss.rect.topleft

            if quit == 1:
                width -= 40 - (self.fps / 30.0 * 5)
                if width < 0:
                    width = 0
                background = pygame.Surface((width, 140), SRCALPHA)
                rect = background.get_rect()
                background.fill(COLOR)
                if self.infoCARD.boss.owner == 1:
                    rect.topleft = self.infoCARD.boss.rect.topright
                elif self.infoCARD.boss.owner == -1:
                    rect.topright = self.infoCARD.boss.rect.topleft

            if width == 0:
                if quit == 1:
                    self.update()
                    return
                quit = 1

            if width == maxWidth and quit == 0:
                background.fill(COLOR)
                background.blit(self.infoCARD.surface, self.infoCARD.rect)
                self.update()
                self.screen.blit(background,rect)
                pygame.display.flip()
                self.clock.tick(self.fps)
                event = pygame.event.wait()

            if width == 0:
                self.infoCARD = None
                self.update()
                return 0

            if event and event.type == MOUSEBUTTONUP:
                quit = 1
            elif event and event.type == QUIT:
                audio = [self.Sound.soundVolume, self.Sound.musicVolume]
                setConfig(audio)
                pygame.quit()
                sys.exit()

        return 0

    def showName(self, player):
        """Show the name of the card selected at the bottom of the window"""
        self.backCard, self.backCardRect = loadImage("name.png")

        if player == 1:
            for card in self.player1Hand.cards:
                if card == self.CARD:
                    name = self.CARD.name
                    self.cardName = Text(name, self.FONT, white, 40)
        elif player == -1:
            for card in self.player2Hand.cards:
                if card == self.CARD:
                    name = self.CARD.name
                    self.cardName = Text(name, self.FONT, white, 40)

        if self.cardName != None:
            self.cardName.rect.midbottom = self.backgroundRect.midbottom
            self.cardName.rect.y -= 10
            self.backCardRect.center = self.cardName.rect.center
from Sound import Sound

s = Sound('sounds/symphony.wav')
s.play()

while True:
    pass
Exemple #55
0
    def __init__(self, width, height, screen=None, soundInstance=None,
                  boss=None):
        # We create the window
        self.width = width
        self.height = height
        if screen == None:
            self.screen = pygame.display.set_mode((self.width, self.height))
        else:
            self.screen = screen

        if soundInstance == None:
            self.Sound = Sound()
        else:
            self.Sound = soundInstance
            print self.Sound.soundVolume

        self.background, self.backgroundRect = loadImage("background.jpg")

        # We keep the Menu instance if we are running TuxleTriad from Menu.py
        if boss != None:
            self.boss = boss
            self.boss.app = self
        else:
            self.boss = None

        # The Clock of the game, to manage the frame rate
        self.clock = pygame.time.Clock()
        self.fps = 60
        Cards1 = []
        Cards2 = []

        # We generate two  and draw 5 cards from each
        # to have an entire Hand of Card
        list1 = [i for i in range(len(allCards))]
        random.shuffle(list1)
        list2 = [i for i in range(len(allCards))]
        random.shuffle(list2)
        for i in range(5):
            number = list1[0]
            Cards1.append(Card(number, 1))
            list1.remove(number)
        for i in range(5):
            number = list2[0]
            Cards2.append(Card(number, -1))
            list2.remove(number)

        # We create the Hands to manage the lists of cards
        self.player1Hand = Hand(Cards1, 1)
        self.player2Hand = Hand(Cards2, -1)

        # We create the Score
        self.scorePlayer1 = Score("5", 1, self.width, self.height)
        self.scorePlayer2 = Score("5", -1, self.width, self.height)

        # With this variable, we cannot do anything until the animation
        #played is finished.
        self.animation = 0

        # If we have to play the animation in different directions
        self.sensAnimation = 0
        self.player = 1

        #self.Sound = Sound()
        self.position = None
        self.CARD = None

        # We create the field of the game, 3x3.
        sizeCard = self.player1Hand.cards[0].image.get_size()
        self.field = Field(self.width, self.height, sizeCard)
        self.alphaAnimation = 255
        self.emptyCase = 9

        # Manage the winner congratulations font
        self.winner = None
        self.winnerFont = pygame.font.Font(None, 60)

        # Manage the display of the name of the card selected
        self.cardFont = pygame.font.Font(None, 40)
        self.cardFontSurf = None

        # Manage the background for the name of the card selected
        self.backCard, self.backCardRect = loadImage("name.png")

        self.main()
Exemple #56
0
    def __init__(self, width, height, screen=None, soundInstance=None,
                  boss=None):
        # We create the window
        self.width = width
        self.height = height
        if screen == None:
            self.screen = pygame.display.set_mode((self.width, self.height))
        else:
            self.screen = screen

        if soundInstance == None:
            self.Sound = Sound()
        else:
            self.Sound = soundInstance

        self.background, self.backgroundRect = loadImage("background.jpg")

        # We keep the Menu instance if we are running TuxleTriad from Menu.py
        if boss != None:
            self.boss = boss
            self.boss.app = self
            self.FONT = self.boss.FONT
        else:
            self.boss = None
            self.FONT = "Dearest.ttf"

        # The Clock of the game, to manage the frame rate
        self.clock = pygame.time.Clock()
        self.fps = 60
        # Creation of two players
        self.player1 = Player(1)
        self.player2 = Player(-1)
        self.players = {1 : self.player1, -1 : self.player2}
        self.player1Hand = self.player1.hand
        self.player2Hand = self.player2.hand

        # We create the Score
        self.scorePlayer1 = Score("5", 1, self.width, self.height)
        self.scorePlayer2 = Score("5", -1, self.width, self.height)

        # With this variable, we cannot do anything until the animation
        # played is finished.
        self.animation = 0

        # If we have to play the animation in different directions
        self.sensAnimation = 0
        self.player = 1

        self.position = None
        self.CARD = None
        self.infoCARD = None

        # We create the field of the game, 3x3.
        sizeCard = self.player1Hand.cards[0].image.get_size()
        self.field = Field(self.width, self.height, sizeCard, self)
        self.emptySquare = 9

        self.alphaAnimation = 255

        # Manage the winner congratulations font
        self.winner = Text("", self.FONT, white, 60)

        # Manage the display of the name of the card selected
        self.cardName = None

        # Do we show the name of the card selected?
        self.selectedCardName = 1
class Sectoid(object):
    def __init__(self,name,hp=8,taunt=0,defense=10,cover=0,aimPen=0):
        self.name=name
        self.hp=hp
        self.playerTaunt=taunt
        self.alive=1
        self.defense=defense
        self.cover=cover
        self.aimPenalty=aimPen
        self.coverPosition=0
        self.wepSound=Sound().weaponSounds("Laser")
        self.deathSound=Sound().deathSounds("Sectoid")
        self.tauntSound=Sound().abilitySounds("Taunt")
        self.uponHit=Sound().enemyPainSounds("Sectoid")

#***********************************************************************
#ACTIONS ALIEN CAN TAKE
#***********************************************************************
    
    def action(self):
        action=0
        tRNG=random.randint(1,5)
        if tRNG==1:
            action="taunt"
        else:
            action="shoot"

        return action

    def taunt(self):     
        self.tauntSound.play()
        print ('{name} taunts you! \n It yells, "Gleep gloop!\n"'.format(name=self.name))
        pissOff=1
        return pissOff     

    def takeCover(self,alienBattleMap,pod,whichAlien):
        alienChooseCover=Sectoid.randomSample(alienBattleMap,pod,whichAlien)
        self.cover=alienBattleMap[alienChooseCover].getCovValue()
        self.aimPenalty=alienBattleMap[alienChooseCover].getAimPen()
        self.coverPosition=alienChooseCover
        return self.cover, self.aimPenalty,self.coverPosition

    def shoot(self,playerDef):
        targetHit=0
        print ("{NAME} shoots!\n".format(NAME=self.name))
        self.wepSound.play()
        adjustedHitChance=Sectoid.calcHitChance(self,playerDef)
        hitCoverRNG=random.randint(1,2)
        RNG=random.randint(1,100)
        if RNG <= adjustedHitChance:
            print ("Alien Chance to Hit: ", adjustedHitChance)
            print ("Alien's Roll: ", RNG,"\n")
            print ("Ouch! You're hit!\n")
            targetHit=1

        else:
            if hitCoverRNG==1:
                print ("Alien Chance to Hit: ", adjustedHitChance)
                print ("Alien's Roll: ", RNG,"\n")
                targetHit=3

            else:
                print ("Alien Chance to Hit: ", adjustedHitChance)
                print ("Alien's Roll: ", RNG,"\n")
                print ("It misses!\n")
                targetHit=2

        return targetHit



#******************************************************
#RNG FOR COVER SELECTION
#***************************************************   

    def randomCoverType(alienBattleMap):
        typeRNG=random.randrange(len(alienBattleMap))
        x=typeRNG
        return x

    def randomSample(alienBattleMap,pod,whichAlien):
        mapRNG=random.randrange(len(alienBattleMap))
        answer=mapRNG
        return answer


#************************************************
#ALIEN STAT CALCULATION
#*************************************************

    def getDefense(self):
        defense=self.defense+self.cover
        return defense
    
    def damage(self,DMGval):
        if self.hp > self.hp-DMGval:
            self.uponHit.play()
        self.hp-=DMGval
        if self.hp <=0:
            self.hp=0;
        if self.hp > 0:
            self.action
        if self.hp==0:
            print ("You killed it!")
        return self.hp

    def calcHitChance(self,playerDef):
        baseHitChance=80
        adjustedHitChance=baseHitChance-playerDef-self.aimPenalty
        if adjustedHitChance<0:
            adjustedHitChance=0
        if adjustedHitChance>100:
            adjustedHitChance=100
        return adjustedHitChance

#************************************************************
#RETURN CLASS VARIABLES
#************************************************************

    def __repr__(self):
        return self.name

    def __str__(self):
        return self.name

    def getName(self):
        return self.name
    
    def getHP(self):
        return self.hp

    def returnCoverPosition(self):
        return self.coverPosition

    def returnCoverValue(self):
        if self.cover==40:
            cover="High cover"
        elif self.cover==20:
            cover="Low cover"
        else:
            cover="No cover"
        return cover

    def playAlienDeath(self):
        self.deathSound.play()

    def playHitSound(self):
        self.uponHit.play()