def IteratedMGame(strategy, opponent, games):
    strategy.setOpponent(opponent)
    opponent.setOpponent(strategy)

    sc = Score(strategy.name(), strategy.author(),
               opponent.name())  # get the scores
    sc1 = Score(opponent.name(), opponent.author(), strategy.name())

    while (sc.runsMade < games.Iter_N):
        strategy.play(games)  # play one round
        opponent.play(games)

        strategy.calculateScore(games)
        opponent.calculateScore(games)
        sc.runsMade += 1
        sc1.runsMade += 1

        sc.lambd = strategy.getLastLambda()
        sc.materialScore = strategy.getMaterialSc()
        sc.socialScore = strategy.getSocialSc()
        sc.aggregates = sc.socialScore * games.Lambda_global + sc.materialScore * (
            1.0 - games.Lambda_global)

        sc1.lambd = opponent.getLastLambda()
        sc1.materialScore = opponent.getMaterialSc()
        sc1.socialScore = opponent.getSocialSc()
        sc1.aggregates = sc1.socialScore * games.Lambda_global + sc1.materialScore * (
            1.0 - games.Lambda_global)

    return sc.materialScore, sc.socialScore, sc.aggregates, sc1.aggregates
Ejemplo n.º 2
0
    def __init__(self, master=None):
        """
        Constructeur de l'application
        Initialise tous les éléments visuels, sonores et touches
        @param master: Fenetre mère tkinter
        """

        self.canvas = None
        self.main_frame = None
        self.hp_canvas = None
        self.frameHeros = None
        self.rows = None
        self.ennemies = None
        self.vague = 1

        super().__init__(master)
        self.master = master
        self.pack(fill="both")
        self.score = Score()
        self.create_HPBAR()
        self.create_MAIN()
        self.hero = Joueur(ask_name())
        self.drawJoueur()
        self.init_game(fullreset=True)
        self.pause()
        self.init_sound()
        self.init_touch_binding()
Ejemplo n.º 3
0
    def listPlays(self):
        self.moveList.clear()
        for rowIndex in range(len(self.boardState)):
            k = 0
            for colIndex in range(len(self.boardState[0])):
                if self.boardState[rowIndex][colIndex].isAnchor():
                    score = Score.Score()
                    # case anchor immediately right of extant letter
                    if (colIndex > 0
                            and self.boardState[rowIndex][colIndex -
                                                          1].isNotEmpty()):
                        iterNode = self.dictionary.root
                        # 4 means look left
                        wordStart = self._findWordStart(rowIndex, colIndex, 4)
                        for x in range(colIndex - len(wordStart), colIndex):
                            currentSquare = self.boardState[rowIndex][x]
                            if currentSquare.get() not in iterNode.neighbors:
                                raise Exception("Illegal word on board")
                            iterNode = iterNode.neighbors[currentSquare.get()]
                            adding = self._wordToScore(currentSquare.get())
                            score.word += adding
                        self._extendRight(wordStart, iterNode, rowIndex,
                                          colIndex, True, score)
                    else:
                        self._leftPart("", self.dictionary.root, k, rowIndex,
                                       colIndex, score)
                    k = 0

                else:
                    k += 1
Ejemplo n.º 4
0
    def get_rmsle_list(self, dataset, num_folds, n_estimators_list):
        self.num_iterations += 1
        print 'n_estimators_list: %s' % n_estimators_list
        rmsle_list = []
        score = Score.Score()

        for fold_ind in range(num_folds):
            print '  fold_ind: %d' % fold_ind
            fold_train = dataset.getTrainFold(fold_ind)
            fold_test = dataset.getTestFold(fold_ind)
            self._train(fold_train, n_estimators_list)
            score.addFold(fold_test.getSales(), self.predict(fold_test))

            for month_ind in range(12):
                cur_rmsle = score.getRMSLE(month_ind)
                rmsle_list.append(cur_rmsle)

                if cur_rmsle < self.best_rmsle_list[month_ind]:
                    self.is_best = True
                    self.best_rmsle_list[month_ind] = cur_rmsle
                    self.n_estimators_list[month_ind] = n_estimators_list[
                        month_ind]

        print 'best_n_estimators_list: %s' % self.n_estimators_list
        return rmsle_list
Ejemplo n.º 5
0
  def cross_validate(self, dataset, num_folds):
    dataset.createFolds(num_folds)
    best_params = None
    best_rmsle = float("inf")
    for C in SVMRegression.C_vals:
      for poly_degree in SVMRegression.poly_degrees:
        if self.debug:  
          print "Running SVM regression with C=%d, poly_degree=%d on %d folds" %(C, poly_degree, num_folds)

        cur_score = Score.Score()

        for fold_ind in range(num_folds):
          fold_train = dataset.getTrainFold(fold_ind)
          fold_test = dataset.getTestFold(fold_ind)
          self._train_with_values(fold_train, poly_degree=poly_degree, C=C)
          cur_score.addFold(fold_test.getSales(), self.predict(fold_test))
          
        cur_rmsle = cur_score.getRMSLE()
        if cur_rmsle < best_rmsle:
          if self.debug:
            print "Achieved new best score %f" %cur_rmsle
          best_params = (C, poly_degree)
          best_rmsle = cur_rmsle
        
    self.C, self.poly_degree = best_params
