Beispiel #1
0
    def __init__(self):
        blocks.Stage.__init__(self, 40)

        tree_ground = blocks.Tile(blocks.Color('lawngreen').darken(0.8), flat=True)
        self.images = [
            blocks.Block(blocks.Color('lawngreen')),
            blocks.Block(blocks.Color('firebrick')),
            blocks.Tile(blocks.Color('lawngreen')),
            blocks.Tile(blocks.Color('lawngreen'), flat=True),
            blocks.Brick(blocks.Color('gray40'), blocks.Color('firebrick'), flat=True),
            blocks.Brick(blocks.Color('gray40'), blocks.Color('firebrick')),
            blocks.Crate(blocks.Color('burlywood3')),
            blocks.IceBlock(blocks.Color('cyan2')),
            blocks.Tree(blocks.Color('forestgreen'), blocks.Color('brown'), tree_ground),
            blocks.IceBlock(blocks.Color('skyblue')),
        ]

        #self.map_area(range(10, 12), range(16, 24), (0, 2))
        self.map_area(range(12, 14), range(16, 24), (0, 4))
        self.map_range_row(range(11, 14), 11, (0, 2))
        self.map_range_row(range(16, 19), 11, (0, 7))
        self.map_range_row(range(16, 24), 14, (0, 3))
        self.map_range_row(range(18, 24), 16, (0, 5))
        self.map_range_row(range(18, 22), 17, (0, 6))
        self.map_range_col(range(7, 12), 23, (0, 0))
        self.map_range_col(range(14, 16), 12, (0, 9))
        self.map_add(14, 17, ((0, 8),))
        self.map_add(14, 22, ((0, 8),))
        # HI
        self.map_stack_range(range(5), 9, 23, 0)
        self.map_stack_range(range(5), 9, 20, 0)
        self.map_range_row(range(21, 23), 9, (2, 0))
        self.map_stack_range(range(5), 9, 17, 1)
        self.map_stack_range((0, 4), 9, 16, 1)
        self.map_stack_range((0, 4), 9, 18, 1)
def main():
    blocks1 = initialize_blocks.initialize_blocks()

    print(
        simulations.simulation([
            blocks.Block(
                attack_number=2, attack_letter='A', initial_attack_strength=4)
        ], [
            blocks.Block(
                attack_number=2, attack_letter='A', initial_attack_strength=4)
        ], 1000))
Beispiel #3
0
def spawnBlock():
    global block, nextBlock

    if nextBlock is None:
        nextBlock = blocks.Block(blocks.randomBlock())
        nextBlock.image = blockImage

    block = nextBlock
    block.location = (int((playfield.width / 2) - (block.size / 2)), 0)

    nextBlock = blocks.Block(blocks.randomBlock())
    nextBlock.image = blockImage
Beispiel #4
0
    def transposeBlock(self):
        """
		top-left is the center of rotation
		"""
        transposeBlock = blocks.Block(self.activeBlock.getTranspose())
        if not self.isThereCollision(transposeBlock, self.blockPosition):
            self.activeBlock = transposeBlock
Beispiel #5
0
def applytx(blockdata, txdata, debug=0):
    block = blocks.Block(blockdata.decode('hex'))
    tx = transactions.Transaction.parse(txdata.decode('hex'))
    if debug:
        processblock.debug = 1
    o = processblock.apply_tx(block, tx)
    return block.serialize().encode('hex'), ''.join(o).encode('hex')
Beispiel #6
0
 def load_map(self):
     self.map_blocks = level_map.get_level_map(self.level)
     for element in self.map_blocks:
         color, xpos, ypos = element
         image = self.block_dict[color]
         obj_ = blocks.Block(self.surface, image, (xpos, ypos), color)
         self.on_screen_blocks.append(obj_)
Beispiel #7
0
def translate(file_, indent_size=4):
    """
    The function for actually translating the code.
    code:
        List containing lines of code.
    """
    # Setup
    with open(file_, "r") as f:
        text = f.read()
        nodes = ast.parse(text).body
        code = text.splitlines()
    blocks.Block.indent = indent_size
    top = blocks.Block(should_indent=False)

    # Run filtering process
    code = filter(should_keep_line, code)

    # Include includes
    top.append_blocks(includes_from_code(code))

    # Add main function
    main_func = main_function()
    top.append_block(main_func)

    nodes = filter_body_nodes(nodes)
    for node in nodes:
        evaluate_node(node, main_func)

    return str(top)
Beispiel #8
0
    def init(self):
        if self.next_block == None:

            block_color = blocks.colors[randint(0, len(blocks.colors) - 1)]
            block_type = randint(0, len(blocks.types) - 1)
            start_col = randint(2, number_columns - 2)
            self.next_block = blocks.Block(block_color, start_col, 0,
                                           block_type)

        self.block = self.next_block
        block_color = blocks.colors[randint(0, len(blocks.colors) - 1)]
        block_type = randint(0, len(blocks.types) - 1)
        start_col = randint(2, number_columns - 2)
        self.next_block = blocks.Block(block_color, start_col, 0, block_type)

        if self.check_stop_moving(self.block):
            self.end = True
Beispiel #9
0
    def update(self):
        self.objects.update()
        self.objects.draw(self.image)
        #once quarter across screen shift screen
        if self.hero.rect.x > round(
                self.rect.width / 4) and self.worldShift < self.maxShift:
            self.shift(round(self.rect.width / 4) -
                       self.hero.rect.x)  #make the shift negative
        #fighting
        for foe in self.enemies:
            if (foe.rect.x -
                    self.hero.rect.right) < 15 and not self.hero.fighting:
                foe.fighting = True
                self.target = foe
                self.hero.target = foe
                self.hero.fighting = True
                #make hero image first of the walk image
                self.hero.image.fill(constants.BLACK)
                self.hero.image.blit(self.hero.spriteSheet, (0, 0),
                                     (12, 712, 44, 58))
                self.hero.width = 12

        if self.target != None:
            if self.target.stats["HP"] <= 0 and not self.hero.dead:
                #reset hero for next fight
                self.hero.fighting = False
                self.hero.dir = 1
                self.hero.sinPos = 0
                self.hero.rect.y = self.hero.basey
                #give the hero the treasure for the victory
                for i in range(self.target.stats["Treasure"]):
                    blockType = random.choice(constants.blockList)
                    newBlock = blocks.Block(self.hold, blockType)
                    self.hold.add(newBlock)
                #remove the enemy from the groups
                self.enemies.remove(self.target)
                self.target.kill()
                self.target.noise.play()
                self.target = None
                if constants.multi:
                    self.hero.changex = 0

        #give hero a penalty for holding too much
        if len(self.hold.blockList) > 3 * (self.penalty + 1):
            self.penalty += 1
            for i in self.hero.stats:
                if i != 'MAX_HP':
                    self.hero.stats[i] -= 1
        elif len(self.hold.blockList) < 3 * self.penalty:
            self.penalty -= 1
            for i in self.hero.stats:
                if i != 'MAX_HP':
                    self.hero.stats[i] += 1

        #make health bar percentage of max health
        self.healthBar.width = round(
            100 * (self.hero.currentHP / self.hero.stats['MAX_HP']))
        pygame.draw.rect(self.image, constants.RED, self.healthBar)
