Пример #1
0
 def readMap(self,mapName):
     mapFile = open(mapName,'r')
     self.x = int(mapFile.readline())
     self.y = int(mapFile.readline())
     line = mapFile.readline()
     lineList = line.split(',')
     for i in range(self.x):
         for j in range(self.y):
             if(lineList[j].isdigit()):
                 a = int(lineList[j])
                 temp = tile(j,i,a,0,self.size, self.gap)
                 self.arrayY.append(temp)
                 self.spriteGroup.add(temp)
                 if(a==2):
                     self.wallSprites.add(temp)
                 else:
                     self.roadSprites.add(temp)
                 self.nodeCount=self.nodeCount+1
             else:
                 self.wpCount = self.wpCount +1
                 wp = 'W'+str(self.wpCount)
                 temp = tile(j,i,0,wp,self.size, self.gap)
                 self.arrayY.append(temp)
                 self.spriteGroup.add(temp)
                 self.currentWaypoints.append(temp)
                 self.nodeCount=self.nodeCount+1
         self.arrayX.append(self.arrayY)
         self.arrayY=[]
         lineList=mapFile.readline().split(',')
Пример #2
0
def generateMap(level):
    global generated
    tileNumber = (19, 24, 34, 1)
    enemyNumber = (4, 5, 7, 0)
    loop = True
    while loop:
        try:
            tile((player.x, player.y), True, content="Spawn")
            temp = [i for j in const.mape for i in j if i]
            while len(temp) < tileNumber[level - 1]:
                rand.choice(temp).generate()
                temp = [i for j in const.mape for i in j if i]
            player.tile.discover()
            temp = [i for j in const.mape for i in j if i]
            temp = [i for i in temp if i.neighborsNb == 1]
            boss = rand.randrange(len(temp))
            temp.pop(boss).content = "Boss"
            shop = rand.randrange(len(temp))
            temp.pop(shop).content = "Shop"
            blacksmith = rand.randrange(len(temp))
            temp.pop(blacksmith).content = "Blacksmith"
        except ValueError:
            loop = True
            clrMap()
        else:
            loop = False
    generated = True
    temp = [i for j in const.mape for i in j if i]
    temp = [i for i in temp if i.content == None]
    for i in range(enemyNumber[level - 1]):
        mob = rand.randrange(len(temp))
        temp.pop(mob).content = "Mob"
def creatHtile(screen, pTile,
               playerNo):  # will return a list of hand tile object
    tileObjList = []
    if playerNo == 1:
        for i in range(len(pTile)):
            tileObj = tile(screen, pTile[i], False)  # create tile object
            tileObj.image = pygame.image.load("pic/tile_type3_300ppi/" +
                                              pTile[i] +
                                              ".png")  # load tile image
            tileObj.image = pygame.transform.smoothscale(
                tileObj.image, (60, 75))  # rescale the image
            tileObj.rect = tileObj.image.get_rect()
            tileObj.rect.left = 180 + i * 60
            tileObj.rect.top = 640
            tileObj.blitSelf()  # show the tile
            tileObjList.append(tileObj)  # add tile into the object list

    elif playerNo == 2:
        for i in range(len(pTile)):
            tileObj = tile(screen, pTile[i], False)
            tileObj.image = pygame.image.load("pic/tile_type3_300ppi/3-b.png")
            tileObj.image = pygame.transform.smoothscale(
                tileObj.image, (48, 60))
            tileObj.image = pygame.transform.rotate(tileObj.image, 90)
            tileObj.rect = tileObj.image.get_rect()

            tileObj.rect.bottom = 680 - i * 48
            tileObj.rect.left = 1060
            tileObj.blitSelf()
            tileObjList.append(tileObj)

    elif playerNo == 3:
        for i in range(len(pTile)):
            tileObj = tile(screen, pTile[i], False)
            tileObj.image = pygame.image.load("pic/tile_type3_300ppi/3-b.png")
            tileObj.image = pygame.transform.smoothscale(
                tileObj.image, (48, 60))
            tileObj.image = pygame.transform.rotate(tileObj.image, 180)
            tileObj.rect = tileObj.image.get_rect()

            tileObj.rect.top = 140 - 60
            tileObj.rect.left = 940 - 48 - i * 48
            tileObj.blitSelf()
            tileObjList.append(tileObj)

    elif playerNo == 4:
        for i in range(len(pTile)):
            tileObj = tile(screen, pTile[i], False)
            tileObj.image = pygame.image.load("pic/tile_type3_300ppi/3-b.png")
            tileObj.image = pygame.transform.smoothscale(
                tileObj.image, (48, 60))
            tileObj.image = pygame.transform.rotate(tileObj.image, 270)
            tileObj.rect = tileObj.image.get_rect()
            tileObj.rect.top = 80 + i * 48
            tileObj.rect.left = 80
            tileObj.blitSelf()
            tileObjList.append(tileObj)

    return tileObjList  # return the object list
    def drawATile(self,screen,tileStack):
        # check whether there is a tile in tile stack
        if tileStack == []:
            return False
        # when player holds certain number of tiles, they are not able to draw
        elif len(self.hT)+1 not in [1,2,5,8,11,12,14]:
            print( f"player{self.sequence}cannot draw, it has {len(self.hT)} tiles")

        # next part will add create a tile object for different players
        # move tile into the hand tile
        # remove tile from the stack
        elif self.sequence == 1: #create the tile object for player 1
            tileObj = tile(screen,tileStack[0], False) #creat the tile object
            tileObj.image = pygame.image.load("pic/tile_type3_300ppi/" + tileStack[0] + ".png") # load the tile image
            tileObj.image = pygame.transform.smoothscale(tileObj.image, (60, 75)) # transform the tile image
            tileObj.rect = tileObj.image.get_rect()
            tileObj.rect.x = self.hT[len(self.hT)-1].rect.x + 60 # set the x coordinate of the tile
            tileObj.rect.y = self.hT[0].rect.y # set the y coordinate of the tile
            tileObj.blitSelf()
            self.hT.append(tileObj) # add obj to the hand tile list
            tileStack.pop(0) # remove the tile from the stack

        elif self.sequence == 2: #create the tile object for player 2
            tileObj = tile(screen,tileStack[0], False)
            tileObj.image = pygame.image.load("pic/tile_type3_300ppi/3-b.png")
            tileObj.image = pygame.transform.smoothscale(tileObj.image, (48, 60))
            tileObj.image = pygame.transform.rotate(tileObj.image,90)
            tileObj.rect = tileObj.image.get_rect()
            tileObj.rect.x = self.hT[0].rect.x
            tileObj.rect.y = self.hT[len(self.hT)-1].rect.y - 48
            tileObj.blitSelf()
            self.hT.append(tileObj)
            tileStack.pop(0)

        elif self.sequence == 3: #create the tile object for player 3
            tileObj = tile(screen,tileStack[0], False)
            tileObj.image = pygame.image.load("pic/tile_type3_300ppi/3-b.png")
            tileObj.image = pygame.transform.smoothscale(tileObj.image, (48, 60))
            tileObj.image = pygame.transform.rotate(tileObj.image,180)
            tileObj.rect = tileObj.image.get_rect()
            tileObj.rect.x = self.hT[len(self.hT)-1].rect.x - 48
            tileObj.rect.y = self.hT[0].rect.y
            tileObj.blitSelf()
            self.hT.append(tileObj)
            tileStack.pop(0)

        elif self.sequence == 4: #create the tile object for player 4
            tileObj = tile(screen,tileStack[0], False)
            tileObj.image = pygame.image.load("pic/tile_type3_300ppi/3-b.png")
            tileObj.image = pygame.transform.smoothscale(tileObj.image, (48, 60))
            tileObj.image = pygame.transform.rotate(tileObj.image,270)
            tileObj.rect.x = self.hT[0].rect.x
            tileObj.rect.y = self.hT[len(self.hT)-1].rect.y + 48
            tileObj.blitSelf()
            self.hT.append(tileObj)
            tileStack.pop(0)
        self.tileSorting2(screen)