Ejemplo n.º 6
0
 def __init__(self, d):
     self.doc = d
     self.maxLyrics = 0
     self.lastVolta = 0
     self.beamMode = BeamMode.BEAM_NO
     self.score = Score.Score(defaultStyle)
     self.measureLength = list()
Ejemplo n.º 7
0
def main():
    fileSeq = "../files/maguk-sequences.fasta"
    fileMatrice = "../files/blosum62.iij"
    parsedFiles = Parser(fileSeq, fileMatrice)
    #=============== Sequences ================
    mySequences = parsedFiles.getSeq()
    # for elem in mySequences:
    # 	print(elem)
    #==========================================

    #================ Blosum ==================
    listAA = parsedFiles.getListAA()
    blosum = parsedFiles.getBlosum()
    blosumObj = Blosum(listAA, blosum)
    #print(blosumMatrice)

    # print(mySequences[0])
    # print(mySequences[1])

    x1 = ["T", "H", "I", "S", "L", "I", "N", "E", "D", "E", "D", "E", "D"]
    x2 = ["I", "S", "A", "L", "I", "G", "N", "E", "D", "A", "D", "I"]
    x1 = ["T", "H", "I", "S", "L", "I", "N", "E"]
    x2 = ["I", "S", "A", "L", "I", "G", "N", "E", "D"]
    x1 = mySequences[0].getSeq()
    x2 = mySequences[2].getSeq()
    x1 = ["M", "G", "G", "E", "T", "F", "A"]
    x2 = ["G", "G", "V", "T", "T", "F"]

    print(x1)
    print(x2)
    test = Score(x1, x2, blosumObj, -4)
Ejemplo n.º 8
0
    def get_rmsle_list(self, dataset, num_folds, alpha_list, rho_list):
        self.num_iterations += 1

        rmsle_list = []

        score = Score.Score()
        for fold_ind in range(num_folds):
            fold_train = dataset.getTrainFold(fold_ind)
            fold_test = dataset.getTestFold(fold_ind)
            self._train(fold_train, alpha_list, rho_list)
            score.addFold(fold_test.getSales(), self.predict(fold_test))

        for month_ind in range(12):
            cur_rmsle = score.getRMSLE(month_ind)
            rmsle_list.append(cur_rmsle)

            if cur_rmsle < self.best_rmsle_list[month_ind]:
                self.is_best = True
                self.best_rmsle_list[month_ind] = cur_rmsle
                self.alpha_list[month_ind] = alpha_list[month_ind]
                self.rho_list[month_ind] = rho_list[month_ind]

        print "alpha_list: %s" % alpha_list
        print "best_rho_list: %s" % str(self.rho_list)
        print "best_alpha_list: %s" % str(self.alpha_list)
        return rmsle_list
Ejemplo n.º 9
0
def rhythmModeInit(data):
    data.players.empty()
    data.leftPlayers.empty()
    data.midPlayers.empty()
    data.rightPlayers.empty()
    data.leftPlayers.add(Player(data, 0))
    data.midPlayers.add(Player(data, 1))
    data.rightPlayers.add(Player(data, 2))
    data.score = Score()
Ejemplo n.º 10
0
def grooveModeInit(data):
    # resest players and score
    data.players.empty()
    data.leftPlayers.empty()
    data.midPlayers.empty()
    data.rightPlayers.empty()
    player = Player(data, 0)  # for pink color
    player.lane = 1  # move to middle
    player.updateXPos(data)
    data.players.add(player)
    data.score = Score()
Ejemplo n.º 11
0
def BruteForceMotifSearch(DNA, t, n, l):
    assert l > 0
    assert n > 0
    assert DNA != []
    assert t > 0
    s_tree = [1] * t
    s = [0 for i in range(t)]
    # pozycje startowe
    bestScore = sc.Score(s, DNA, l + 1)  # score pierwszego liscia
    bestMotif = [x for x in s]
    while True:
        s_tree = tree.NextLeaf(s_tree, t, n - l + 1)  # nastepny lisc
        s = [s_treex - 1 for s_treex in s_tree]
        # przeszukiwanie po drzewie w celu znalezienia najlepszego score
        if sc.Score(s, DNA, l) > bestScore:
            bestScore = sc.Score(s, DNA, l)
            bestMotif = [x for x in s]
        if sum(s_tree) == t:
            break
    return bestMotif
Ejemplo n.º 12
0
 def on_init(self):
     self.gamedisplay = pygame.display.set_mode(
         self.size, pygame.HWSURFACE | pygame.DOUBLEBUF)
     GameWorld.Gameworld.gameDisplay = self.gamedisplay
     pygame.display.set_caption(self.name)
     pygame.display.set_icon(self.img)
     self.clock = pygame.time.Clock()
     self.score = Score.Score()
     self.gameworld = GameWorld.Gameworld(self.score)
     self.UI = UI.UI(self.score, (self.display_width, self.display_height))
     return True