Beispiel #10
0
    def __init__(self, player):
        """create level"""
        Level.__init__(self, player)

        self.level_limit = -1570
        self.spawn1 = -2000
        self.spawn2 = 2000

        self.background = pygame.image.load(
            "Resources/Backgrounds/background_forest_6.png").convert()
        self.background.set_colorkey(constants.RED)
        #draw background
        #self.background = pygame.surface.Surface((constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT)).convert()
        #self.background.fill(constants.BG_COLOUR)

        # Array with width, height, x, and y of blocks
        # level = [ [blocks.GRASS_LEFT, 500, 500],
        #           [blocks.GRASS_MIDDLE, 0, 300],
        #           [blocks.GRASS_MIDDLE, 570, 500],
        #           [blocks.GRASS_RIGHT, 640, 500],
        #           [blocks.GRASS_LEFT, 800, 400],
        #           [blocks.GRASS_MIDDLE, 870, 400],
        #           [blocks.GRASS_RIGHT, 940, 400],
        #           [blocks.GRASS_LEFT, 1000, 500],
        #           [blocks.GRASS_MIDDLE, 1070, 500],
        #           [blocks.GRASS_RIGHT, 1140, 500],
        #           [blocks.STONE_PLATFORM_LEFT, 1120, 280],
        #           [blocks.STONE_PLATFORM_MIDDLE, 1190, 280],
        #           [blocks.STONE_PLATFORM_RIGHT, 1260, 280],
        #           ]
        level = self.generate_random_level(3500)

        ### Go through the array above and add blocks:
        ### TO DO: REDO THIS FOR MISC ITEMS (TREES ETC)

        for _block in level:
            # If block is a spawnblock
            if _block[0] == blocks.SPAWN_BLOCK:
                # add spawn block
                block = blocks.PickupSpawnerBlock()
                self.pickup_spawn_loc = _block[1]
                self.block_list.add(block)

            elif _block[0] == blocks.FLAG:
                # Add flag
                block = blocks.Flag()
                self.entity_list.add(block)
            elif _block[0] == blocks.BUSH_1:
                block = blocks.Bush()
                self.entity_list.add(block)
            else:
                block = blocks.Block(_block[0])
                self.block_list.add(block)

            block.rect.x = _block[1]
            block.rect.y = _block[2]
Beispiel #11
0
def demo_blocks(g):
    ss = config.sprite_size
    ps = config.play_size
    num_blocks_x = (ps.w - 2 * ss) / ss
    for y in range(0, 3):
        y_coord = ss * (y + 1)
        for x in range(0, num_blocks_x):
            x_coord = (1 + x) * ss + ps.x
            b = blocks.Block((x_coord, y_coord), y % 6)
            g.add(b)
Beispiel #12
0
def parse(exprs):
    '''
    Convert a series of expressions to a syntax tree. This also
    creates a "root" block which encompasses all parent expressions,
    to ensure that the syntax tree is rooted at a single node.
    '''

    root = blocks.Block(None, make_blocks(exprs), 'root')
    for imp in imports.get_imports():
        root.children.insert(0, 'import %s;' % imp)
    return root
Beispiel #13
0
def translate_empty_blocks(block):
    '''
    Recursively translate the "block none;" construct.
    '''

    for i, expr in enumerate(block.children):
        if not isinstance(expr, blocks.Block):
            if expr.endswith(' none'):
                block.children[i] = blocks.Block(expr[:-5], [])
        else:
            translate_empty_blocks(expr)
Beispiel #14
0
def karta_load(gr, gs):
    print('типо загружаем карту')
    qwerty = open("save_karta.json", 'r')
    uiopas = json.load(qwerty)
    print(uiopas)
    for sapoiu in uiopas:
        print(sapoiu)
        sdx = blocks.Block(sapoiu['x'], sapoiu['y'], sapoiu['tip'])
        gs.add(sdx)
        gr.add(sdx)

    qwerty.close()
Beispiel #15
0
def randomly_fill_row(grid, row_index, col_start):
  if col_start >= grid.width:
    raise StopIteration
  for col in xrange(col_start, grid.width + 1):
    for length in xrange(1, grid.width - col + 1):
      block = blocks.Block(col, length)
      grid_clone = grid.clone()
      grid_clone.maybe_add_block(block, row_index)
      for filled_grid in randomly_fill_row(grid_clone,
                                           row_index,
                                           block.start + block.length + 1):
        yield filled_grid
      else:
        yield grid_clone
Beispiel #16
0
def build_castles(width, height):
  grid = grids.Grid(width, height)
  grid.maybe_add_block(blocks.Block(0, width), 0)
  candidates = set([grid])
  for row_index in xrange(1, height):
    new_candidates = set()
    for grid in candidates:
      for filled_grid in randomly_fill_row(grid, row_index, 0):
        new_candidates.add(filled_grid)
    candidates = new_candidates
  castles = set()
  for candidate in candidates:
    if candidate.is_castle() is True:
      castles.add(candidate)
  return castles
Beispiel #17
0
def make_blocks(exprs):
    '''
    Convert a list of expressions into a syntax tree. Called
    recursively to generate a full tree.
    '''

    block_list = []
    i = 0

    while i < len(exprs):
        expr = exprs[i]
        if is_open_block(expr):
            try:
                inner_blocks = 1
                j = i

                # Find the corresponding close-block
                while inner_blocks > 0:
                    j += 1
                    if is_close_block(exprs[j]):
                        inner_blocks -= 1
                    elif is_open_block(exprs[j]):
                        inner_blocks += 1

                # Create a new block, recursively call make_blocks
                # on the statements between the open and close block,
                # and set the new block's children to the result.
                block_list.append(
                    blocks.Block(block_id(expr), make_blocks(exprs[i + 1:j])))

                # Move the stack pointer forward to represent all of
                # the statements that were just added to the new
                # block's children.
                i = j
            except IndexError:
                print('Exception encountered while parsing %s' % expr)
                raise SyntaxException(
                    'Not enough close block statements. ' +
                    'You\'re probably missing a close-brace ' +
                    'or a semicolon.')

        # If it's not an open block statement, just add it to the
        # sequence of expressions we've found thus far.
        elif expr:
            block_list.append(expr)
        i += 1

    return block_list
Beispiel #18
0
def makeBlock(info,inventory,source):
    '''compile the info from the blockOrder into a block
    and change the image with the source'''
    blockType = constants.blockList[(info[0]-1)] #list start at 0 so decrease value by 1
    base = blocks.Block(inventory,blockType)
    inventory.add(base)
    base.selected = False#unselect so it can fall
    for i in range(info[1]): #rotate to correct direction
        base.rotate('clock')
    #repositon block to position in info
    size = constants.blockSize

    base.moveOverride(-base.rect.x,-base.rect.y)#move block back to 0,0
    base.moveOverride(size*(info[-1][0]+1),size*info[-1][1])
   
        
    for rect in base.rects:
        #get a position to blit onto the block image
        posRect = rect.move(-base.rect.x,-base.rect.y)
        base.image.blit(source,posRect,rect)
    base.moveOverride(0,-base.rect.y - 30)#move above top of inventory
    return base #return the block
Beispiel #19
0
def main():
    #初期化処理
    pygame.init()
    pygame.display.set_caption("Tetris")  #タイトルを設定
    fall_cnt = 0  #落下カウント
    gr_cnt = 0  #接地秒数カウント
    score = 0
    new_block = True  #新ブロック生成フラグ
    while True:
        #ブロック生成
        if new_block:
            activeBlock = blocks.Block(BLOCK_INIT_X, BLOCK_INIT_Y,
                                       random.randrange(7))
            activeBlock.draw()
            GAMEOVER = activeBlock.checkGameover(MAP)
            new_block = False
        #ゲームオーバー処理
        if GAMEOVER:
            gamescreen.drawLine()
            font = pygame.font.SysFont(None, 40)
            text = font.render("GAMEOVER", False, (255, 0, 0))
            SCREEN.blit(text, (10, 50))
            pygame.display.update()
            new_block = False
        else:
            #ブロックの移動処理
            if fall_cnt == 2:
                score += 1
                if activeBlock.fall(MAP):
                    gr_cnt += 1
                fall_cnt = 0
            fall_cnt += 1
            if pygame.key.get_pressed()[K_LEFT]:
                activeBlock.move((-1) * BLOCK_SPEED_X, MAP)
            if pygame.key.get_pressed()[K_RIGHT]:
                activeBlock.move(BLOCK_SPEED_X, MAP)
            if pygame.key.get_pressed()[K_SPACE]:
                activeBlock.rotate(MAP)
            if pygame.key.get_pressed()[K_DOWN]:
                fall_cnt = 2
            #ブロック設置判定
            if gr_cnt == 3:
                new_block = True
                MAP.embed(activeBlock)
                gr_cnt = 0

            #消失判定
            MAP.align(score)
            #描画関連
            SCREEN.fill((255, 255, 255))
            MAP.draw()
            activeBlock.draw()
            gamescreen.drawLine()
            gamescreen.drawScore(SCREEN, score)
            pygame.display.update()
            time.sleep(0.1)
        #pygameのイベント処理
        for event in pygame.event.get():
            if event.type == QUIT:  # 閉じるボタンが押されたら終了
                pygame.quit()  # Pygameの終了(画面閉じられる)
                sys.exit()