Пример #5
0
   def setActor(self, actor, x, y):
      if x < len(self.grid) and y <= len(self.grid):
         #make sure we're not adding a duplicate (causes movement)
         if actor not in self.actorList:
            self.actorList.append(actor)
         # if the actor being set is in the list, it is assumed to be moving. Remove the old pointer
         else:
            self.grid[actor.x][actor.y] = tile(None) # delete the Ronald Reagan

         self.grid[x][y] = tile(actor)
         actor.x = x
         actor.y = y
Пример #6
0
    def placeWord(cls, word, startX, startY, direction):

        for index, letter in enumerate(word):
            if direction == 'down':
                new_tile = tile(letter=letter,
                                x=startX,
                                y=startY + index,
                                direction=direction)
            elif direction == 'right':
                new_tile = tile(letter=letter,
                                x=startX + index,
                                y=startY,
                                direction=direction)

            cls.banana_board.append(new_tile)
Пример #7
0
   def buildWorld(self, size):
      for rows in range(size):


         #create a new row 
         self.grid.append([])

         for cols in range(size):

            if random.randint(0,1) == 1:
              #add to the row
               self.grid[rows].append(tile(None))
            else:
               self.actorList.append(npc.NPC())
               self.grid[rows].append(tile(self.actorList[-1]))
Пример #8
0
 def getTile(self, x, y):
     if self.tiles[x][y] == None:
         t = tile.tile()
         t.tex = "grass.png"
         return t
     else:
         return self.tiles[x][y]
Пример #9
0
 def _generate_empty_grid():
     grid = []
     for i in range(GRID_SIZE):
         grid.append([])
         for _ in range(GRID_SIZE):
             grid[i].append(tile(0))
     return grid
Пример #10
0
 def merge(row):
     pair = False
     new_row = []
     for i in range(len(row)):
         if pair:
             new_row.append(tile(2 * row[i].value))
             self.score += 2 * row[i].value
             pair = False
         else:
             if i + 1 < len(row) and row[i].value == row[i +
                                                         1].value:
                 pair = True
                 new_row.append(tile(0))
             else:
                 new_row.append(row[i])
     assert len(new_row) == len(row)
     return new_row
Пример #11
0
 def generateTile(self, xC, yC, height):
     """Creates a generic tile"""
     t = tile(xCoor = xC, yCoor = yC)
     self.tiles[(xC, yC)] = t
     t.jobs = []
     t.connectedCities = []
     t.improvements = []
     t.height = height
     t.world = self
Пример #12
0
	def clearPoint(self, xy):
		'''turns a tile into floor. Ignores the very edges of the map
		'''
		if xy[0] < 1 or xy[0] >= len(self.data[0])-1:
			return
		if xy[1] < 1 or xy[1] >= len(self.data)-1:
			return
		if self.data[xy[1]][xy[0]].style.name == "stone.txt":
			self.data[xy[1]][xy[0]] = tile.tile(tile.tileTypes["floor.txt"])
Пример #13
0
 def generateTile(self, xC, yC, height):
     """Creates a generic tile"""
     t = tile(xCoor=xC, yCoor=yC)
     self.tiles[(xC, yC)] = t
     t.jobs = []
     t.connectedCities = []
     t.improvements = []
     t.height = height
     t.world = self
Пример #14
0
	def setPoint(self, xy, tileName):
		'''changes a tile.
		'''
		if xy[0] < 1 or xy[0] >= len(self.data[0])-1:
			return
		if xy[1] < 1 or xy[1] >= len(self.data)-1:
			return
		tempPlace = self.data[xy[1]][xy[0]].enemyPlaced
		self.data[xy[1]][xy[0]] = tile.tile(tile.tileTypes[tileName])
		self.data[xy[1]][xy[0]].enemyPlaced = tempPlace
Пример #15
0
    def create(self):
        mapData = []
        for i in range(0, 100):
            tempTile = tile.tile()

            manaValue = self.mapMakingManaValue[i]
            valueSum = 0
            for j in manaValue:
                valueSum += int(j[0])

            randomValue = random.randrange(0, valueSum)

            valueSum = 0
            target = None
            for j in manaValue:
                valueSum += int(j[0])
                if randomValue < valueSum:
                    target = j
                    break
            tempTile.mana = int(target[1])

            stateValue = self.mapMakingValue[i]
            valueSum = 0
            for j in stateValue:
                valueSum += int(j[0])

            randomValue = random.randrange(0, valueSum)

            valueSum = 0
            target = None
            for j in stateValue:
                valueSum += int(j[0])
                if randomValue < valueSum:
                    target = j
                    break

            if target[1][0] == 'move':
                moveValue = 0
                while moveValue == 0:
                    moveValue = random.randrange(-target[1][2], target[1][2])
                if target[1][1] == 'portal':
                    moveValue += i
                    if moveValue < 0:
                        moveValue = 0
                    elif moveValue > 100:
                        moveValue = 100
                tempTile.state = (target[1][0], target[1][1], moveValue)
            else:
                tempTile.state = target[1]

            mapData.append(tempTile)

        makingMap = gameMap.gameMap(mapData)

        return makingMap