Ejemplo n.º 13
0
def IteratedPD(strategy, opponent, games):
    strategy.setOpponent(opponent)
    opponent.setOpponent(strategy)

    sc = Score(strategy.name(), strategy.author(), opponent.name())   # get the scores
    sc1 = Score(opponent.name(), opponent.author(), strategy.name())

    while(sc.runsMade < games.Iter_N):
        strategy.play(games)    # play one round
        opponent.play(games)

        strategy.calculateScore(games)
        opponent.calculateScore(games)
        sc.runsMade += 1
        sc1.runsMade += 1

        sc.materialScore = strategy.getMaterialSc()
        sc1.materialScore = opponent.getMaterialSc()

    return sc.materialScore, sc1.materialScore
Ejemplo n.º 14
0
def BranchAndBoundMotifSearch(DNA, t, n, l):
    """ t - number of sample DNA sequences
    n - length of each DNA sequence
    l - length of the motif (l -mer)
    s=(s1, s2,… st) - array of motif’s starting
    positions"""
    assert l > 1
    assert n > 1
    assert DNA != []
    assert t > 1

    bestScore = 0
    i = 0  # poziom drzewa
    s_tree = [1] * t  # pozycje startowe
    while True:
        assert i <= t
        if i < t:  # poziom musi byc mniejszy od wysokosci
            s = [s_treex - 1 for s_treex in s_tree]
            optimisticScore = sc.Score(s, DNA, l) + (t - i) * l
            # optymistyczny score dla nie do konca wypelnionych pozycji startowch np 1_ _ _
            # oszczedza zagladanie do (n–l + 1)^t-i lisci
            if optimisticScore < bestScore:
                s_tree, i = tree.Bypass(s_tree, i, t, n - l + 1)
                # pomijamy dzieci, poniewaz nie znajdziemy wsrod nich lepszego score od
                # optymistycznego
            else:
                s_tree, i = tree.NextVertex(s_tree, i, t, n - l + 1)
        else:
            s = [s_treex - 1 for s_treex in s_tree]
            score = sc.Score(s, DNA, l)
            if score > bestScore:  # jesli znalezlismy lepsze score
                bestScore = score  # ustawiamy je jako najlepsze
                bestMotif = [
                    x for x in s
                ]  # i pozycje startowe dzieki ktorym mozna uzyskac score
            s_tree, i = tree.NextVertex(s_tree, i, t, n - l + 1)
        if sum(
                s_tree
        ) == 0:  # jesli skonczymy na wierzcholku ( 0,0,...,0) przerywamy
            break
    return bestMotif
Ejemplo n.º 15
0
    def _leftPart(self, partialWord, node, limit, row, col, score):
        """Create options for left part"""
        self._leftValue(partialWord, row, col, score)
        self._extendRight(partialWord, node, row, col, True, score)
        if limit > 0:
            for e in node.neighbors:
                if e in self.robotRack:
                    self.robotRack.remove(e)

                    self._leftPart(partialWord + e, node.neighbors[e],
                                   limit - 1, row, col, Score.Score())
                    self.robotRack.append(e)
Ejemplo n.º 16
0
 def event(self, event):
     if event.type == PG.MOUSEBUTTONDOWN:
         if self.selected[0]:
             G.Globals.STATE = StoryBoard.StoryBoard(
                 "story_texts/intro.txt", self.images)
         if self.selected[1]:
             G.Globals.STATE = Instructions.Instructions()
         if self.selected[2]:
             G.Globals.STATE = Options.Options()
         if self.selected[3]:
             G.Globals.STATE = Score.Score()
         if self.selected[4]:
             G.Globals.RUNNING = False
Ejemplo n.º 17
0
 def __init__(self, sense):
     """
     Initialize the game world
     :param sense The sense hat
     """
     self.level = Level()
     self.score = Score()
     self.mappy = Map(0, 7)
     self.snake = Snake(3, self.mappy)
     self.candy = Candy(self.snake)
     self.sense = sense
     self.i = 0
     print(self.snake)
     self.sense.clear()
     self.sense.show_message("Level: " + str(self.level.level),
                             text_colour=[180, 180, 180])
Ejemplo n.º 18
0
def main():
    score = Score.Score()
    while not score.is_over():
        parts, threads = init_all(score)
        score_was_changed = False
        while threads[2].isAlive():  #while the score is not changed
            stop = datetime.datetime.now() + datetime.timedelta(
                seconds=config.GAME_DELAY)

            while (datetime.datetime.now() < stop):
                pass

            update_screen(score, parts)
        score.inc_score(parts[2].loc[1] == 0)
        update_screen(score, parts)
        parts[0].kill_thread()
        parts[1].kill_thread()