def initialize_blocks():
    '''
	Initialized all blocks into one list
	Returns:  List of all blocks in the game, with no alliegance
	'''
    block_list = []
    block_stats = read_file('block_stats.txt')

    # Read in information about each block
    for line_num, line in enumerate(block_stats):

        #Convert to ints, bools, and tuples
        for index, info in enumerate(line):

            #Ints
            if info.isdigit():
                block_stats[line_num][index] = int(info)

            #Booleans
            elif info == 'T':
                block_stats[line_num][index] = True

            elif info == 'F':
                block_stats[line_num][index] = False

            #Tuples
            elif info[0] == '(':  #For Bruce and Comyn
                temp = info
                temp = temp.strip('()').split(',')
                for i, element in enumerate(
                        temp):  #Should be tuple of integers
                    temp[i] = int(element)
                block_stats[line_num][index] = tuple(temp)

        #store information from line
        name = line[0]
        movement_points = line[1]
        attack_letter = line[2]
        attack_number = line[3]
        attack_strength = line[4]
        block_type = line[5]
        cross = line[6]
        block_id = line[7]
        #print(line[0], line[7])
        # Check if it's a noble
        if block_type == 'BRUCE' or block_type == 'COMYN':
            is_noble = True

            # Set up noble homes
            home = line[8]

            # Assign noble loyalty
            loyalty = block_type
            #print(block_id)
            temp_block = blocks.Noble(name, movement_points, attack_letter,
                                      attack_number, attack_strength, cross,
                                      block_id, home, loyalty)
            #print(temp_block.name, temp_block.blockID, temp_block.allegiance)
        else:
            is_noble = False
            temp_block = blocks.Block(name, movement_points, attack_letter,
                                      attack_number, attack_strength, cross,
                                      block_type, block_id)

        #Finished block - no alliegence yet
        block_list.append(temp_block)

    return block_list