Пример #16
0
    def __init__(self,boardSize = None,carPlacement = None,random_values = 0, preMade_data = None,param_tile = None):
        """
        This method initializes a singleton of a board,a two dimensional array of various tiles and a car tile
        :param boardSize: dictionary of the form {'x': Int, 'y':Int}
        :param carPlacement: dictionary of the form {'x': Int, 'y':Int}
        :param random_values: tells the generator whether to randomize tile values
        :return:
        """

        #   To save the amount of memory, tile instance can be set as an input
        if param_tile is None:
            self._tile = tile()
        else:
            self._tile = tile

        #   board data should be received at real time environment, but should be generated
        #   randomly for testing purposes
        if preMade_data is not None:
            self._instance = preMade_data

        elif board._instance is None :
            xVal = None         #   Setted x value
            yVal = None         #   Setted y value
            if boardSize == None or type(boardSize) != type({}):
                if random_values == 0:
                    board._instance =self.init_board(board._defaultX, board._defaultY)
                elif random_values == 1:
                    board._instance =self.init_board(board._defaultX, board._defaultY,random_values = 1)
                xVal = board._defaultX
                yVal =  board._defaultY
            else:
                try:
                    xVal = boardSize['x']
                    yVal =  boardSize['y']
                    if (xVal<= 0) or (yVal <= 0):
                        raise self.impossible_action_exception("illegal board size")
                    board._instance =self.init_board(xVal, yVal)

                except:
                    board._instance =self.init_board(board._defaultX, board._defaultY)

            if carPlacement == None or type(carPlacement) != type({}):
                flag = self.initial_car_placement(int((xVal-1)/2), int((yVal-1)/2))
                print flag
            else:
                try:
                    flag = self.initial_car_placement(carPlacement['x'],carPlacement['y'])
                except:
                    #   A more - permissive form that allows to receive illegal car placement
                    #   flag = self.initial_car_placement(self.car_default_initial_placement[0], self.car_default_initial_placement[1])
                    #   less permisive form - raises an excpetion
                    raise self.impossible_action_exception("Cannot place car outside of the board borders")
            if flag == False:
                raise self.impossible_action_exception("Error car's initial placement")
Пример #17
0
 def read_tile(self, tyle):
   self.clgame.m.setTile(
     tyle['row'],
     tyle['col'], 
     tile.tile(
       tyle['tex'], 
       False, 
       tyle['rot'], 
       tyle['flipV'], 
       tyle['flipH']
       )
     )
Пример #18
0
    def make_board(self, x, y,
                   z):  # c = x (width) d = y (height) e = z (num bombs)
        # Declaration of board and adding row/columns
        self.width = x
        self.length = y
        self.num_bombs = z

        for j in range(self.width):
            column = []
            for i in range(self.length):
                column.append(tile())
            self.board.append(column)

        return
Пример #19
0
def initialize(gridwidth, gridheight):

    global tilelist

    y = 0

    while y < gridheight:

        x = 0

        while x < gridwidth:

            currenttile = tile.tile(x, y, float('inf'), None, None, False)
            x += 1
            tilelist.append(currenttile)

        y += 1

    for i in range(0, 1679):

        above = i - gridwidth
        below = i + gridwidth
        left = i - 1
        right = i + 1

        if above > -1 and above < 1680:

            currenttile_adjacencylistabove = tilelist[i].getadjacencylist()
            currenttile_adjacencylistabove.append(tilelist[i - gridwidth])
            tilelist[i].setadjacencylist(currenttile_adjacencylistabove)

        if below > -1 and below < 1680:

            currenttile_adjacencylistbelow = tilelist[i].getadjacencylist()
            currenttile_adjacencylistbelow.append(tilelist[i + gridwidth])
            tilelist[i].setadjacencylist(currenttile_adjacencylistbelow)

        if left > -1 and left < 1680 and i % 60 != 0:

            currenttile_adjacencylistleft = tilelist[i].getadjacencylist()
            currenttile_adjacencylistleft.append(tilelist[i - 1])
            tilelist[i].setadjacencylist(currenttile_adjacencylistleft)

        if right > -1 and right < 1680 and i % 60 != 59:

            currenttile_adjacencylistright = tilelist[i].getadjacencylist()
            currenttile_adjacencylistright.append(tilelist[i + 1])
            tilelist[i].setadjacencylist(currenttile_adjacencylistright)

    return tilelist
Пример #20
0
    def getTile(self, x, y):
        tileFound = True

        if x - 1 > len(self.tiles) or y - 1 > len(self.tiles[x]):
            tileFound = False
        elif self.tiles[x][y] == None:
            tileFound = False

        if not tileFound:
            t = tile.tile()
            t.tex = "grass.png"
            return t
        else:
            return self.tiles[x][y]
Пример #21
0
	def fromJson(self,json):
		self.width = json["width"]
		self.height = json["height"]
		self.tiles = []
		for key,value in json["tiles"].items():
			#print(value["terrain"],flush = True)
			new_tile = tile.tile(value["terrain"],int(key),value["x"],value["y"])
			self.tiles.append(new_tile)
		for t in self.tiles:
			#print(json["tiles"],flush = True)
			#print(json["tiles"][str(t.tid)],flush = True)
			#print(json["tiles"][str(t.tid)]["adjacent"],flush = True)
			t.load_adj(json["tiles"][str(t.tid)]["adjacent"],self.tiles)
		self.base_tile = self.tiles[0]