Ejemplo n.º 19
0
def predict_vm(ecs_infor_array,input_file_array):

    #Get the CPU information
    N_Stype,Servers,N_Pvm,Pvm,Predict_time,Predict_Start=utils.splitEscData(ecs_infor_array)

    #Get the History Data information
    length,Hvm,History_End=utils.splitInputData(input_file_array)
    #History Data


    #Statistic and Split
    #lenD,S_Data=utils.Statistic_Split(length,Hvm,N_Pvm,Pvm)
    lenD,S_Data=utils.Denoise_Split(length,Hvm,N_Pvm,Pvm)

    # deal with gaps
    gaps=int(round((utils.getTimeDiff(Predict_Start,History_End))/86400))
    for i in range(N_Pvm):
        for j in range(gaps):
            S_Data[i].append(S_Data[i][-7])
    print S_Data

    
    result = []
    if ecs_infor_array is None:
        print 'ecs information is none'
        return result
    if input_file_array is None:
        print 'input file information is none'
        return result

    #-----------------------Smirror-------------------------
    #NEPvm=mirror.Smirror(lenD,N_Pvm,S_Data,Predict_time)
    #-----------------------Smirror-------------------------
    #NEPvm=mirror.Commirror(lenD,N_Pvm,S_Data,Predict_time)
    #------------------------ES-----------------------------
    NEPvm=ES.CES(lenD,N_Pvm,S_Data,Predict_time)
    print NEPvm
    
    # allocation
    Servers_N,P_Servers=Allocation.Allocate(NEPvm,Pvm,N_Stype,Servers)

    S=Score.Score(NEPvm,Pvm,Servers_N,P_Servers,Servers)
    print S
    
    result=utils.results_expression(P_Servers,Servers_N,Servers,Pvm)
    return result
Ejemplo n.º 20
0
    def __init__(self, frame):
        self.width = 0
        self.height = 0
        self.frame = frame
        self.width, self.height = pygame.display.get_surface().get_size()

        pygame.display.set_caption("Fishin' Mission")
        self.frame.fill((135, 206, 235))
        self.cloud = Clouds.Clouds(self.frame)
        self.fisher = Fisher.Fisher(self.frame)
        self.boat = Boat.Boat(self.frame)
        self.rod = Rod.Rod(self.frame)
        self.wave = Waves.Waves(self.frame)
        self.score = Score.Score(self.frame)
        self.upgrades = Upgrades.Upgrades(self.frame)
        self.trash_list = []
        self.trash_interval = 6
        self.start_time = time.time()
        self.fish1_list = []
        self.fish2_list = []
        self.fish3_list = []
        self.fish1_interval = 10
        self.fish2_interval = 5
        self.fish3_interval = 20
        self.trashCount = 0
        self.fish1Count = 0
        self.fish2Count = 0
        self.fish3Count = 0

        # Load Fish Images
        self.image1 = pygame.image.load('images/small fish.png')
        self.image2 = pygame.image.load('images/medium sized fish.png')
        self.image3 = pygame.image.load('images/big fish.png')
        self.fish1width = 117
        self.fish1height = 117
        self.fish2width = 146
        self.fish2height = 146
        self.fish3width = 176
        self.fish3height = 176
        self.image1 = pygame.transform.scale(
            self.image1, (self.fish1width, self.fish1height))
        self.image2 = pygame.transform.scale(
            self.image2, (self.fish2width, self.fish2height))
        self.image3 = pygame.transform.scale(
            self.image3, (self.fish3width, self.fish3height))
Ejemplo n.º 21
0
 def __init__(self):
     self.time = 0
     self.step = 0.003
     self.path = Path.Path()
     pos = Position.Position(0, 0)
     pos.y = 420
     self.path.add(pos, 0)
     pos.x = 90
     self.path.add(pos, 1)
     pos.x = 180
     self.path.add(pos, 1)
     pos.y = 180
     self.path.add(pos, 2)
     pos.x = 420
     self.path.add(pos, 2)
     pos.y = 500
     self.path.add(pos, 2)
     pos.x = 750
     self.path.add(pos, 2)
     pos.y = 330
     self.path.add(pos, 1)
     pos.x = 1250
     self.path.add(pos, 2)
     pos.x = 1350
     self.path.add(pos, 2)
     self.tower = Towers.Tower(0, 0)
     self.map = Map.Map()
     self.area = Area.Area()
     self.wave = Wave.Wave(self.path)
     self.wave.nextWave()
     self.score = Score.Score()
     self.shop = Shop.Shop()
     self.isSetupDone = False
     self.setupTime = 0
     self.newTower = False
     self.newTowerType = 0
     self.enemies = pygame.sprite.Group()
     self.towerList = list()
     self.avg = list()
     self.timer = 0
     self.startTimer = False
Ejemplo n.º 22
0
    def post(self, article_id):
        if self.user:
            username = self.request.get("username")
            score = self.request.get("score")
            user_id = str(self.user.key.integer_id())

            article = NewsArticle.get_by_id(id = long(article_id), parent = article_key())
            article.total_score += float(score)
            article.no_scored += 1
            temp = article.total_score / float( article.no_scored )
            article.score = '%.2f' % temp
            logging.warning("Hello %s / %s = %s" % (article.total_score, article.no_scored, article.score) )
            add_article(article)
            articlekey = 'ARTICLE_' + article_id
            age_set(articlekey, article)

            s = Score(parent = score_key(), user_id = user_id, article_id = article_id, score = float(score) )
            s.put()
            scorekey = 'SCORE_' + article_id + '_' + user_id
            age_set(scorekey, s)
            logging.warning('scorekey = %s' % scorekey)

            self.render_post(article = article, score = s)