Beispiel #21
0
def main():
    loadLevel()
    pygame.init() # Инициация PyGame, обязательная строчка 
    window = pygame.display.set_mode(DISPLAY) # Создаем окошко
    pygame.display.set_caption("Simulator") # Пишем в шапку
    screen = Surface((WIN_WIDTH,WIN_HEIGHT)) # Создание видимой поверхности. будем использовать как фон
    screen.fill(Color(BACKGROUND_COLOR))     # Заливаем поверхность сплошным цветом. 
    #Вместо BACKGROUND_COLOR могу сделать ((0, 255, 0))

    #Создание окна информации
    #info_string = Surface((INFO_STRING_WIDTH, INFO_STRING_HEIGHT))  # Создание видимой поверхности для строки инф
    #info_string.fill(Color(INFO_STRING_COLOR))
    #info_string.set_colorkey(Color(INFO_STRING_COLOR))

    #Шрифты
    font.init()
    score_font = font.SysFont('Comic Sans MS', 50, False, True)
    # score_font = font.Font(None,32)

    hero = player.Player(playerX,playerY) # создаем героя по (x,y) координатам
    left = right = False # по умолчанию - стоим
    up = down = False

    entities.add(hero)
    timer = pygame.time.Clock()
    numEpisod(hero) # Определяю номер эпизода (это для удобства вывода)

    total_level_width  = len(level[0])*blocks.PLATFORM_WIDTH # Высчитываем фактическую ширину уровня
    total_level_height = len(level)*blocks.PLATFORM_HEIGHT   # Высчитываем фактическую высоту уровня
    print ("Размер уровня:   Ширина: " + str(total_level_width) + "   Высота: " + str(total_level_height))
    camera = Camera(camera_configure, total_level_width, total_level_height)
    blocks.levelSize(total_level_width, total_level_height)  # Определение размера уровня для метода teleporting класса BigEnergy

    way = [[0] * len(level[0]) for i in range(len(level))] # Создаем карту уровня для алгоритма
    monWay = [[0] * len(level[0]) for i in range(len(level))]  # Создаем карту уровня для алгоритма


    way[int(hero.startY / 32)][int(hero.startX / 32)] = 'H' # Добавляем расположение героя на карту (в массив)
    hero.myPosX = int(hero.startX / 32)
    hero.myPosY = int(hero.startY / 32)

    amountBigEnergy = 0 # Общее кол-во Больших энергий на карте

    x=y=0 # координаты
    for row in level: # вся строка
        for col in row: # каждый символ
            if col == "-":
                pf = blocks.Block(x,y)
                entities.add(pf)
                platforms.append(pf)
                way[int(y/32)][int(x/32)] = 'B' #Если есть данный блок, то заполняем массив B
                monWay[int(y / 32)][int(x / 32)] = 'B'  # Если есть данный блок, то заполняем массив B для монстра
            if col == "*":
                bd = Bomb(x, y, 0, 0, 444, 0) #(x, y, 0, 0, 444, 0)
                entities.add(bd)
                platforms.append(bd)
                monsters.add(bd)
                # Добавляем монстра в массив
                masMons.append(bd)
                way[int(y/32)][int(x/32)] = 'M' #Если есть данный блок, то заполняем массив B
                monWay[int(y / 32)][int(x / 32)] = 'M'  # Если есть данный блок, то заполняем массив B для монстра
            if col == "@":
                bh = blocks.BlackHole(x,y)
                entities.add(bh)
                platforms.append(bh)
                animatedEntities.add(bh)
                masBlHole.append(bh)
                #way[int(y/32)][int(x/32)] = '@' #'@' #Если есть данный блок, то заполняем массив @
                monWay[int(y / 32)][int(x / 32)] = '@'  # '@' #Если есть данный блок, то заполняем массив @
                blocks.BlackHole.myCoord(bh)
            if col == "E":
                be = blocks.BigEnergy(x,y)
                entities.add(be)
                platforms.append(be)
                animatedEntities.add(be)
                way[int(y / 32)][int(x / 32)] = 'E' #Если есть данный блок, то заполняем массив E
                masBE.append(be)
                blocks.BigEnergy.myCoord(be)
                amountBigEnergy += 1 # Запоминаем кол-во энергий на карте
            if col == "W":
                ex = blocks.Exit(x,y)
                entities.add(ex)
                platforms.append(ex)
                animatedEntities.add(ex)
                way[int(y / 32)][int(x / 32)] = 'W' # Если есть данный блок, то заполняем массив W
                monWay[int(y / 32)][int(x / 32)] = 'W'  # Если есть данный блок, то заполняем массив W для монстра
                blocks.Exit.myPosX = int(x/32)
                blocks.Exit.myPosY = int(y/32)

            x += blocks.PLATFORM_WIDTH #блоки платформы ставятся на ширине блоков
        y += blocks.PLATFORM_HEIGHT    #то же самое и с высотой
        x = 0                   #на каждой новой строчке начинаем с нуля

    index = 0
    bomb = 0
    for mn in masMons:
        Monster.myCoord(mn)
        mn.index = index
        #print(mn.index)
        mn.moveTime = mn.startMoveTime
        way[mn.myPosY][mn.myPosX] = 'M'  # Если есть данный блок, то заполняем массив M
        monWay[mn.myPosY][mn.myPosX] = 'M'  # Если есть данный блок, то заполняем массив M для монстра
        index += 1
        if mn.algorithm == 444:
            bomb += 1
        elif mn.algorithm == 333:
            mn.myTargetPosX = mn.myPosX
            mn.myTargetPosY = mn.myPosY

    #bigEnergyCounter = maps.amountBigEnerge(way)
    if not PLAY:
        if (amountBigEnergy == 0):
            alg.algWaveFindExit('W', hero, way, 0, monWay, masBlHole)
        else:
            alg.algWaveFindExit('E', hero, way, masBE, monWay, masBlHole)
    elif PLAY:
        maps.printInfo(hero, way) # Выводим карту уровня, если управляет игрок

    #Для идентификации монстров
    #print('')
    #amountMonster = maps.amountMonster(way) #Подсчитываем кол-во монстров на карте
    #monParam = 5 # Имя X Y Alg moveTime #Кол-во параметров массива для каждого монстра
    #hero.monInfo = [[0] * monParam for i in range(amountMonster)] # Создается массив по кол-ву монстров

    # hero.monInfo[0][1][]
    

    #hero.monArray1 = np.array(['Number', 'Name', 'x', 'y', 'Alg', 'moveTime'])

    for mn in masMons:
        hero.monInfo.append(observations.ObservedMonster(-999999, -999999, observations=[observations.Observation(timestamp=-1, x=int(mn.startX/32), y=int(mn.startY/32))]))
        observations.addObservation(hero.monInfo, observations.Observation(timestamp=0, x=int(mn.startX/32), y=int(mn.startY/32)), index=mn.index)
        #print('Name: ' + str(mn.name) + '  Alg: ' + str(mn.algorithm) + '  moveTime: ' + str(mn.moveTime))

    #    hero.monArray1 = np.append(hero.monArray1, [mn, 'Name', 'x', 'y', 'Alg', 'moveTime'])
    #    print('Array: \n' + str(hero.monArray1))
    #1 monstr, 1 zahod, 3 elem

    #maps.printHeroInfo(hero.monInfo) # Вывод информации о массиве
    #print('')

    hero.moveTime = hero.startMoveTime  # Необходима для плавного движения персонажа т.к. его скорость 8 пикселей, а не 32, как расчитана карта(массив)
    # определение времени
    #todayTime = datetime.datetime.today()   #date = todayTime.strftime("%d-%m-%y")   #time = todayTime.strftime("%H-%M-%S")
    slowSpeed = 0  # Переменная для искуственного замедления симулятора
    if PLAY: wait = 0 # Переменная для искуственного замедления симулятора
    else: wait = 4 # Переменная для искуственного замедления симулятора
    stayHide = 0 # Переменная отвечающая за кол-во шагов (moveTime), которое агент просидит в укрытии после того как опасность уйдет

    DELAY = STARTDELAY
    startTime = datetime.datetime.now()
    while True: # Основной цикл программы  #not hero.winner:
        timer.tick(DELAY)
        #slowSpeed -= 1
        if hero.live <= 0 or hero.winner:
            if hero.live <= 0:
                print('Поражение!\n')
            elif hero.winner:
                print('Победа!\n')
            # Подсчитываем время
            if hero.live < 0: hero.live = 0  # Почему-то по итогу эпизода иногда отрицательная жизнь.
            finishTime = datetime.datetime.now() # Время конца цикла
            workTime = finishTime - startTime    # Вычисление времени работы цикла
            #print (workTime) # если написать workTime.seconds то выведется время в секундах
            saveResult(hero, workTime, masMons)
            if (REPEAT == True):
                print('Новый эпизод!')
                #Отрисовываем блоки еще раз
                x = y = 0  # координаты
                for row in level:  # вся строка
                    for col in row:  # каждый символ
                        if col == "-":
                            way[int(y / 32)][int(x / 32)] = 'B'  # Если есть данный блок, то заполняем массив B
                            monWay[int(y / 32)][int(x / 32)] = 'B'  # Если есть данный блок, то заполняем массив B для монстра
                        x += blocks.PLATFORM_WIDTH  # блоки платформы ставятся на ширине блоков
                    y += blocks.PLATFORM_HEIGHT  # то же самое и с высотой
                    x = 0  # на каждой новой строчке начинаем с нуля
                hero.winner = False # Возвращаем стартовое значение поля победы
                hero.imDie = False
                hero.live = 2       # Возвращаем стартовое значение жизней
                hero.score = 0      # Возвращаем стартовое значение очков
                hero.amMove = 0     # Выставляем количство шагов на 0
                maps.clearMap(way)  # Очищаем карту от предыдущих путей, энергий, монстров, героя
                maps.clearMonsterMap(monWay)  # Очищаем карту от предыдущих путей, энергий, монстров, героя
                #maps.clearHeroFromMap(way)
                hero.moveTime = hero.startMoveTime
                way[hero.myPosY][hero.myPosX] = 'H'
                if hero.episod % amEpisod == 0: #Для изменения алгоритмов монстров
                    hero.monInfo = [] #append(observations.ObservedMonster(-999999, -999999, observations=[observations.Observation(timestamp=-1, x=int(mn.startX / 32), y=int(mn.startY / 32))]))
                    hero.obsCount = 0
                    hero.indexForThisMon = []
                    hero.myLastPosXforMonTop = -1
                    hero.myLastPosYforMonTop = -1
                    hero.oCforLastMonTop = -1
                    hero.myLastPosXforMonBot = -1
                    hero.myLastPosYforMonBot = -1
                    hero.oCforLastMonBot = -1
                    hero.myLastPosXforMonRight = -1
                    hero.myLastPosYforMonRight = -1
                    hero.oCforLastMonRight = -1
                    hero.myLastPosXforMonLeft = -1
                    hero.myLastPosYforMonLeft = -1
                    hero.oCforLastMonLeft = -1
                    hero.finalAlgCheck111 = []
                    hero.finalAlgCheck222 = []
                    hero.finalAlgCheck333 = []
                    #hero.known = -1
                for mn in masMons:  # Возвращаем монстров на свою позицию
                    Monster.teleporting(mn, mn.startX, mn.startY, platforms, hero, way)
                    Monster.myCoord(mn)
                    mn.moveTime = mn.startMoveTime
                    way[int(mn.rect.y / 32)][int(mn.rect.x / 32)] = 'M'
                    monWay[int(mn.rect.y / 32)][int(mn.rect.x / 32)] = 'M'
                    if hero.episod % amEpisod == 0:
                        hero.monInfo.append(observations.ObservedMonster(-999999, -999999, observations=[observations.Observation(timestamp=-1, x=int(mn.startX / 32), y=int(mn.startY / 32))]))
                        observations.addObservation(hero.monInfo,observations.Observation(timestamp=0, x=int(mn.startX / 32),y=int(mn.startY / 32)), index=mn.index)
                        if mn.name != 'Bomb':
                            numberAlg = random.randint(1, 3)
                            numberMT = random.randint(2, 4)
                            #print ('number: ' + str(numberAlg))
                            if numberAlg == 1:
                                mn.algorithm = 111
                                mn.startMoveTime = numberMT
                                mn.moveOnLeft = mn.moveOnRight = mn.moveOnUp = mn.moveOnDown = False
                                numberLRUD = random.randint(1, 4)
                                if numberLRUD == 1: mn.moveOnLeft = True
                                if numberLRUD == 2: mn.moveOnRight = True
                                if numberLRUD == 3: mn.moveOnUp = True
                                if numberLRUD == 4: mn.moveOnDown = True
                            elif numberAlg == 2:
                                mn.algorithm = 222
                                mn.startMoveTime = numberMT
                            elif numberAlg == 3:
                                mn.algorithm = 333
                                mn.startMoveTime = numberMT
                            print('Name: ' + str(mn.name) + '  Alg: ' + str(mn.algorithm) + '  moveTime: ' + str(mn.moveTime))
                    if mn.algorithm == 333:
                        mn.myTargetPosX = mn.myPosX
                        mn.myTargetPosY = mn.myPosY
                    #mn.myPosX = int(mn.rect.x / 32)
                    #mn.myPosY = int(mn.rect.y / 32)
                    #mn.myPrevPosX = -1
                    #mn.myPrevPosY = -1
                    print('x:   ' + str(mn.rect.x / 32))
                    print('y:   ' + str(mn.rect.y / 32))
                    #Monster.algMove(mn, hero, way)
                for be in masBE: # Распределяем энергии по карте
                    blocks.BigEnergy.teleporting(be, 32 * random.randint(6, 6), 224, platforms, True, way)
                    while (hero.rect.x == be.rect.x and hero.rect.y == be.rect.y) or (ex.rect.x == be.rect.x and ex.rect.y == be.rect.y) or (way[int(be.rect.y / 32)][int(be.rect.x / 32)] == 'M'):
                        blocks.BigEnergy.teleporting(be, 32, 32 * random.randint(4, 5), platforms, True, way)
                    blocks.BigEnergy.myCoord(be)
                    way[int(be.rect.y / 32)][int(be.rect.x / 32)] = 'E'
                amountBigEnergy = maps.amountBigEnerge(way)
                #maps.printInfo(hero, way)
                if not PLAY:
                    if (amountBigEnergy == 0):
                        print('Прокладываю путь до W')
                        alg.algWaveFindExit('W', hero, way, 0, monWay, masBlHole) #Прокладываем новый маршрут до конечной точки
                    else:
                        print('Прокладываю путь до E')
                        alg.algWaveFindExit('E', hero, way, masBE, monWay, masBlHole) #[amountBigEnergy-1]) #Прокладываем новый маршрут до конечной точки
                elif PLAY:
                    maps.printInfo(hero, way)
                #maps.printInfo(hero, way)  # Выводим карту на экран
                #maps.clearNumberFromMap(way) #Очищаем карту от всех прочих путей не вошедших в итоговый маршрут
                startTime = datetime.datetime.now()
            else:
                raise SystemExit("QUIT")

        for e in pygame.event.get(): # Обрабатываем события
            if e.type == QUIT or (e.type == KEYUP and e.key == K_ESCAPE):
                print('Соединение разорвано!')
                #Подсчитываем время
                finishTime = datetime.datetime.now() # Время конца цикла
                workTime = finishTime - startTime    # Вычисление времени работы цикла
                saveResult(hero, workTime, masMons)
                raise SystemExit("QUIT")
            if e.type == KEYUP and e.key == K_SPACE:
                print('Пауза!')
                pause = True
                while pause:
                    for e in pygame.event.get():  # Обрабатываем события
                        if e.type == KEYUP and e.key == K_SPACE:
                            pause = False
                            print('Продолжаем!')
                        if e.type == QUIT or (e.type == KEYUP and e.key == K_ESCAPE):
                            raise SystemExit("QUIT")
            if e.type == KEYDOWN and e.key == K_MINUS:
                if DELAY > 2:
                    DELAY = 15
                    wait = 4
                    print('Скорость симулятора понижена!   DELAY = ' + str(DELAY))
                else: print('Отказ! Достигнута минимальная разрешенная скорость!   DELAY = ' + str(DELAY))
            if e.type == KEYDOWN and e.key == K_EQUALS:
                DELAY = 999
                wait = 0
                #DELAY += 50
                print('Скорость симулятора повышена!   DELAY = ' + str(DELAY))
            if e.type == KEYDOWN and e.key == K_BACKSPACE:
                DELAY = STARTDELAY
                print('Скорость симулятора восстановлена!   DELAY = ' + str(DELAY))

            if PLAY:
                if e.type == KEYDOWN and e.key == K_UP:
                    up = True
                if e.type == KEYDOWN and e.key == K_DOWN:
                    down = True
                if e.type == KEYDOWN and e.key == K_LEFT:
                    left = True
                if e.type == KEYDOWN and e.key == K_RIGHT:
                    right = True
                #if e.type == KEYDOWN and e.key == K_LSHIFT:
                #    lS = True
                if e.type == KEYUP and e.key == K_UP:
                    up = False
                if e.type == KEYUP and e.key == K_DOWN:
                    down = False
                if e.type == KEYUP and e.key == K_RIGHT:
                    right = False
                if e.type == KEYUP and e.key == K_LEFT:
                    left = False
                #if e.type == KEYUP and e.key == K_LSHIFT:
                #    lS = False
                maps.clearHeroFromMap(way)
                way[int(hero.rect.y / 32)][int(hero.rect.x / 32)] = 'H'


        if slowSpeed == 0:
            slowSpeed = wait
            #for mn in masMons:  # Возможно будет актуально, как будет карта личных маршрутов монстров. Но moveTime вычитается чуть позже и из-за этого не обновляется маршрут pendingMove
                #if mn.moveTime <= 0:
                #    maps.clearMonsterWayFromMap(monWay)
            maps.clearMonsterWayFromMap(monWay)
            for bh in masBlHole:
                blocks.BlackHole.myCoord(bh)
                #way[bh.myPosY][bh.myPosX] = '@'
                monWay[bh.myPosY][bh.myPosX] = '@'
            for mn in masMons:  # Алгоритм движения монстров
                if mn.moveTime <= 0:
                    # if mn.myPrevPosY == mn.myPosY and mn.myPrevPosX == mn.myPosX:
                    #    way[mn.myPrevPosY][mn.myPrevPosX] = 'M'
                    # else:
                    way[mn.myPosY][mn.myPosX] = '0'  # Показывает текущую позицию (До выбора следующего пути по алгоритму!)
                    monWay[mn.myPosY][mn.myPosX] = '0'
                    # if way[mn.myPrevPosY][mn.myPrevPosX] != 'H':
                    #    way[mn.myPrevPosY][mn.myPrevPosX] = '0'  # Отмечаем на карте, что ушли с предыдущей позиции
                    if mn.algorithm == 111:
                        Monster.patrolMove(mn, way, monWay)
                        #Monster.monsterPatrolWay(mn, monWay)
                    elif mn.algorithm == 222:
                        Monster.randMove(mn, way, monWay)
                        #Monster.monsterRandWay(mn, monWay)
                    elif mn.algorithm == 333:
                        Monster.pendingMove(mn, monWay , way)
                        #Monster.monsterPendingWay(mn, monWay)

                    if hero.monInfo[mn.index].alg == 111:
                        Monster.monsterPatrolWay(mn, monWay)
                    elif hero.monInfo[mn.index].alg == 222:
                        Monster.monsterRandWay(mn, monWay)
                    elif hero.monInfo[mn.index].alg == 333:
                        Monster.monsterPendingWay(mn, monWay)

                else:
                    mn.moveTime -= 1
                    mn.left = mn.right = mn.up = mn.down = False  # Для плавного движения это убирается

                    if mn.algorithm == 333:
                        Monster.checkForPendingMove(mn, monWay, way)

                    if hero.monInfo[mn.index].alg == 111:
                        Monster.monsterPatrolWay(mn, monWay)
                    elif hero.monInfo[mn.index].alg == 222:
                        Monster.monsterRandWay(mn, monWay)
                    elif hero.monInfo[mn.index].alg == 333:
                        Monster.monsterPendingWay(mn, monWay)

                    #if mn.algorithm == 111:
                    #    Monster.monsterPatrolWay(mn, monWay)
                    #elif mn.algorithm == 222:
                    #    Monster.monsterRandWay(mn, monWay)
                    #elif mn.algorithm == 333:
                    #    Monster.checkForPendingMove(mn, monWay, way)
                    #    Monster.monsterPendingWay(mn, monWay)

                    # way[mn.myPrevPosY][mn.myPrevPosX] = 'M' #На карте видна лишь предыдущая позиция! Куда двигается монстр - не видно!

            for mn in masMons:
                way[mn.myPosY][mn.myPosX] = 'M'  # На карте видна лишь предыдущая позиция! Куда двигается монстр - не видно!
                monWay[mn.myPosY][mn.myPosX] = 'M'  # На карте видна лишь предыдущая позиция! Куда двигается монстр - не видно!
                #print(str(mn.name) + ' MOVETIME: ' + str(mn.moveTime))
                #if mn.moveTime == mn.startMoveTime:
                #maps.printMonsterInfo(monWay)



            if not PLAY:
                alg.identificationAlg(hero, way, masMons, monWay)
                #knownCount = 0
                how333 = 0
                for mn in masMons:
                    if hero.monInfo[mn.index].alg == 333:
                        how333 += 1
                #print('Монстров осталось изучить: ' + str(knownCount) + ' | Episod: ' + str(hero.episod))
                if hero.lastLeft == hero.lastRight == hero.lastUp == hero.lastDown == False:
                    hero.checkMoveTime += 1   #print(colored(str(hero.checkMoveTime), 'cyan'))
                    if hero.checkMoveTime > hero.startMoveTime:
                        hero.moveTime = 0
                else: hero.checkMoveTime = 0
                run = True
                hide = False
                if hero.known == -1: dangerous = False
                else: dangerous = alg.radar(hero, way, masMons, monWay)
                #maps.printInfo(hero, way)
                if hero.moveTime <= 0 or (hero.imDie == True and hero.live > 0):
                    #if amountBigEnergy >= 0:  # Если энергии, которые присутствовали на карте ещё не собраны
                        #way[ex.myPosY][ex.myPosX] = 'W'  # Если есть данный блок, то заполняем массив W
                        #monWay[ex.myPosY][ex.myPosX] = 'W'  # Если есть данный блок, то заполняем массив W для монстра
                        bigEnergyCounter = maps.amountBigEnerge(way)  # тогда сверяем их с текущим количеством на карте
                        amountBigEnergy = 0
                    #if ((bigEnergyCounter != amountBigEnergy and amountBigEnergy >= 0) or hero.imDie == True): #or (bigEnergyCounter == 0): #если кол-во на карте и общее различается, то прокладываем маршрут до следующей цели
                        if hero.imDie == True:
                            hero.imDie = False
                            maps.clearHeroFromMap(way)
                            hero.moveTime = hero.startMoveTime
                            way[hero.myPosY][hero.myPosX] = 'H'
                        #if bigEnergyCounter != amountBigEnergy and amountBigEnergy >= 0:
                            #amountBigEnergy = maps.amountBigEnerge(way)
                        for be in masBE:
                            blocks.BigEnergy.myCoord(be)
                            if be.myPosY > 0 and be.myPosX > 0 and way[be.myPosY][be.myPosX] != 'M':
                                amountBigEnergy += 1
                                way[be.myPosY][be.myPosX] = 'E'
                        if bigEnergyCounter != amountBigEnergy: #Если кол-во энергий на карте != кол-ву энергий фактически, то стираем их и отрисовываем снова
                            maps.deleteBigEnerge(way)
                            print('BigEnergyCounter: ' + str(bigEnergyCounter) + '  |  AmountBigEnergy: ' + str(amountBigEnergy))
                            for be in masBE:
                                blocks.BigEnergy.myCoord(be)
                                if be.myPosY > 0 and be.myPosX > 0 and way[be.myPosY][be.myPosX] != 'M':
                                    way[be.myPosY][be.myPosX] = 'E'
                        maps.clearWayNumFromMap(way) # Очищаем карту, чтобы можно было проложить новый маршрут до другого объекта
                        #amountBigEnergy -= 1  # Уменьшаем общее кол-во энергий
                        #print('Кол-во монстров (без бомб): ' + str(index-bomb) + ' (' + str((index-1-bomb)/2) +') | Алг333: ' + str(how333))
                        if dangerous == True:
                            for bh in masBlHole:
                                if bh.myPosY == hero.myPosY and bh.myPosX == hero.myPosX:
                                    hide = True
                                    stayHide = hero.startMoveTime*3

                        if stayHide <= 0:
                            if dangerous == True and hide == False:
                                symbol = alg.calcWay(hero, way, monWay, '@', 'W')
                                #print('Прокладываю путь до @')
                                if symbol == 'W':
                                    print('Прокладываю путь до W')
                                    alg.algWaveFindExit('W', hero, way, 0, monWay, masBlHole)  # amountBigEnergy-1
                                else:
                                    print('Прокладываю путь до @')
                                    alg.algWaveFindExit('@', hero, way, masBE, monWay, masBlHole)  # [amountBigEnergy-1])
                            elif hide == False:
                                #if (index-1-bomb)/2 > how333:    #Если количество монстров с алгоритмом 333 меньше чем половина монстров, то
                                #    if bigEnergyCounter <= 0: #or amountBigEnergy <= 0: # если энергии на карте закончились, тогда строим путь к выходу
                                #        print('Прокладываю путь до W')
                                #        alg.algWaveFindExit('W', hero, way, 0, monWay, masBlHole) #amountBigEnergy-1
                                #    else:
                                #        print('Прокладываю путь до E')
                                #        alg.algWaveFindExit('E', hero, way, masBE, monWay, masBlHole)#[amountBigEnergy-1])
                                #else:
                                    symbol = alg.calcWay(hero, way, monWay, 'E', 'W')
                                    #print('symbol: ' + str(symbol))
                                    #maps.clearWayNumFromMap(way)  # Очищаем карту, чтобы можно было проложить новый маршрут до другого объекта
                                    if symbol == 'W':
                                        print('Прокладываю путь до W')
                                        alg.algWaveFindExit('W', hero, way, 0, monWay, masBlHole) #amountBigEnergy-1
                                    else:
                                        print('Прокладываю путь до E')
                                        alg.algWaveFindExit('E', hero, way, masBE, monWay, masBlHole)#[amountBigEnergy-1])
                        else: stayHide -= 1
                        #maps.printInfo(hero, way) #Если раскоментить здесь: Отображает виденее героя и его действия

                        #Если на позиции героя иконка монстра, а герой еще жив, значит они совершат движение одновременно
                        #if way[hero.myPosY][hero.myPosX] == 'M':
                        #    hero.wait = True
                        #maps.clearNumFromMap(way)  # очищаю карту от всех возможных путей(чисел) и оставляю только проложенный (+) (для удобства отображения)
                #else: print('Проскочил')
                if hero.moveTime <= 0: # если перемещение героя в планируемую точку закончилось, вычисляем следующее движение
                    # Укажем место героя на карте (почему-то редко-редко теряется)
                    maps.clearHeroFromMap(way)
                    hero.myPosX = int(hero.rect.x / 32)
                    hero.myPosY = int(hero.rect.y / 32)
                    way[int(hero.myPosY)][hero.myPosX] = 'H'  # Добавляем расположение героя на карту (в массив)
                    #way[int(hero.startY / 32)][int(hero.startX / 32)] = 'H'
                    if dangerous == True:
                        for bh in masBlHole:
                            if bh.myPosY == hero.myPosY and bh.myPosX == hero.myPosX:
                                hero.checkMoveTime += 1
                                run = False
                                maps.clearWayNumFromMap(way)
                                #hero.startMoveTime = 15
                                #hero.moveTime = hero.startMoveTime
                    if run == True:
                        if dangerous == True:
                            left, right, up, down, hero.moveTime = alg.algWave(hero, way, monWay, '@')
                        else:
                            left, right, up, down, hero.moveTime = alg.algWave(hero, way, monWay, 'E')
                        #left, right, up, down, hero.moveTime = alg.algWave(hero, way, monWay, '@')

                    if left==True or right==True or up==True or down==True:
                        hero.amMove += 1
                    #maps.printInfo(hero, way) #Если раскоментить здесь: Отображает место куда герой уже наступил
                    #maps.clearNumFromMap(way) # очищаю карту от всех возможных путей(чисел) и оставляю только проложенный (+) (для удобства отображения)

                    #print ("Время движения: " + str(moveTime))
                else:
                    hero.moveTime -= 1
                    left = right = up = down = False #Для плавного движения это убирается
                    maps.clearWayNumFromMap(way)
                    #maps.printInfo(hero, way)
                #print('hero.amMove: ' + str(hero.amMove))

        else: slowSpeed -= 1

        #for mn in masMons: #Для плавного движения
        #    way[mn.myPrevPosY][mn.myPrevPosX] = 'M' #На карте видна лишь предыдущая позиция! Куда двигается монстр - не видно!

        window.blit(screen, (0,0)) # Каждую итерацию необходимо всё перерисовывать экран
        animatedEntities.update()  # показываеaм анимацию
        #mn.update(platforms, mleft, mright, mup, mdown, way)  # передвигаем всех монстров
        if slowSpeed == wait:
            monsters.update(platforms, way, hero)  # передвигаем всех монстров
            hero.updatePlayer(left, right, up, down, platforms, way)  # передвижение игроком
        camera.update(hero)  # центризируем камеру относительно персонажа
        #entities.draw(window) # отображение
        for e in entities:
            window.blit(e.image, camera.apply(e))
        window.blit(score_font.render("Счёт: " + str(hero.score), 1, (255, 255, 255)), (1, 1))
        window.blit(score_font.render("Жизни: " + str(hero.live), 1, (255, 255, 255)), (WIN_WIDTH-165, 1))

        pygame.display.update()     # обновление и вывод всех изменений на экран

        if slowSpeed == wait:
            if PLAY:
                maps.printInfo(hero, way)