Пример #22
0
 def __init__(self, cell_size, rows, cols, window):
     self.dirt_list = []
     self.dirt_targeted = []
     self.cell_size = cell_size
     self.rows = rows
     self.cols = cols
     self.window = window
     self.dirt_machine = []
     self.vacuum = []
     self.grid = []
     self.dirt_img = pygame.image.load("dirt.png")
     for row in range(rows):  # create array
         self.grid.append([])
         for col in range(cols):
             self.grid[row].append(tile(row, col))
             if (row == 0):
                 self.grid[row][col].set_up_border()
             if (col == 0):
                 self.grid[row][col].set_left_border()
             if (row == rows - 1):
                 self.grid[row][col].set_down_border()
             if (col == cols - 1):
                 self.grid[row][col].set_right_border()
     for x in range(globals.globals.cleaning_agents):
         set = False
         self.vacuum.append([])
         while (not set):
             row = random.randint(0, rows - 1)
             col = random.randint(0, cols - 1)
             if (not self.grid[row][col].is_occupied()):
                 self.grid[row][col].set_vacuum()
                 self.vacuum[x].extend([row, col])
                 set = True
             else:
                 pass
     for x in range(globals.globals.dirt_agents):
         set = False
         self.dirt_machine.append([])
         while (not set):
             row = random.randint(0, rows - 1)
             col = random.randint(0, cols - 1)
             if (not self.grid[row][col].is_occupied()):
                 self.grid[row][col].set_dirt_machine()
                 self.dirt_machine[x].extend([row, col])
                 set = True
             else:
                 pass
     print("Vacuum initial positions", self.vacuum)
     print("Dirt agent initial positions", self.dirt_machine)
Пример #23
0
class boardReceiverInterface():

    _tile = tile.tile()

    def BR_NotImplemented(self, message=None):
        """
        General exception for methods that are not implemented
        :param message: Relevant message
        :return: none
        """
        if message is None:
            print "Board Receiver - method not implemented"
        else:
            print "Board Receiver - method % not implemented" % message

        sys.exit(1)

    def receive_board(self):
        """
        This method receives a board from an outer sources and
        transforms it to 2D array
        :return: 2D array of strings
        """
        raise self.BR_NotImplemented('receive_board')

    def get_board(self, refreshBoard=True):
        """
        :return: returns available map
        """
        raise self.BR_NotImplemented('get_board')

    def init_board(self, xVal, yVal):
        """
        Randomizing walls with random values according to a tile instance
        :param xVal: number of cells in an single array
        :param yVal: number of arrays
        :return:    2D array (yVal arrays) with random values
        """
        return [[(random.choice(self._tile.get_tile_mapping().values()))
                 for i in range(xVal)] for j in range(yVal)]

    def convert_to_board_instance(self, data):
        raise self.BR_NotImplemented('convert to board instance')

    def refresh_board(self):
        raise self.BR_NotImplemented('refresh_board')

    def get_car_direction(self, data):
        raise self.BR_NotImplemented('convert to board instance')
def createGrid(rows, columns, tileWidth, tileHeight, centerX, centerY):
    pList = []
    row = []
    for x in range(rows):
        for y in range(columns):
            cartX = x * tileWidth / 2
            cartY = y * tileHeight
            isoX, isoY = cartToIso(cartX, cartY)
            isoX += centerX
            isoY += centerY
            poly = tile.tile(isoX, isoY, tileWidth, tileHeight, cc.ARMOUR)
            poly.defaultColor = cc.ARMOUR
            row.append(poly)
        pList.append(row)
        row = []
    return pList
Пример #25
0
def mapmaker(area):
    composition = []
    size = [area.get_width(), area.get_height()]
    for x in xrange(size[0]):
        for y in xrange(size[1]):
            c = area.get_at((x, y))
            if c == (0, 255, 42, 255):
                composition.append(tile(x, y, grass, False, False))
            elif c == (181, 100, 34, 255):
                composition.append(tile(x, y, wood, False, False))
            elif c == (159, 159, 159, 255):
                composition.append(tile(x, y, grass, False, False))
                composition.append(tile(x, y, rock, True, False))
            elif c == (255, 114, 0, 255):
                composition.append(tile(x, y, dirt, False, False))
            elif c == (55, 114, 0, 255):
                composition.append(tile(x, y, dirt, False, False))
                composition.append(tile(x, y, rock, True, False))
            elif c == (85, 142, 29, 255):
                composition.append(tile(x, y, dtg2, False, False))
            elif c == (0, 0, 0, 255):
                composition.append(tile(x, y, portal, False, True))
    return (size, composition)
Пример #26
0
def mapmaker(area):
    composition = []
    size = [area.get_width(), area.get_height()]
    for x in xrange(size[0]):
        for y in xrange(size[1]):
            c = area.get_at((x,y))
            if c == (0, 255, 42, 255):
                composition.append(tile(x, y, grass, False, False))
            elif c == (181, 100, 34, 255):
                composition.append(tile(x, y, wood, False, False))
            elif c == (159,159,159,255):
                composition.append(tile(x, y, grass, False, False))
                composition.append(tile(x, y, rock, True, False))
            elif c == (255, 114, 0, 255):
                composition.append(tile(x, y, dirt, False, False))
            elif c == (55, 114, 0, 255):
                composition.append(tile(x, y, dirt, False, False))
                composition.append(tile(x, y, rock, True, False))
            elif c == (85, 142, 29, 255):
                composition.append(tile(x, y, dtg2, False, False))
            elif c == (0, 0, 0, 255):
                composition.append(tile(x, y, portal, False, True))
    return (size, composition)
Пример #27
0
 def draw_background(cls, display):
     tile_1 = pygame.image.load(constants.TILE_1_PATH)
     tile_2 = pygame.image.load(constants.TILE_2_PATH)
     y_loc = 0
     for c in range(len(cls.board_array)):
         x_loc = 0
         for r in range(len(cls.board_array[c])):
             if c % 2 == 0:  # even
                 if r % 2 == 0:  # even
                     display.blit(tile_1, (x_loc, y_loc))
                 else:
                     display.blit(tile_2, (x_loc, y_loc))
             else:
                 if r % 2 == 0:  # even
                     display.blit(tile_2, (x_loc, y_loc))
                 else:
                     display.blit(tile_1, (x_loc, y_loc))
             tile_info = tile.tile(x_loc, y_loc)
             x_loc += constants.TILE_SIZE
         y_loc += constants.TILE_SIZE