Ejemplo n.º 23
0
    def __init__(self, player):
        """ Constructor. Pass in a handle to player. Needed for when moving
            platforms collide with the player. """
        self.platform_list = pygame.sprite.Group()
        self.bumper_list = pygame.sprite.Group()
        self.platformRetourArriere_list = pygame.sprite.Group()
        self.platformRetourAvant_list = pygame.sprite.Group()
        self.piece_list = pygame.sprite.Group()
        self.enemy_list = pygame.sprite.Group()
        self.ennemy_tourelle_liste = pygame.sprite.Group()
        self.score = Score()
        self.player = player
        self.bullets_liste = pygame.sprite.Group()
        font.init()
        self.font_a = pygame.font.SysFont('arial', 40)
        self.font_b = pygame.font.SysFont('arial', 70)
        self.font_score = self.font_a.render(self.score.getScore(), 1,
                                             (YELLOW))
        self.font_multiplicateur = self.font_a.render(
            "x " + self.score.getMultiplicateur(), 1, (ORANGE))

        # How far this world has been scrolled left/right
        self.world_shiftx = 0
        self.world_shifty = 0
Ejemplo n.º 24
0
    def cross_validate(self, dataset, num_folds):
        dataset.createFolds(num_folds)

        best_rmsle_list = [float("inf")] * 12
        best_k_list = [None] * 12
        for k in NearestNeighbor.k_values:
            cur_score = Score.Score()

            for fold_ind in range(num_folds):
                fold_train = dataset.getTrainFold(fold_ind)
                fold_test = dataset.getTestFold(fold_ind)
                self._train(fold_train, k)
                cur_score.addFold(fold_test.getSales(),
                                  self.predict(fold_test))

            for month_ind in range(12):
                cur_rmsle = cur_score.getRMSLE(month_ind)
                if cur_rmsle < best_rmsle_list[month_ind]:
                    best_rmsle_list[month_ind] = cur_rmsle
                    best_k_list[month_ind] = k

        self.k_list = list(best_k_list)
        if self.debug:
            print "Best k-values by month: %s" % str(self.k_list)
Ejemplo n.º 25
0
def predict_vm(ecs_infor_array,input_file_array):

    #Get the CPU information
    N_Stype,Servers,N_Pvm,Pvm,Predict_time,Predict_Start=utils.splitEscData(ecs_infor_array)

    #Get the History Data information
    length,Hvm,History_End=utils.splitInputData(input_file_array)
    #History Data
    Hdate=datetime.datetime.strptime(History_End,"%Y-%m-%d %H:%M:%S").date()
    
    #Statistic and Split
    #lenD,S_Data=utils.Statistic_Split(length,Hvm,N_Pvm,Pvm)
    lenD,S_Data=utils.Denoise_Split(length,Hvm,N_Pvm,Pvm)

    # deal with gaps
    gaps=int(round((utils.getTimeDiff(Predict_Start,History_End))/86400))
    for i in range(N_Pvm):
        for j in range(gaps):
            S_Data[i].append(S_Data[i][(-7)])

    
    result = []
    if ecs_infor_array is None:
        print 'ecs information is none'
        return result
    if input_file_array is None:
        print 'input file information is none'
        return result

    #-----------------------Smirror-------------------------
    #NEPvm=mirror.Smirror(lenD,N_Pvm,S_Data,Predict_time)
    #-----------------------Smirror-------------------------
    #NEPvm=mirror.Commirror(lenD,N_Pvm,S_Data,Predict_time)
    #------------------------ES-----------------------------
    #NEPvm=ES.ES(lenD,N_Pvm,S_Data,Predict_time,Days_Gap)

    
    if(N_Pvm>5):
        V=3.3
        NEPvm=mirror.Commirror(lenD,N_Pvm,S_Data,Predict_time,V)
        for i in range(N_Pvm):
            if(Pvm[i][0]=="flavor3")and(Hdate.month>6):
                NEPvm[i]=int(NEPvm[i]*19)
    else:
        '''
        #return
        V=0.65
        NEPvm=mirror.Commirror(lenD,N_Pvm,S_Data,Predict_time,V)
        '''
        V=1
        NEPvm=mirror.Smirror(lenD,N_Pvm,S_Data,Predict_time,V)
   
    print NEPvm
    
    # allocation
    Servers_N,P_Servers=Allocation.Allocate(NEPvm,Pvm,N_Stype,Servers)

    S=Score.Score(NEPvm,Pvm,Servers_N,P_Servers,Servers)
    print S
    
    result=utils.results_expression(P_Servers,Servers_N,Servers,Pvm)
    return result