Beispiel #22
0
def main():
    # -------------------------- INITIALIZING ALL THE NECESSARY VALUES --------------------------
    pygame.init()
    window = pygame.display.set_mode((c.WIDTH, c.HEIGHT))
    pygame.display.set_caption("Frogger")

    run = True

    # initializing lanes and adding them to the sprite group all_lanes
    # all directions are based on:
    # N - North (up the screen), S - South (down), E - East (right), W - West (left),
    direction_list = ['W', 'E']
    all_lanes = pygame.sprite.Group()
    for i in range(1, c.LANE_QUANTITY + 1):
        all_lanes.add(
            lanes.Lane(c.LANE_HEIGHT * i, i, random.choice(direction_list)))

    # initializing goals and adding them to the sprite group all_goals
    all_goals = pygame.sprite.Group()
    for i in range(0, c.COLUMN_QUANTITY):
        all_goals.add(blocks.Block(0, i, 'D'))

    # initializing cones with random positions (columns) on the CONE_LANE:
    list1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    cone1 = blocks.Block(c.CONE_LANE,
                         list1.pop(random.randint(0,
                                                  len(list1) - 1)), 'C')
    cone2 = blocks.Block(c.CONE_LANE,
                         list1.pop(random.randint(0,
                                                  len(list1) - 1)), 'C')
    cone3 = blocks.Block(c.CONE_LANE,
                         list1.pop(random.randint(0,
                                                  len(list1) - 1)), 'C')
    cone4 = blocks.Block(c.CONE_LANE,
                         list1.pop(random.randint(0,
                                                  len(list1) - 1)), 'C')
    # initializing two cones on the borders of the bottom (last) lane:
    cone5 = blocks.Block(c.LANE_QUANTITY - 1, 0, 'C')
    cone6 = blocks.Block(c.LANE_QUANTITY - 1, c.COLUMN_QUANTITY - 1, 'C')
    # sprite group for cones:
    cones = pygame.sprite.Group()
    cones.add(cone1, cone2, cone3, cone4, cone5, cone6)

    # initializing player (the frog)
    frog = player.Player()

    # initializing sprite groups for player and goal blocks (needed for drawing)
    goals = pygame.sprite.Group()
    goals.add(all_goals)
    players = pygame.sprite.Group()
    players.add(frog)

    next_movement = pygame.time.get_ticks(
    ) + c.PLAYER_DELAY  # value for limiting player's movements
    paused = False  # (so that the frog doesn't move too fast

    # -------------------------- GAME LOOP --------------------------
    while run:
        pygame.time.delay(50)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_p:  # game may be paused with 'P' key
                    if not paused:
                        paused = True
                        print("\nPause ON")
                    else:
                        paused = False
                        print("Pause OFF")

        if not paused:
            all_lanes.update()

            if next_movement <= pygame.time.get_ticks():
                keystate = pygame.key.get_pressed(
                )  # reading player's key input
                frog.update(cones, keystate)
                next_movement = pygame.time.get_ticks() + c.PLAYER_DELAY

            # graphics (drawing):
            window.fill(c.BLACK)
            all_lanes.draw(window)
            cones.draw(window)
            for lane_iter in all_lanes.sprites():
                lane_iter.draw(window)
            goals.draw(window)
            players.draw(window)

            # check if the frog collided with obstacle (if yes - game lost)
            for lane_iter in all_lanes.sprites():
                if lane_iter.collision_detector(frog):
                    end_screen(False, window)
                    run = False

            # else, if the frog steppend on the goal block - game won
            if pygame.sprite.spritecollideany(frog, all_goals) is not None:
                end_screen(True, window)
                run = False

            pygame.display.update()

    pygame.quit()