Пример #28
0
    def __init__ (self):

        # Assign a node_id for identification purpose in debug trace
        self.node_id = node.instances_created

        # Instantiate the tile list
        self.tile_list = []
        for i in range (cfg.num_tile): #first & last tiles - dummy, others - compute
            temp_tile = tile.tile ()
            self.tile_list.append (temp_tile)

        # Instantiate the NOC
        self.noc = nmod.noc ()

        # Some book-keeping variables (Can have harwdare correspondance)
        self.node_halt = 0
        self.tile_halt_list = [0] * cfg.num_tile
        self.tile_fid_list = []

        self.noc_start = 0
Пример #29
0
 def build(self):
     info = self.info()
     collision_tiles = []
     display_tiles = pygame.sprite.Group()
     x = y = tc = 0
     for row in self.map_array:
         for col in row:
             if col != " ":
                 t = tile(x, y,
                          info[col][0],
                          (info[col][1]*TILE_SIZE, 
                                         info[col][2]*TILE_SIZE,
                                         TILE_SIZE, 
                                         TILE_SIZE))
                 if info[col][3]:
                     collision_tiles.append(t)
                 display_tiles.add(t)
                 tc += 1
             x += 32
         y += 32
         x = 0
     return collision_tiles, display_tiles
Пример #30
0
	def loadXml(self,node):
		self.getText(node.childNodes)
		if node.nodeType!=Node.ELEMENT_NODE:
			for n in node.childNodes:
				if n.nodeType==Node.ELEMENT_NODE and n.localName == 'xdl_resource_report':
					self.loadXml(n)
		else:
			for n in node.childNodes:
				if n.nodeType==Node.ELEMENT_NODE and n.localName == 'tile':
					el=tile()
					el.loadXml(n)
					self.set_tile(el)
		
			if node.hasAttributes():
				attrs=node.attributes
				attrId='a1'
				if attrId in attrs.keys():
					self.a1=str(attrs[attrId].value)
		
				attrId='a0'
				if attrId in attrs.keys():
					self.a0=str(attrs[attrId].value)
Пример #31
0
                             default=1.5)
    parser_tile.add_argument(
        '--processes',
        nargs='?',
        type=int,
        help='How many concurrent processes should we put towards this?',
        default=4)
    return parser.parse_args()


if __name__ == '__main__':
    args = parse_args()
    if args.command == FEATURIZE_COMMAND:
        df = featurize_directory(args.image_directory,
                                 args.output_file,
                                 processes=args.processes)
    elif args.command == BUILD_COMMAND:
        df = write_options(args.target_image,
                           args.feature_file,
                           args.tile_file,
                           args.candidate_choices,
                           int(args.tiles_per_row),
                           float(args.tile_aspect_ratio),
                           args.comparison_func,
                           processes=args.processes)
    elif args.command == TILE_COMMAND:
        tile(args.tile_file, args.tiled_image, args.width, args.height,
             args.tile_aspect_ratio, args.processes)
    else:
        print('Unknown command.')
Пример #32
0
	def __init__(self,width,height,wrap = True):
		self.width = width
		self.height = height
		tiles = []

		this_col = [None]*height
		first_col = []
		prev_col = this_col.copy()
		for w in range(width):
			for h in range(height):
				if const.GLOBE_MODE and h == height - 1 and  w%2 != 0:
					pass
				else:
					new_tile = tile.tile(x=w,y=h)
					if h == 0 and w == 0:
						self.base_tile = new_tile
					if const.GLOBE_MODE:
						
						if h != 0:
							new_tile.set_adj(d_0 = tiles[-1])
						elif w%2 == 0:
							new_tile.adjacent[0]=new_tile
						if h == height - 1 and  w%2 == 0:
							new_tile.adjacent[180]=new_tile
						
					else:
						if h != 0:
							new_tile.set_adj(d_0 = tiles[-1])
						if h == height - 1:
							new_tile.set_adj(d_180 = this_col[0])
					"""elif const.GLOBE_MODE and w%2==0:
						new_tile.adjacent[0]=new_tile"""
					"""
						if const.GLOBE_MODE:
							if w%2 == 0:
								new_tile.adjacent[180]=new_tile
						else:
							"""
					if w != 0:
						if const.GLOBE_MODE:
							if w%2 == 0:
								if h != height - 1:
									new_tile.set_adj(d_240 = prev_col[h])
									#filler_tile = tile.tile(x=w-1,y=h+1)
									#tiles.append(filler_tile)
									#filler_tile.set_adj(d_120 = new_tile)
									#filler_tile.adjacent[60] = new_tile
									#filler_tile.set_adj(d_180 = new_tile)
								if h != 0:
									new_tile.set_adj(d_300 = prev_col[h-1])
									#filler_tile = tile.tile(x=w-1,y=h-1)
									#tiles.append(filler_tile)

							else:
								new_tile.set_adj(d_300 = prev_col[h])
								new_tile.set_adj(d_240 = prev_col[h+1])
						else:
							#print(w,h,this_col)
							if w%2 == 0:
								new_tile.set_adj(d_300 = prev_col[h-1])
								new_tile.set_adj(d_240 = prev_col[h])
								pass
							else:
								wrap_h = h+1
								if wrap_h == len(this_col):
									wrap_h = 0
								#print(new_tile.tid,this_col[wrap_h].tid,this_col[h-1].tid,flush = True)
								
								new_tile.set_adj(d_300 = prev_col[h])
								new_tile.set_adj(d_240 = prev_col[wrap_h])
						if w == width-1:
							#since w should be even?
							if w%2 == 0:
								#wrap_h = h+1
								#if wrap_h == len(this_col):
								#	wrap_h = 0
								first_col[h-1].set_adj(d_240 = new_tile)
								first_col[h].set_adj(d_300 = new_tile)
							else:
								wrap_h = h+1
								if wrap_h == len(first_col):
									wrap_h = 0
								#first_col[wrap_h].set_adj(d_240 = new_tile)
								first_col[wrap_h].set_adj(d_300 = new_tile)
								first_col[h].set_adj(d_240 = new_tile)
					else:
						first_col.append(new_tile)
					this_col[h] = new_tile
					tiles.append(new_tile)
			prev_col = this_col.copy()
		self.tiles = tiles
Пример #33
0
import tile
from units import chunk_size
from pics import rock

wall1 = []
wall2 = []
wall3 = []
wall4 = []

Len_wall = chunk_size-1