Ejemplo n.º 26
0
def run_game():
    pygame.init()
    setinit = Game_Settings.Settings_of_Show()
    screen = pygame.display.set_mode(
        (setinit.screen_width, setinit.screen_height))

    pygame.display.set_caption("联机坦克大战")
    tank1 = Tank.Tank1(screen)
    tank2 = Tank.Tank2(screen)
    bullets1 = Group()
    bullets2 = Group()

    start_button = Button.Button(screen, 80, 40, (0, 255, 0), (255, 255, 255),
                                 "开始游戏", (500, 200))
    settings_button = Button.Button(screen, 80, 40, (164, 247, 151),
                                    (255, 255, 255), "游戏设置", (500, 300))
    help_button = Button.Button(screen, 80, 40, (105, 194, 49),
                                (255, 255, 255), "游戏帮助", (500, 400))
    game_settings = Game_Settings.Settings(tank_speed=5,
                                           bullet_speed=1,
                                           bullet_allow_num=1)

    bullet_speed1 = Button.Button(screen, 80, 40, (164, 247, 151),
                                  (255, 255, 255), "炮弹速度1", (200, 150))
    bullet_speed2 = Button.Button(screen, 80, 40, (164, 247, 151),
                                  (255, 255, 255), "炮弹速度2", (500, 150))
    bullet_speed3 = Button.Button(screen, 80, 40, (164, 247, 151),
                                  (255, 255, 255), "炮弹速度3", (800, 150))
    tank_speed1 = Button.Button(screen, 80, 40, (164, 247, 151),
                                (255, 255, 255), "坦克速度1", (200, 300))
    tank_speed2 = Button.Button(screen, 80, 40, (164, 247, 151),
                                (255, 255, 255), "坦克速度2", (500, 300))
    tank_speed3 = Button.Button(screen, 80, 40, (164, 247, 151),
                                (255, 255, 255), "坦克速度3", (800, 300))
    login_name_input = TextBox.TextBox(screen, None, None, 20, "隶书", (0, 0, 0),
                                       (255, 255, 255), (500, 300), "输入用户名")
    password_input = TextBox.TextBox(screen, None, None, 20, "隶书", (0, 0, 0),
                                     (255, 255, 255), (500, 300), "输入密码")

    sound_shoot = pygame.mixer.Sound("music//shoot.wav")

    flag = None
    login_name = "wsde"
    '''

    while flag!=login_name:
        screen.fill(setinit.bg_color)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                flag = login_name_input.key_down_text(event)
                print(flag)
        login_name_input.draw_textbox()
        pygame.display.flip()

    flag = None
    password: str = "mmnf"
    print(password)
    while flag != password:
        screen.fill(setinit.bg_color)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                flag= password_input.key_down_text(event)

        password_input.draw_textbox()
        pygame.display.flip()
    '''
    # 游戏主界面
    while True:
        screen.fill(setinit.bg_color)
        flag = game_button(start_button, settings_button, help_button)
        if flag == 0:
            settings_button.draw()

            start_button.draw()

            help_button.draw()

        if flag == -1:
            pygame.display.flip()
            screen.fill(setinit.bg_color)
            #print("-1")

            pygame.display.flip()
            #print(game_settings.tank_speed, game_settings.bullet_speed)
            score_of_two = Score.Score(screen, tank1, tank2, bullets1,
                                       bullets2, setinit)
            # 进入游戏
            main_flag = False
            while not main_flag:

                screen.fill(setinit.bg_color)
                score_of_two.score_change()
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        sys.exit()
                tank1_control_event(game_settings, tank1, bullets1, screen,
                                    sound_shoot)
                tank2_control_event(game_settings, tank2, bullets2, screen,
                                    sound_shoot)

                score_of_two.score_draw()

                for i in bullets1.copy():
                    if i.rect.centerx <= 0 or i.rect.centerx >= 1000:
                        bullets1.remove(i)
                    elif i.rect.centery >= 600 or i.rect.centery <= 0:
                        bullets1.remove(i)
                for i in bullets1.sprites():
                    i.draw_bull()

                for i in bullets2.copy():
                    if i.rect.centerx <= 0 or i.rect.centerx >= 1000:
                        bullets2.remove(i)
                    elif i.rect.centery >= 600 or i.rect.centery <= 0:
                        bullets2.remove(i)
                for i in bullets2.sprites():
                    i.draw_bull()
                update_screen(tank1, bullets1, tank2, bullets2)
                main_flag = score_of_two.who_win()
                pygame.display.flip()

            score_of_two.who_win()
            time.sleep(10)
        if flag == -2:
            pygame.display.flip()
            screen.fill(setinit.bg_color)
            # print("-2")
            temp_settings = -1
            while True:
                # print("1")

                if temp_settings == -1:
                    screen.fill(setinit.bg_color)
                    # print("设定难度")
                    bullet_speed1.draw()
                    bullet_speed2.draw()
                    bullet_speed3.draw()
                    tank_speed1.draw()
                    tank_speed2.draw()
                    tank_speed3.draw()

                    temp_settings: int = settings_mode_ui(
                        game_settings, bullet_speed1, bullet_speed2,
                        bullet_speed3, tank_speed1, tank_speed2, tank_speed3)
                    pygame.display.flip()

                # print(temp_settings)
                if temp_settings == 1:
                    screen.fill(setinit.bg_color)

                    break
                if temp_settings == 2:
                    screen.fill(setinit.bg_color)

                    break
                if temp_settings == 3:
                    screen.fill(setinit.bg_color)

                    break
                if temp_settings == 4:
                    screen.fill(setinit.bg_color)

                    break
                if temp_settings == 5:
                    screen.fill(setinit.bg_color)

                    break
                if temp_settings == 6:
                    screen.fill(setinit.bg_color)

                    break

        if flag == -3:
            pygame.display.flip()
            screen.fill(setinit.bg_color)
            # print("-2")
            help_flag = -1
            jump_end_button = Button.Button(screen, 40, 50, (164, 247, 151),
                                            (255, 255, 255), "结束", (800, 300))
            while True:
                if help_flag == -1:
                    screen.fill(setinit.bg_color)
                    font = pygame.font.SysFont("隶书", 20)
                    text = font.render("服务器端上线后,客户端才可以登录", True,
                                       (255, 255, 255), (0, 255, 0))
                    text_rect = text.get_rect()
                    text_rect.center = screen.get_rect().center
                    screen.blit(text, text_rect)
                    jump_end_button.draw()
                    help_flag = end_help(jump_end_button)
                    pygame.display.flip()
                if help_flag == 1:

                    break

        pygame.display.flip()