Beispiel #23
0
    def setup(self):
        if G.SINGLEPLAYER:
            try:
                print 'Starting internal server...'
                # TODO: create world menu
                G.SAVE_FILENAME = "world"
                start_server(internal=True)
                sock = socket.socket()
                sock.connect(("localhost", 1486))
            except socket.error as e:
                print "Socket Error:", e
                #Otherwise back to the main menu we go
                return False
            except Exception as e:
                print 'Unable to start internal server'
                import traceback
                traceback.print_exc()
                return False
        else:
            try:
                #Make sure the address they want to connect to works
                ipport = G.IP_ADDRESS.split(":")
                if len(ipport) == 1: ipport.append(1486)
                sock = socket.socket()
                sock.connect((tuple(ipport)))
            except socket.error as e:
                print "Socket Error:", e
                #Otherwise back to the main menu we go
                return False

        self.init_gl()

        sky_rotation = -20.0  # -20.0

        # TERRAIN_CHOICE = self.biome_generator.get_biome_type(sector[0], sector[2])
        default_skybox = 'skydome.jpg'
        #if TERRAIN_CHOICE == G.NETHER:
        #    default_skybox = 'skydome_nether.jpg'
        #else:
        #    default_skybox = 'skybox.jpg'

        print 'loading ' + default_skybox

        self.skydome = Skydome(
            'resources/' + default_skybox,
            #'resources/skydome.jpg',
            0.7,
            100.0,
            sky_rotation,
        )

        self.player_ids = {
        }  # Dict of all players this session, indexes are their ID's [0: first Player on server,]

        self.focus_block = B.Block(width=1.05, height=1.05)
        self.earth = vec(0.8, 0.8, 0.8, 1.0)
        self.white = vec(1.0, 1.0, 1.0, 1.0)
        self.ambient = vec(1.0, 1.0, 1.0, 1.0)
        self.polished = GLfloat(100.0)
        self.crack_batch = pyglet.graphics.Batch()

        #if G.DISABLE_SAVE and world_exists(G.game_dir, G.SAVE_FILENAME):
        #    open_world(self, G.game_dir, G.SAVE_FILENAME)

        self.world = World()
        self.packetreceiver = PacketReceiver(self.world, self, sock)
        self.world.packetreceiver = self.packetreceiver
        G.CLIENT = self.packetreceiver
        self.packetreceiver.start()

        #Get our position from the server
        self.packetreceiver.request_spawnpos()
        #Since we don't know it yet, lets disable self.update, or we'll load the wrong chunks and fall
        self.update_disabled = self.update
        self.update = lambda dt: None
        #We'll re-enable it when the server tells us where we should be

        self.player = Player(game_mode=G.GAME_MODE)
        print('Game mode: ' + self.player.game_mode)
        self.item_list = ItemSelector(self, self.player, self.world)
        self.inventory_list = InventorySelector(self, self.player, self.world)
        self.item_list.on_resize(self.window.width, self.window.height)
        self.inventory_list.on_resize(self.window.width, self.window.height)
        self.text_input = TextWidget(self.window,
                                     '',
                                     0,
                                     0,
                                     self.window.width,
                                     visible=False,
                                     font_name=G.CHAT_FONT)
        self.text_input.push_handlers(on_toggled=self.on_text_input_toggled,
                                      key_released=self.text_input_callback)
        self.chat_box = TextWidget(self.window,
                                   '',
                                   0,
                                   self.text_input.y + self.text_input.height +
                                   50,
                                   self.window.width / 2,
                                   height=min(300, self.window.height / 3),
                                   visible=False,
                                   multi_line=True,
                                   readonly=True,
                                   font_name=G.CHAT_FONT,
                                   text_color=(255, 255, 255, 255),
                                   background_color=(0, 0, 0, 100),
                                   enable_escape=True)
        self.camera = Camera3D(target=self.player)
        if G.HUD_ENABLED:
            self.label = pyglet.text.Label('',
                                           font_name='Arial',
                                           font_size=8,
                                           x=10,
                                           y=self.window.height - 10,
                                           anchor_x='left',
                                           anchor_y='top',
                                           color=(255, 255, 255, 255))
        pyglet.clock.schedule_interval_soft(self.world.process_queue,
                                            1.0 / G.MAX_FPS)
        pyglet.clock.schedule_interval_soft(self.world.hide_sectors, 10.0,
                                            self.player)
        return True