for i in xrange(Len_wall):
    wall1.append(tile.tile(i, 0, rock, True, False))

for i in xrange(Len_wall):
    wall2.append(tile.tile(0, i+1, rock, True, False))

for i in xrange(Len_wall):
    wall3.append(tile.tile(i+1, Len_wall, rock, True, False))

for i in xrange(Len_wall):
    wall4.append(tile.tile(Len_wall, i, rock, True, False))
Пример #34
0
class map_subscriber():
    """
    This class is responsible for fetching the data from the ROS
    and allows several other options.
    """

    _initial_location = None
    _board = None
    _direction = None
    _tile = tile.tile()
    _tileVal_obstacle = _tile.get_WallVal()
    _tileVal_free = _tile.get_FreeVal()
    _tileVal_unmapped = _tile.get_UnmappedVal()
    _tileVal_car = _tile.get_CarVal()
    _listener = None

    def __init__(self):
        print "Creating new subscriber\n"
        self._map_index = 0
        self.listener()

    def __str__(self):
        print "Current map:\n{0}".format(self._current_map)

    def refresh_board(self, odom, occu_grid):

        width = occu_grid.info.width
        height = occu_grid.info.height
        map = [[0 for x in range(width)] for x in range(height)]
        for i in range(width):
            for j in range(height):
                if occu_grid.data[j * width + i] == 0:
                    map[j][i] = self._tileVal_free
                elif occu_grid.data[j * width + i] > 0:
                    map[j][i] = self._tileVal_obstacle
                elif occu_grid.data[j * width + i] == -1:
                    map[j][i] = self._tileVal_unmapped

        grid_y = int(
            round(
                (odom.pose.pose.position.x - occu_grid.info.origin.position.x)
                / occu_grid.info.resolution, 0))
        grid_x = int(
            round(
                (odom.pose.pose.position.y - occu_grid.info.origin.position.y)
                / occu_grid.info.resolution, 0))
        map[grid_x][grid_y] = self._tileVal_car
        while True:
            try:
                (trans,
                 rot) = self._listener.lookupTransform('/map', '/camera_link',
                                                       rospy.Time(0))
                break
            except (tf.LookupException, tf.ConnectivityException,
                    tf.ExtrapolationException):
                continue
        euler = tf.transformations.euler_from_quaternion(rot)
        yaw = euler[2]
        yaw = (yaw * 180 / pi)

        if self._initial_location is None:
            self._initial_location = coordinate(grid_x, grid_y)
        self._board = map
        self._direction = self.calcDirection(yaw)

    def listener(self):

        # In ROS, nodes are uniquely named. If two nodes with the same
        # node are launched, the previous one is kicked off. The
        # anonymous=True flag means that rospy will choose a unique
        # name for our 'listener' node so that multiple listeners can
        # run simultaneously.
        rospy.init_node('listener', anonymous=True)
        occu_grid_sub = message_filters.Subscriber('rtabmap/proj_map',
                                                   OccupancyGrid)
        odom_sub = message_filters.Subscriber('rtabmap/odom', Odometry)

        ts = message_filters.TimeSynchronizer([odom_sub, occu_grid_sub], 10)
        ts.registerCallback(self.refresh_board)
        flag = False
        while not flag:
            try:
                self._listener = tf.TransformListener()
            except:
                continue
            flag = True
        time.sleep(5)
        #rospy.spin()

    def get_initial_coordinate(self):
        """
        getter method for initial car location
        :return: coordinate instance, coordinate with 0 value upon failure
        """
        if self._initial_location is None:
            return coordinate.coordinate(0, 0)
        try:
            return self._initial_location
        except:
            return coordinate.coordinate(0, 0)

    def get_board(self):
        """
        getter method to access the map data
        :return: (map_instance, index) upon success, False otherwise
        """
        try:
            return self._current_map, self._map_index
        except:
            return False

    def calcDirection(self, yaw):
        if -22.5 <= yaw < 22.5:
            return 1
        if 22.5 <= yaw < 67.5:
            return 2
        if 67.5 <= yaw < 112.5:
            return 3
        if 112.5 <= yaw < 157.5:
            return 4
        if -157.5 > yaw or yaw >= 157.5:
            return 5
        if -157.5 <= yaw < -112.5:
            return 6
        if -112.5 <= yaw < 67.5:
            return 7
        if -67.5 <= yaw < -22.5:
            return 8
        return 1
Пример #35
0
import cPickle as p
from tile import tile

tl = []
techID = 0