Score.containers = all, HUD

while True:
    levx = 1
    levy = 1
    world = 1
    level = Level(str(world) + "." + str(levy) + str(levx) + ".lvl", tileSize)
    bgImage = pygame.image.load("Background/Floor.png").convert()
    bgRect = bgImage.get_rect()
    for p in thePlayers.sprites():
        player2 = p
    player = Player(5,
                    [4 * tileSize + tileSize / 2, 6 * tileSize + tileSize / 2])
    print levelChangeBlocks.sprites()
    timer = Timer([132, 50])
    score = Score([100, height - 30])
    #score2 = Score([width - 100, height - 30])
    #levelIndicator = LevelIndicator([width-10, 16], lev)
    while player.living:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    player.go("up")
                if event.key == pygame.K_DOWN:
                    player.go("down")
                if event.key == pygame.K_RIGHT:
                    player.go("right")
                if event.key == pygame.K_LEFT:
                    player.go("left")
                #if event.key == pygame.K_w:
Ejemplo n.º 28
0
def GameLoop():
    global game_speed
    game_speed = 60
    global game_exit
    game_exit = False

    Init()
    NonMovingBackgroundDisplay()

    InitializeStairPhotos()

    #initial stair list
    global stair_list
    stair_list = []
    Stair.stair_list = stair_list
    for i in range(8):
        new_stair = Stair.Stair(display_width * 0.6, i)
        stair_list.append(new_stair)
    stair_list[4].x = 300
    stair_list[4].type = "general"

    jie_front = pygame.image.load('小傑正面.png')
    jie_right1 = pygame.image.load('小傑側面_右跨步.png')
    jie_right2 = pygame.image.load('小傑側面_右收步.png')
    jie_left1 = pygame.image.load('小傑側面_左跨步.png')
    jie_left2 = pygame.image.load('小傑側面_左收步.png')
    jie_front = pygame.transform.scale(jie_front,
                                       (Person.width, Person.height))
    jie_right1 = pygame.transform.scale(jie_right1,
                                        (Person.width, Person.height))
    jie_right2 = pygame.transform.scale(jie_right2,
                                        (Person.width, Person.height))
    jie_left1 = pygame.transform.scale(jie_left1,
                                       (Person.width, Person.height))
    jie_left2 = pygame.transform.scale(jie_left2,
                                       (Person.width, Person.height))

    ming_front = pygame.image.load('小銘正面.png')
    ming_right1 = pygame.image.load('小銘側面_右跨步.png')
    ming_right2 = pygame.image.load('小銘側面_右收步.png')
    ming_left1 = pygame.image.load('小銘側面_左跨步.png')
    ming_left2 = pygame.image.load('小銘側面_左收步.png')
    ming_front = pygame.transform.scale(ming_front,
                                        (Person.width, Person.height))
    ming_right1 = pygame.transform.scale(ming_right1,
                                         (Person.width, Person.height))
    ming_right2 = pygame.transform.scale(ming_right2,
                                         (Person.width, Person.height))
    ming_left1 = pygame.transform.scale(ming_left1,
                                        (Person.width, Person.height))
    ming_left2 = pygame.transform.scale(ming_left2,
                                        (Person.width, Person.height))

    global person_list
    person_list = []
    Person.display_width = display_width
    Person.display_height = display_height
    for i in range(Tool.players):
        if i == 0:
            person = Person.Person(300 + 75 + 40 - i * 40,
                                   stair_list[4].y - 60, jie_front, jie_right1,
                                   jie_right2, jie_left1, jie_left2, i + 1)
        elif i == 1:
            person = Person.Person(300 + 75 + 40 - i * 40,
                                   stair_list[4].y - 60, ming_front,
                                   ming_right1, ming_right2, ming_left1,
                                   ming_left2, i + 1)
        person_list.append(person)

    Score.Instance = Score.Score()

    global events

    alt = False
    f4 = False
    while not game_exit:
        try:
            #Update and Display

            BackgroundDisplay()
            events = pygame.event.get()
            for i in range(8):
                stair_list[i].Update(display_width * 0.6)
                """
                for person in person_list:
                    stair_list[i].HitPersonUpdate(person)
                """

            # 附近的樓梯檢查碰撞就好

            for person in person_list:
                try:
                    stair_list[(person.y - 33) // 75].HitPersonUpdate(person)
                except IndexError:
                    pass
                try:
                    stair_list[(person.y - 33) // 75 +
                               1].HitPersonUpdate(person)
                except IndexError:
                    pass

            # person update
            for person in person_list:
                person.Update(events)

            if Tool.players == 2:
                Person.PersonInteraction(person_list)

            Score.Instance.Update()

            GraphicDisplay()

            for event in events:
                Tool.CheckAltF4(event)
                #Quit
                if event.type == pygame.QUIT:
                    QuitGame()

                #Press Space to Pause
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        Paused()
                    if event.key == pygame.K_F4:
                        f4 = True
                    if event.key == pygame.K_LALT or event.key == pygame.K_RALT:
                        alt = True

                if alt and f4:
                    QuitGame()

                if event.type == pygame.KEYUP:
                    if event.key == pygame.K_F4:
                        f4 = False
                    if event.key == pygame.K_LALT or event.key == pygame.K_RALT:
                        alt = False

            pygame.display.update()
            if Score.Instance.current_score % 50 == 0:
                game_speed += 0.2
            clock.tick(int(game_speed))

        except Exceptions.GameOverError:
            game_exit = True
Ejemplo n.º 29
0
def game():
    def runHappyDog():
        hDog.startAnimation()

    def duckFlyAway():
        if duck.life:
            score.pickUp()
            duck.flyAway()

    pygame.mouse.set_visible(False)
    bullets = NUM_BULLETS
    score = 0
    ducks = pygame.sprite.Group()
    duck = Duck(-40, -40, 40, 40)
    aim = Aim(-40, -40)
    score = Score()
    hDogs = pygame.sprite.Group()
    hDog = HappyDog(270, 400, 100, 100)

    hDogs.add(hDog)
    ducks.add(duck)

    all.add(ducks)
    all.add(hDogs)
    all.add(aim)
    all.add(score)
    running = True

    clock = pygame.time.Clock(
    )  # clock allows to do delay for repaint of screen

    surfaceDisplay.fill(COLOR_OF_SKY)  # this surface is main field for paint
    surfaceDisplay.blit(bg, START_OF_DISPLAY)
    screen.blit(surfaceDisplay,
                START_OF_DISPLAY)  # show surfaceDisplay on the screen

    timerFlyingDuck = threading.Timer(duckFlightTime, duckFlyAway).start(
    )  # Designing timer for duck. When it ticks then the duck flies away

    while running:

        # Checking the completion of the animation of a happy dog to create a
        # new duck or checking that the duck is alive, but she flew away
        if (hDog.endAnimation) or (duck.life and not duck.alive()):
            # DELAY
            # Set new random place for duck
            # Adding duck to groups sprite ducks
            # adding this group to all group
            # restart timer
            time.sleep(DELAY_DUCK_APPEARANCE)

            duck.setPlace(random.randrange(-100, 500),
                          random.randrange(-40, 200))

            ducks.add(duck)
            all.add(ducks)

            bullets = NUM_BULLETS

            timerFlyingDuck = threading.Timer(duckFlightTime, duckFlyAway)
            timerFlyingDuck.start()

        # Checking life of duck and checking launch of happy dog
        # if there is no duck in any group and
        # the duck is dead
        # and the happy dog is not running
        # then run the happy dog
        if not duck.alive() and not hDog.run and not duck.life:
            runHappyDog()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.MOUSEMOTION:
                aim.updatePosition(event.pos)
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:  # Left button of mouse
                    if bullets > 0:
                        bullets -= 1
                        shoot.play()  # Trigger shot sound
                        gotin = duck.checkClick(
                            event.pos
                        )  # Check whether the user got into the duck
                        if gotin:
                            score.changeScore(bullets)

        # if numbers of bullets equals null and duck is alive
        # then duck flies away and timer will be killed
        if (bullets == 0 and duck.life):
            duckFlyAway()
            try:
                timerFlyingDuck.cancel()
            except Exception:
                print("Timer slomalsya")

        # Repainting sprites
        all.clear(screen, surfaceDisplay)
        all.update()
        dirty = all.draw(screen)

        # Updating screen for user
        screen.blit(bg, START_OF_DISPLAY)
        pygame.display.update(dirty)

        # Delay loop
        clock.tick(35)

    if not running:
        quit()
Ejemplo n.º 30
0
 def __init__(self):
     self.score = Score()
     self.team1_players = []
     self.team2_players = []