Beispiel #24
0
def set_block(block_x, block_y, tip):
    x = 37 * block_x
    y = 36 * block_y
    dgsgdysg = blocks.Block(x, y, tip)
    group_sprite.add(dgsgdysg)
Beispiel #25
0
def getcode(blockdata, address):
    block = blocks.Block(blockdata.decode('hex'))
    return block.get_code(address)
Beispiel #26
0
def getstate(blockdata):
    block = blocks.Block(blockdata.decode('hex'))
    return block.to_dict()
Beispiel #27
0
        self.pos = nextpos

        self.rect.x = self.pos.x
        self.rect.y = self.pos.y


import keyboard

if __name__ == "__main__":
    pygame.init()
    pygame.mixer.init()

    block_x = 400
    block_y = 100

    b = blocks.Block((block_x, block_y))
    blocks.group.add(b)

    spawn_x = block_x - 200
    spawn_y = 100 - 24

    def spawn(x, y):
        b_pos = (x, y)

        vx = 4
        vy = 0

        b = Ball(b_pos, (vx, vy))
        group.add(b)

    screen = pygame.display.set_mode(config.screen_size)
Beispiel #28
0
      block = blocks.Block(col, length)
      grid_clone = grid.clone()
      grid_clone.maybe_add_block(block, row_index)
      for filled_grid in randomly_fill_row(grid_clone,
                                           row_index,
                                           block.start + block.length + 1):
        yield filled_grid
      else:
        yield grid_clone