#unsorted tiles
tl.append([])
t=tile(techID,'Low water','misc',0, True, 0, 'Your feet become wet.', None)
techID+=1
tl[0].append(t)
t=tile(techID,'Mud','misc',1, True, 0, 'The ground under your feet feels soft and wet.', None)
techID+=1
tl[0].append(t)
t=tile(techID,'Hot caveground','misc',2, True, 0, 'The ground under your feet feels like hot coals.', None)
techID+=1
tl[0].append(t)
t=tile(techID,'Water','misc',3,False,0,'None', None)
techID+=1
tl[0].append(t)
t=tile(techID,'Ore','misc',4,False, 0,'You brake some ore out of the solid rock here.', None, 2, None)
techID+=1
tl[0].append(t)
t=tile(techID,'Gem','misc',5,False, 0,'You brake a gem out of the solid rock here.', None, 4, None)
techID+=1
tl[0].append(t)
t=tile(techID,'Blue Mushroom','misc',6, True, 0, 'A blue mushroom grows here.', None, False, None)
techID+=1
tl[0].append(t)
t=tile(techID,'Brown Mushroom','misc',7, True, 0, 'A brown mushroom grows here.', None, False, None)
techID+=1
Пример #36
0
def play(keysettings, screen, imagefiles, fps, screensync = True):
  clock = pygame.time.Clock()

  screenrect = screen.get_rect()

  tilefile = imagefiles["tile"]

  background = pygame.Surface(screen.get_size())
  tileimage = pygame.image.load(tilefile).convert_alpha()
  tile(background, tileimage)

  red = (255, 20, 20)
  blue = (0, 50, 200)
  yellow = (255, 255, 0)

  backgroundrect = background.get_rect()

  pausefont = pygame.font.Font(None, screenrect.width / 5)
  pausetext = pausefont.render("Paused", 1, yellow)
  pausetextrect = pausetext.get_rect()
  pausetextrect.centerx = screenrect.centerx
  pausetextrect.centery = screenrect.centery

  scorefont = pygame.font.Font(None, screenrect.width / 10)

  score = 0
  starttime = time.time()

  wormfile = imagefiles["worm"]

  worm = pygame.image.load(wormfile).convert_alpha()

  direction = "left"

  wormrect = worm.get_rect()
  wormrect.bottom = screenrect.bottom
  wormrect.centerx = screenrect.centerx

  wormspeed = [-2, 0]

  fireballfile = imagefiles["fireball"]

  fireball = pygame.image.load(fireballfile).convert_alpha()

  fireballcount = (screenrect.width / fireball.get_rect().width) / 4 + 1

  fireballrects = [fireball.get_rect() for i in range(fireballcount)]
  for e in fireballrects:
    e.bottom = 0
    e.left = int(random() * (screenrect.width - e.width) + e.width)

  maxfireballspeed = 4

  fireballspeeds = [
    (0, int(random() * maxfireballspeed) + 1)
    for i in range(len(fireballrects))
  ]

  paused = False

  gameover = False
  while not gameover:
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        sys.exit()
      elif event.type == pygame.KEYDOWN:
        if event.key == keysettings["escape"]:
          sys.exit()
        elif event.key == keysettings["pause"]:
          if paused:
            starttime = time.time()
            paused = False
          else:
            paused = True
        elif event.key == keysettings["screenshot"]:
          screenshot(screen)
        elif not paused:
          if event.key == keysettings["left"]:
            if direction == "right":
              worm = pygame.transform.flip(worm, 1, 0)
              replaceRect(wormrect, worm.get_rect())

              wormspeed[0] = -wormspeed[0]

              direction = "left"
          elif event.key == keysettings["right"]:
            if direction == "left":
              worm = pygame.transform.flip(worm, 1, 0)
              replaceRect(wormrect, worm.get_rect())

              wormspeed[0] = -wormspeed[0]

              direction = "right"
          elif event.key == keysettings["plus"]:
            temp = fireball.get_rect()
            temp.bottom = 0
            temp.left = int(random() * (screenrect.width - e.width) + e.width)
            fireballrects.append(temp)
            fireballspeeds.append((0, int(random() * maxfireballspeed) + 1))
          elif event.key == keysettings["minus"]:
            if len(fireballrects) > 0 and len(fireballspeeds) > 0:
              del fireballrects[-1]
              del fireballspeeds[-1]

    if paused:
      screen.blit(pausetext, pausetextrect)
    else:
      score += time.time() - starttime
      starttime = time.time()

      scoretext = scorefont.render(str(int(score)), 1, blue)
      scorerect = scoretext.get_rect()
      scorerect.top = screenrect.top + screenrect.height / 20
      scorerect.right = screenrect.right - screenrect.width / 20

      if wormrect.left > screenrect.left and direction == "left":
        if pygame.key.get_pressed()[keysettings["left"]]:
          wormrect = wormrect.move(wormspeed)
      elif wormrect.right < screenrect.right and direction == "right":
        if pygame.key.get_pressed()[keysettings["right"]]:
          wormrect = wormrect.move(wormspeed)

      for i in range(len(fireballrects)):
        if fireballrects[i].colliderect(wormrect):
          gameover = True
        elif fireballrects[i].top < screenrect.bottom:
          fireballrects[i] = fireballrects[i].move(fireballspeeds[i])
        else:
          fireballrects[i].bottom = int(random() * (screenrect.height - 0.75 * screenrect.height))
          fireballrects[i].centerx = int(random() * (screenrect.width - 50) + 25)
          fireballspeeds[i] = (0, int(random() * maxfireballspeed) + 1)

      screen.blit(background, backgroundrect)
      screen.blit(worm, wormrect)

      for i in range(len(fireballrects)):
        screen.blit(fireball, fireballrects[i])

      screen.blit(scoretext, scorerect)

    if screensync:
      clock.tick(fps)

    pygame.display.flip()

  gameoverfont = pygame.font.Font(None, screenrect.width / 5)
  scoretext = gameoverfont.render("Oh Noes !!!", 1, red)
  textpos = scoretext.get_rect()
  textpos.centerx = screenrect.centerx
  textpos.centery = screenrect.centery

  screen.blit(scoretext, textpos)
  pygame.display.flip()

  return
Пример #37
0
from path import path as path
#import player
#import health
#import Terranada
#import enemy
#import gun
from pics import rock as rock, grass as grass
from tile import tile

#player1 = player.player()
#sams_health = health.health()

#terranada = Terranada.Terranada()
#terras_health = health.health()
#terras_health.setset(1)

world1 = []
world1.append(tile(0,0,rock,True))
Пример #38
0
	def fillMap(self):
		self.data = [None] * self.size[1]
		for i in range(self.size[1]):
			self.data[i] = [None] * self.size[0]
			for j in range(self.size[0]):
				self.data[i][j] = tile.tile(tile.tileTypes["stone.txt"])