def build_castles(width, height):
  grid = grids.Grid(width, height)
  grid.maybe_add_block(blocks.Block(0, width), 0)
  candidates = set([grid])
  for row_index in xrange(1, height):
    new_candidates = set()
    for grid in candidates:
      for filled_grid in randomly_fill_row(grid, row_index, 0):
        new_candidates.add(filled_grid)
    candidates = new_candidates
  castles = set()
  for candidate in candidates:
    if candidate.is_castle() is True:
      castles.add(candidate)
  return castles


grid = grids.Grid(4, 3)
assert grid.maybe_add_block(blocks.Block(0, 3), 0)
grids.pretty_print(grid)
Beispiel #29
0
def main():

    finished = False
    first_time = True
    possible_answers = {'y', 'n'}
    attack_or_defense = ['attack', 'defense']
    index = 0
    attack = list()
    defense = list()
    '''
	while not finished:
		
		if not first_time:
			bad_input = True
			while bad_input:
				input1 = input('do you want to add more blocks (y) or (n): ')
				if input1 not in possible_answers:
					print('Type y or n')
				else:
					bad_input = False
					if input1 == 'n':
						finished = True

		if not finished:
			bad = True
			while bad:
				print('What strength block do you want to add to', attack_or_defense[index])
				strength = input('>')
				if strength.isdigit():
					bad = False
			bad = True
			while bad:
				print('What letter block you want to add to', attack_or_defense[index])
				letter = input('>')
				if letter.isalpha() and len(letter) == 1:
					bad = False
			bad = True
			while bad:
				print('What attack number do you want to add to', attack_or_defense[index])
				attack_number1 = input('>')
				if attack_number1.isdigit():
					bad = False
			new_block = blocks.Block(initial_attack_strength = int(strength), attack_letter = letter, attack_number = int(attack_number1))
			if index == 1:
				defense.append(new_block)
			else:
				attack.append(new_block)
		index = 1 - index

		if not first_time and not finished:
			bad_input = True
			while bad_input:
				input1 = input('do you want to add more blocks (y) or (n): ')
				bad_input = False
				if input1 not in possible_answers:
					print('Type y or n')
				else:
					if input1 == 'n':
						finished = True
		if not finished:
			bad = True
			while bad:
				print('What strength block do you want to add to', attack_or_defense[index])
				strength = input('>')
				if strength.isdigit():
					bad = False
			bad = True
			while bad:
				print('What letter block you want to add to', attack_or_defense[index])
				letter = input('>')
				if letter.isalpha() and len(letter) == 1:
					bad = False
			bad = True
			while bad:
				print('What attack number do you want to add to', attack_or_defense[index])
				attack_number1 = input('>')
				if attack_number1.isdigit():
					bad = False
			new_block = blocks.Block(initial_attack_strength = int(strength), attack_letter = letter, attack_number = int(attack_number1))
			

			if index == 1:
				defense.append(new_block)
			else:
				attack.append(new_block)
		index = 1 - index
		first_time = False
	'''

    attack = [
        blocks.Block(attack_number=3,
                     attack_letter='A',
                     initial_attack_strength=4)
    ]
    defense = [
        blocks.Block(attack_number=4,
                     attack_letter='B',
                     initial_attack_strength=4)
    ]
    bad_input = True
    while bad_input:
        try:
            num_times = int(input('How many times do you want to run this: '))
            bad_input = False
        except ValueError:
            print('type number')

    print('SIMULATION RUNNING')
    print(simulations.simulation(attack, defense, num_times))