def pengAction(screen, playerA, playerB):
    #action happened after the user clicked peng button 碰
    #player A will execute peng
    dTname = playerB.dT[-1].name
    indexlist = []
    for i in range(len(playerA.hT)):
        if playerA.hT[i].name == dTname:
            indexlist.append(i)

    if playerA.sequence == 1:
        for i in range(3):
            tileObj = tile(screen, dTname, False)
            tileObj.image = pygame.image.load("pic/tile_type3_300ppi/" +
                                              dTname + ".png")
            tileObj.image = pygame.transform.smoothscale(
                tileObj.image, (60, 75))
            tileObj.rect = tileObj.image.get_rect()
            tileObj.rect.left = 180 + len(playerA.aT) * 60
            tileObj.rect.top = 720
            tileObj.blitSelf()
            playerA.aT.append(tileObj)
        for i in range(2):
            playerA.hT.pop(indexlist[i] - i)
            for x in playerA.hT[indexlist[i] -
                                i:len(playerA.hT
                                      )]:  # reset the rect of the tiles
                x.rect.x -= 60

    elif playerA.sequence == 2:
        for i in range(3):
            tileObj = tile(screen, dTname, False)
            tileObj.image = pygame.image.load("pic/tile_type3_300ppi/" +
                                              dTname + ".png")
            tileObj.image = pygame.transform.smoothscale(
                tileObj.image, (48, 60))
            tileObj.image = pygame.transform.rotate(tileObj.image, 90)
            tileObj.rect = tileObj.image.get_rect()
            tileObj.rect.left = 1130
            tileObj.rect.bottom = 720 - len(playerA.aT) * 48
            tileObj.blitSelf()
            playerA.aT.append(tileObj)
        for i in range(2):
            playerA.hT.pop(indexlist[i] - i)
            for x in playerA.hT[indexlist[i] -
                                i:len(playerA.hT
                                      )]:  # reset the rect of the tiles
                x.rect.y += 48

    elif playerA.sequence == 3:
        for i in range(3):
            tileObj = tile(screen, dTname, False)
            tileObj.image = pygame.image.load("pic/tile_type3_300ppi/" +
                                              dTname + ".png")
            tileObj.image = pygame.transform.smoothscale(
                tileObj.image, (48, 60))
            tileObj.image = pygame.transform.rotate(tileObj.image, 180)
            tileObj.rect = tileObj.image.get_rect()
            tileObj.rect.top = 140 - 60 - 70
            tileObj.rect.left = 940 - 48 - len(playerA.aT) * 48
            tileObj.blitSelf()
            playerA.aT.append(tileObj)
        for i in range(2):
            playerA.hT.pop(indexlist[i] - i)
            for x in playerA.hT[indexlist[i] -
                                i:len(playerA.hT
                                      )]:  # reset the rect of the tiles
                x.rect.x += 48

    elif playerA.sequence == 4:
        for i in range(3):
            tileObj = tile(screen, dTname, False)
            tileObj.image = pygame.image.load("pic/tile_type3_300ppi/" +
                                              dTname + ".png")
            tileObj.image = pygame.transform.smoothscale(
                tileObj.image, (48, 60))
            tileObj.image = pygame.transform.rotate(tileObj.image, 270)
            tileObj.rect = tileObj.image.get_rect()
            tileObj.rect.top = 80 + len(playerA.aT) * 48
            tileObj.rect.left = 10
            tileObj.blitSelf()
            playerA.aT.append(tileObj)

        for i in range(2):
            playerA.hT.pop(indexlist[i] - i)
            for x in playerA.hT[indexlist[i] -
                                i:len(playerA.hT
                                      )]:  # reset the rect of the tiles
                x.rect.y -= 48
    playerB.dT.remove(playerB.dT[-1])
    playerA.tileSorting2(screen)
def gangAction2(screen, playerA):
    hTNameList = playerA.get_hTNameList()
    hTNameList = tNametoInt(hTNameList)
    tName = f"3-{getQura(hTNameList)[0]}"
    indexlist = []
    for i in range(len(playerA.hT)):
        if playerA.hT[i].name == tName:
            indexlist.append(i)
    if playerA.sequence == 1:
        for i in range(4):
            tileObj = tile(screen, tName, False)
            tileObj.image = pygame.image.load("pic/tile_type3_300ppi/" +
                                              tName + ".png")
            tileObj.image = pygame.transform.smoothscale(
                tileObj.image, (60, 75))
            tileObj.rect = tileObj.image.get_rect()
            tileObj.rect.left = 180 + len(playerA.aT) * 60
            tileObj.rect.top = 720
            tileObj.blitSelf()
            playerA.aT.append(tileObj)
        for i in range(4):
            playerA.hT.pop(indexlist[i] - i)
            for x in playerA.hT[indexlist[i] -
                                i:len(playerA.hT
                                      )]:  # reset the rect of the tiles
                x.rect.x -= 60

    elif playerA.sequence == 2:
        for i in range(4):
            tileObj = tile(screen, tName, False)
            tileObj.image = pygame.image.load("pic/tile_type3_300ppi/" +
                                              tName + ".png")
            tileObj.image = pygame.transform.smoothscale(
                tileObj.image, (48, 60))
            tileObj.image = pygame.transform.rotate(tileObj.image, 90)
            tileObj.rect = tileObj.image.get_rect()
            tileObj.rect.left = 1130
            tileObj.rect.bottom = 720 - len(playerA.aT) * 48
            tileObj.blitSelf()
            playerA.aT.append(tileObj)
        for i in range(4):
            playerA.hT.pop(indexlist[i] - i)
            for x in playerA.hT[indexlist[i] -
                                i:len(playerA.hT
                                      )]:  # reset the rect of the tiles
                x.rect.y += 48

    elif playerA.sequence == 3:
        for i in range(4):
            tileObj = tile(screen, tName, False)
            tileObj.image = pygame.image.load("pic/tile_type3_300ppi/" +
                                              tName + ".png")
            tileObj.image = pygame.transform.smoothscale(
                tileObj.image, (48, 60))
            tileObj.image = pygame.transform.rotate(tileObj.image, 180)
            tileObj.rect = tileObj.image.get_rect()
            tileObj.rect.top = 140 - 60 - 70
            tileObj.rect.left = 940 - 48 - len(playerA.aT) * 48
            tileObj.blitSelf()
            playerA.aT.append(tileObj)
        for i in range(4):
            playerA.hT.pop(indexlist[i] - i)
            for x in playerA.hT[indexlist[i] -
                                i:len(playerA.hT
                                      )]:  # reset the rect of the tiles
                x.rect.x += 48

    elif playerA.sequence == 4:
        for i in range(4):
            tileObj = tile(screen, tName, False)
            tileObj.image = pygame.image.load("pic/tile_type3_300ppi/" +
                                              tName + ".png")
            tileObj.image = pygame.transform.smoothscale(
                tileObj.image, (48, 60))
            tileObj.image = pygame.transform.rotate(tileObj.image, 270)
            tileObj.rect = tileObj.image.get_rect()
            tileObj.rect.top = 80 + len(playerA.aT) * 48
            tileObj.rect.left = 10
            tileObj.blitSelf()
            playerA.aT.append(tileObj)

        for i in range(4):
            playerA.hT.pop(indexlist[i] - i)
            for x in playerA.hT[indexlist[i] -
                                i:len(playerA.hT
                                      )]:  # reset the rect of the tiles
                x.rect.y -= 48

    playerA.tileSorting2(screen)
 def tileCallback(self, sender):
     tile()