예제 #1
0
    def cmd_tile(self):
        Tile.cmd_tile(self)

        if not self.root:
            self.root = LeafFrame(self, None, Container(self))

            active = self.monitor.get_active()

            if active:
                self.add(active)

            for win in self.monitor.iter_windows():
                if win != active:
                    self.add(win)
        else:
            self.promote()
            for child in self.root.childs():
                if child.cont.empty and not child.cont.win:
                    child.cont.set_window(force=True)

        self.root.moveresize(
            self.monitor.wa_x, self.monitor.wa_y,
            self.monitor.wa_width, self.monitor.wa_height
        )

        for win in self.iter_hidden():
            win.set_below(True)

        for child in self.root.childs():
            child.cont.window_below(False)
            child.reset_cycle()
예제 #2
0
	def init(self,voice=1):
		if voice==1: super().init()
		self.bgColor = (255,255,255)
		self.count = 0
		self.sec = 0 
		self.min = 0
		self.timetext = "TIME : 0:00"
		self.timechange = False
		self.movechange = False
		self.mute = -1
		self.mode = "play"
		#self.mode = "solve"
		self.solvelist = [5,6,7,3,2,6,5,1,2,3,7]
		self.solvelist += [11,12,8,4,3,7,6,10,9]
		self.solvelist += [13,14,15,16,12,11,10,9,13,14,15,11]
		self.solvelist += [10,14,13,9,10,6,5,9,13,14,15]
		self.solveindex = len(self.solvelist)-1

		datastring = "1000\n"
		datastring += "1000\n"
		writeFile("game4data.txt",datastring)

		global curk,k
		curk,k = 16,16
		global pg,pp
		pg = [2,7,10,11,14]
		pp = [1,3,4,5,9,13]
		
		Gear.init()
		Tile.init()
		Pipe.init()

		self.win = False
		self.gears = pygame.sprite.Group()
		self.pipes = pygame.sprite.Group()

		self.gears.add(Gear(330-65,180+65,-1,0))
		self.gears.add(Gear(330+65*4,180,17,0,1))

		self.tiles = pygame.sprite.Group()

		for i in range(4):
			for j in range(4):
				x=330+65*j
				y=180+65*i
				num=j*4+i+1
				if num != curk: self.tiles.add(Tile(x,y,num))
				if num in pg: 
					self.gears.add(Gear(x,y,num,0))
				if num in pp:
					if num == 13:
						self.pipes.add(Pipe(x,y,num,4))
					elif num == 5:
						self.pipes.add(Pipe(x,y,num,5))
					else:
						self.pipes.add(Pipe(x,y,num,1))

		self.exit = 20
		self.exittype = 1
		self.timer = 15
예제 #3
0
    def __init__(self, width, height, colony, food):
        self.width = width
        self.height = height
        self.colony = [
                        colony[0]*TILE_SIZE, colony[1]*TILE_SIZE,
                        TILE_SIZE, TILE_SIZE
                        ]
        self.food = food
        screen_size = [width*TILE_SIZE, height*TILE_SIZE]
        self.screen = pygame.display.set_mode(screen_size)
        self.screen.fill(WHITE)
        self.tiles = []
        self.ants = {}

        # Populate grid
        for w in range(0, width):
            for h in range(0, height):
                square = Tile(w*TILE_SIZE, h*TILE_SIZE)
                self.tiles.append(square)
                rect, color = square.render()
                pygame.draw.rect(self.screen, color, rect)
        # Place colony
        pygame.draw.rect(self.screen, GREEN, self.colony)
        # Place food
        food_pos = food['position']
        pile = [[food_pos[0]*TILE_SIZE+TILE_SIZE/2, food_pos[1]*TILE_SIZE],
                [food_pos[0]*TILE_SIZE, (food_pos[1]+1)*TILE_SIZE],
                [(food_pos[0]+1)*TILE_SIZE, (food_pos[1]+1)*TILE_SIZE]]
        pygame.draw.polygon(self.screen, YELLOW, pile)
        pygame.display.set_caption("Ant colony visualization")
        pygame.display.flip()
예제 #4
0
	def init(self):
		super().init()
		self.bgColor = (255,255,255)
		self.count = 15
		self.sec = 0 
		self.min = 0
		self.timetext = "TIME : 0:00"
		self.moveup = False
		self.mute = -1

		global curk,k
		curk,k = 3,3
		global p
		p = [1,4,6,7,10,11,13,16]
		
		Gear.init()
		Tile.init()
		self.win = False
		self.gears = pygame.sprite.Group()
		self.gears.add(Gear(330,180+65*4,-1,1))
		self.gears.add(Gear(330+65*4,180,17,0))
		self.tiles = pygame.sprite.Group()

		for i in range(4):
			for j in range(4):
				x=330+65*j
				y=180+65*i
				num=j*4+i+1
				if num != curk: self.tiles.add(Tile(x,y,num))
				if num in p: 
					if num==4: 
						self.gears.add(Gear(x,y,num,1))	
					else:
						self.gears.add(Gear(x,y,num,0))
예제 #5
0
파일: tile_auto.py 프로젝트: Belluka/pytyle
    def cmd_untile(self):
        Tile.cmd_untile(self)

        if self.store:
            for cont in self.store.all()[:]:
                cont.remove(reset_window=True)

            self.store.reset()
예제 #6
0
 def tileClicked(self, x, y):
     tile = self.grid[x][y]
     if tile is None:
         tileID = self.takeCard()
         if (tileID is not None):
             tile = Tile(self.tileData[tileID], tileID, x, y, self.activePlayer)
             self.grid[x][y] = tile
     else:
         tile.rotate()
     self.calculatePower()
예제 #7
0
	def init(self):
		super().init()
		self.bgColor = (255,255,255)
		self.count = 0
		self.sec = 3100
		self.min = 0
		self.timetext = "TIME : 0:30"
		self.timeup = False
		self.mute = -1

		global curk,k
		curk,k = 4,4
		global p1,p2,p3,p4,p5,p6,p7
		p1 = [5,7,10,12,15]
		p2 = [8,9]
		p3 = [14]
		p4 = []
		p5 = [3]
		p6 = [2]
		p7 = [6,11]
		
		Pipe.init()
		Tile.init()
		Gear.init()

		self.win = False
		self.pipes = pygame.sprite.Group()
		self.tiles = pygame.sprite.Group()
		self.gears = pygame.sprite.Group()

		self.gears.add(Gear(330+65*3+5,180-55,-1,0))

		for i in range(4):
			for j in range(4):
				x=332+65*j
				y=180+65*i
				num = j*4+i+1
				if num in p1: 
					self.pipes.add(Pipe(x,y,num,1))	
				elif num in p2:
					self.pipes.add(Pipe(x,y,num,2))
				elif num in p3:
					self.pipes.add(Pipe(x,y,num,3))
				elif num in p4:
					self.pipes.add(Pipe(x,y,num,4))
				elif num in p5:
					self.pipes.add(Pipe(x,y,num,5))
				elif num in p6:
					self.pipes.add(Pipe(x,y,num,6))
				elif num in p7:
					self.pipes.add(Pipe(x,y,num,7))
				elif num!= curk:
					self.tiles.add(Tile(x,y,num))

		self.timer = 15
예제 #8
0
	def init(self,voice=1):
		if voice==1: super().init()
		self.bgColor = (255,255,255)
		self.count = 0
		self.sec = 0 
		self.min = 0
		self.timetext = "TIME : 0:00"
		self.timechange = False
		self.movechange = False
		self.mute = -1
		self.mode = "play"
		#self.mode = "solve"
		self.solvelist = [11,10,9,13,14,10,11,7,6,10,11,12,8]
		self.solvelist += [7,3,2,6,10,11,12,8,7,3]
		self.solveindex = len(self.solvelist)-1

		datastring = "1000\n"
		datastring += "1000\n"
		writeFile("game5data.txt",datastring)

		global curk,k
		curk,k = 4,4
		global p3,p6
		p3 = [1,2,3,5,6,9]
		p6 = [8,11,12,14,15,16]
		
		Pipe.init()
		Tile.init()
		Gear.init()

		self.win = False
		self.pipes = pygame.sprite.Group()
		self.tiles = pygame.sprite.Group()
		self.gears = pygame.sprite.Group()

		self.gears.add(Gear(330+65*3+5,180-55,-1,0,1))
		
		for i in range(4):
			for j in range(4):
				x=332+65*j
				y=180+65*i
				num = j*4+i+1
				if num in p3:
					self.pipes.add(Pipe(x,y,num,3))
				elif num in p6:
					self.pipes.add(Pipe(x,y,num,6))
				elif num!= curk:
					self.tiles.add(Tile(x,y,num))

		self.exit = 0
		self.exittype = 6
		self.timer = 15
		self.gassound = pygame.mixer.Sound('sound/gas01.wav')
		self.gassound.play()
		self.gassound.set_volume(0.2)
예제 #9
0
파일: objects.py 프로젝트: Catagen/boxo
    def __init__(self, tile, source, game):
        super(Character, self).__init__(source=source, pos=(Tile.get_tile(tile).x, Tile.get_tile(tile).y))
        self.speed_x, self.speed_y = CHAR_SPEED_X, CHAR_SPEED_Y
        self.deacc = CHAR_DEACCELERATION
        self.velocity_x = 0
        self.velocity_y = 0
        self.tile = tile
        self.game = game
        self.moving = False

        self.game.add_widget(self)
예제 #10
0
class TestTile(unittest.TestCase):

    def setUp(self):
        pygame.init()
        self.screen = pygame.display.set_mode((32, 32))
        self.tile = Tile(0, 0, 'data/tiles/wall.png', self.screen, (32, 32))

    def test_blitting(self):
        self.tile.update()
        pygame.display.flip()
        pygame.time.Clock().tick(2)
예제 #11
0
 def __init__(self, element, xoffset = 0.0, yoffset = 0.0, level=0):
     QObject.__init__(self)
     Tile.__init__(self, element)
     self.__board = None
     self.graphics = GraphicsTileItem(self)
     self.__xoffset = xoffset
     self.__yoffset = yoffset
     self.__dark = False
     self.level = level
     self.activeAnimation = dict() # key is the property name
     self.queuedAnimations = []
예제 #12
0
파일: main2.py 프로젝트: Catagen/boxo
    def __init__(self):
        super(Game, self).__init__()

        self.level = Level(1, [10,11,12,25], [11,12])
        Tile.make_tiles(self.size, self.level)

        self.background = Background(source='img/background.png')
        self.size = self.background.size
        self.add_widget(self.background)
        self.character = Character(pos=(20, self.height/2))
        self.add_widget(self.character)
        Clock.schedule_interval(self.update, 1.0/60.0)
예제 #13
0
def buildtile(args):
    """Given a region name and coordinates, build the corresponding tile."""
    # this should work for single and multi threaded cases
    (log, name, tilex, tiley) = args
    log.log_debug(1,"Building tile (%d,%d) of map %s..." % \
                    (tilex, tiley, name))
    yamlfile = file(os.path.join('Regions', name, 'Region.yaml'))
    myRegion = yaml.load(yamlfile)
    yamlfile.close()
    myTile = Tile(myRegion, tilex, tiley)
    myTile.log = log
    myTile()
예제 #14
0
    def cmd_untile(self):
        assert self.root

        Tile.cmd_untile(self)

        for win in self.iter_hidden():
            win.set_below(False)

        for child in self.root.childs():
            child.cont.remove(reset_window=True)

        self.root = None
예제 #15
0
파일: main.py 프로젝트: Catagen/boxo
    def __init__(self, level):
        super(Game, self).__init__()
        self.level = Level.load_level(level)
        self.background = Sprite(source='img/background.PNG')
        self.size = self.background.size
        self.player = None
        self.boxes = []

        # Initiate the game by creating tiles
        Tile.make_tiles(self.size, self.level)

        # Add bg widget first to not cover other sprites
        self.add_widget(self.background)

        # Add proper widgets for every non-empty tile in the Tile.List
        for tile in Tile.List:
            if tile.type != 'empty':
                if Tile.get_tile(tile.number - Tile.V).walkable:
                    self.add_widget(Sprite(
                        source=Tile.image_files[tile.type],
                        pos=(tile.x, tile.y)), index=2)
                else:
                    self.add_widget(Sprite(
                        source=Tile.image_files[tile.type + '_edge'],
                        pos=(tile.x, tile.y - SPRITE_EDGE_OFFSET)))

        for tile in self.level.boxspawn:
            self.boxes.append(Box(tile, self))

        self.player = Player(self.level.playerspawn, self)

        self.fps_lab = Label(
            text='FPS: ' + str(Clock.get_rfps()),
            pos=(2, self.height - 110),
            font_name=APP_FONT,
            font_size=18,
            color=(240, 240, 240, 0.8))

        self.add_widget(self.fps_lab)

        self.add_widget(Label(
            text="Level {}".format(self.level.level),
            pos=(0, self.height - 80),
            font_name=APP_FONT,
            font_size=18,
            color=(240, 240, 240, 0.8)))

        # Schedule an interval for the game update function
        Clock.schedule_interval(self.update, 1.0/60.0)
예제 #16
0
	def move(self, direction):
		if self.won or self.over:
			return

		cell = None
		tile = None



		vector = self.vectorMap(direction)
		traversals = self.buildTraverals(vector)
		moved = False

		self.prepareTiles()


		for x in traversals['x']:
			for y in traversals['y']:
				cell = (x,y)
				tile = self.grid.cellContent(cell)
				if(tile != None):
					positions = self.findFarthestPosition(cell,vector)
					next = self.grid.cellContent(positions['next'])

					if(next != None and next.value == tile.value and next.mergedFrom == None):
						merged = Tile(positions['next'], tile.value*2)
						merged.mergedFrom = [tile, next]

						self.grid.insertTile(merged)
						self.grid.removeTile(tile)
						tile.updatePosition(positions['next'])

						self.score += merged.value

						if (merged.value == self.win_score):
							sleep(10)
							self.won = True
					else:
						self.moveTile(tile, positions['farthest'])

						if (not self.positionsEqual(cell, tile)):
							moved = True
		if moved:
			self.addRandomTile()

			if not self.movesAvalable():
				self.over = True				

			self.actuate()
예제 #17
0
파일: tile_auto.py 프로젝트: Belluka/pytyle
    def cmd_tile(self):
        Tile.cmd_tile(self)

        if not self.store:
            self.store = AutoStore()

        if self.store.empty():
            active = self.monitor.get_active()

            if active:
                self.add(active)

            for win in self.monitor.iter_windows():
                if win != active:
                    self.add(win)
예제 #18
0
	def test_tile(self):
		#we'll go with zuerich
		ll = (47.376957, 8.539893)
		#for each zoom
		for z in range(0, 19):
			#get the tile coords
                        x, y, z = xyFromLatLng(ll, z, self.projection)
			#the tile we want
			tile = {'x': x, 'y': y, 'z': z, 'gid': 0, 'clientid': 0, 'priority':0 , 'style': 'map'}
			print 'input: ' + str(tile)
			#convert to mapware tile
			tile = Tile(RenderTask.RenderTask(None, tile), self.projection)
			print 'calc tile: ' + str(tile)
			tile.scale = calculateScale(tile)
			print 'calc scale: ' + str(tile)
예제 #19
0
class Map:
    
    def __init__(self):
        self.game_map = MapData().generate_coordinate_list() 
        self.tiles = 10
        self.floor = Tile("floor")
        self.wall = Wall()
    
    def SetTiles(self, canvas):
        for j in range(self.tiles+1):
            for i in range(self.tiles):
                if self.game_map[j*self.tiles+i].get("t")== 0:
                    self.floor.cr_image(canvas,i,j)
                elif self.game_map[j*self.tiles+i].get("t")== 1:
                    self.wall.cr_image(canvas,i,j)
예제 #20
0
	def init(self):
		super().init()
		self.bgColor = (255,255,255)
		self.count = 50
		self.sec = 0 
		self.min = 0
		self.timetext = "TIME : 0:00"
		self.moveup = False
		self.mute = -1

		global curk,k
		curk,k = 16,16
		global pg,pp
		pg = [2,7,10,11,14]
		pp = [1,3,4,5,9,13]
		
		Gear.init()
		Tile.init()
		Pipe.init()

		self.win = False
		self.gears = pygame.sprite.Group()
		self.pipes = pygame.sprite.Group()

		self.gears.add(Gear(330-65,180+65,-1,0))
		self.gears.add(Gear(330+65*4,180,17,0))

		self.tiles = pygame.sprite.Group()

		for i in range(4):
			for j in range(4):
				x=330+65*j
				y=180+65*i
				num=j*4+i+1
				if num != curk: self.tiles.add(Tile(x,y,num))
				if num in pg: 
					self.gears.add(Gear(x,y,num,0))
				if num in pp:
					if num == 13:
						self.pipes.add(Pipe(x,y,num,4))
					elif num == 5:
						self.pipes.add(Pipe(x,y,num,5))
					else:
						self.pipes.add(Pipe(x,y,num,1))

		self.exit = 20
		self.exittype = 1
		self.timer = 15
예제 #21
0
파일: tileMap.py 프로젝트: nhandler/cs429
    def update(self, player, enemy_group):
        
        (px, py) = player.isOutOfBounds(
            self.width, 
            self.height, 
            TileMap.TILE_LEFT, 
            TileMap.TILE_RIGHT, 
            TileMap.TILE_UP, 
            TileMap.TILE_DOWN
        )

        for enemy in enemy_group:
            enemy.isOutOfBounds(
                self.width,
                self.height,
                TileMap.TILE_LEFT,
                TileMap.TILE_RIGHT,
                TileMap.TILE_UP,
                TileMap.TILE_DOWN
            )

        if (px == TileMap.TILE_LEFT and self.x - 1 >= 0 and self.tilemapping[self.x-1][self.y]):
            self.x -= 1
            self.save(player)
            self.tile = Tile(self.save_path, self.tilemapping[self.x][self.y])
            player.coords = (self.width-1, py)
            return False
        elif (px == TileMap.TILE_RIGHT and self.x + 1 < len(self.tilemapping) and self.tilemapping[self.x+1][self.y]):
            self.x += 1
            self.save(player)
            self.tile = Tile(self.save_path, self.tilemapping[self.x][self.y])
            player.coords = (0, py)
            return False
        
        if (py == TileMap.TILE_UP and self.y - 1 >= 0 and self.tilemapping[self.x][self.y-1]):
            self.y -= 1
            self.save(player)
            self.tile = Tile(self.save_path, self.tilemapping[self.x][self.y])
            player.coords = (px, self.height-1)
            return False
        elif (py == TileMap.TILE_DOWN and self.y + 1 < len(self.tilemapping[self.x]) and self.tilemapping[self.x][self.y+1]):
            self.y += 1
            self.save(player)
            self.tile = Tile(self.save_path, self.tilemapping[self.x][self.y])
            player.coords = (px, 0)
            return False
        
        return True
예제 #22
0
 def test_tile(self):
     # we'll go with saramento (west coast bias)
     ll = (38.555556, -121.468889)
     # for each zoom
     for z in range(0, 19):
         # get the tile coords
         x, y, z = xyFromLatLng(ll, z, self.projection)
         print "Tile info", x, y, z
         # the tile we want
         tile = {"x": x, "y": y, "z": z, "gid": 0, "clientid": 0, "priority": 0, "style": "map"}
         print "input: " + str(tile)
         # convert to mapware tile
         tile = Tile(RenderTask.RenderTask(None, tile), self.projection)
         print "calc tile: " + str(tile)
         tile.scale = calculateScale(tile)
         print "calc scale: " + str(tile)
예제 #23
0
 def test_tile(self):
    #we'll go with saramento (west coast bias)
    ll = (38.555556, -121.468889)
    #for each zoom
    for z in range(0, 19):
       #get the tile coords
       x, y, z = xyFromLatLng(ll, z, self.projection)
       print "Tile info", x, y, z
       #the tile we want
       tile = {'x': x, 'y': y, 'z': z, 'gid': 0, 'clientid': 0, 'priority':0 , 'style': 'map'}
       print 'input: ' + str(tile)
       #convert to mapware tile
       tile = Tile(RenderTask.RenderTask(None, tile), self.projection)
       print 'calc tile: ' + str(tile)
       tile.scale = calculateScale(tile)
       print 'calc scale: ' + str(tile)
예제 #24
0
    def __init__(self, event_data):
        self._event_data = event_data
        self._stop = False

        assert 'event' in self._event_data

        if hasattr(self, self._event_data['event']):
            getattr(self, self._event_data['event'])()
        else:
            print 'Unrecognized event: %s' % self._event_data['event']
            return

        ptxcb.Window.exec_queue()
        Tile.exec_queue()

        ptxcb.connection.push()
예제 #25
0
파일: objects.py 프로젝트: Catagen/boxo
    def move(self, direction):

        if direction == 12:
            tile_difference = Tile.V
            speed = self.speed_y
        elif direction == 3:
            tile_difference = Tile.H
            speed = self.speed_x
        elif direction == 6:
            tile_difference = -Tile.V
            speed = -self.speed_y
        elif direction == 9:
            tile_difference = -Tile.H
            speed = -self.speed_x
        else:
            raise ValueError("Incorrect direction in Box.move()")

        target_tile = Tile.get_tile(self.tile + tile_difference)

        if target_tile.walkable:

            for box in self.game.boxes:
                if box.tile == self.tile + tile_difference:
                    return False

            if direction in (6, 12): self.velocity_y = speed
            if direction in (9, 3): self.velocity_x = speed

            self.tile += tile_difference
            return True

        return False
예제 #26
0
	def __build(self, mods):
		grid = []

		for x in range(config.height):
			grid.append([])

			for y in range(config.width):
				t = Tile(x, y)

				# See if these coords have a modifier
				if (x, y) in mods:
					t.modifier = mods[(x, y)]

				grid[x].append(t)

		return grid
예제 #27
0
    def get_surrounding_tiles(base_node):
        
        array =(
            (base_node.number + N),
            (base_node.number + NE),
            (base_node.number + E),
            (base_node.number + SE),
            (base_node.number + S),
            (base_node.number + SW),
            (base_node.number + W),
            (base_node.number + NW),
            )

        tiles = []

        onn = base_node.number 
        diagonals = [onn + NE, onn + NW, onn + SE, onn + SW]

        for tile_number in array:

            surrounding_tile = Tile.get_tile(tile_number)
            
            if tile_number not in range(1, Tile.total_tiles + 1):
                continue

            if surrounding_tile.walkable and surrounding_tile not in closed_list:
                # tiles.append(surrounding_tile) # Diagonal movement
                tiles = blocky(tiles, diagonals, surrounding_tile)

        return tiles
예제 #28
0
    def gain_knowledge_of_terrain_of_tile(self, tile, position, depth):
        """
        Writes the entity memory of a tile, to the memory map.

        If position is out of range, do nothing
        """
        x, y = position
        self._init_memory_map_if_not_set(self.parent.dungeon_level.value)
        try:
            if (not self._memory_map[depth].tile_matrix[y][x].get_terrain() or
                    self._memory_map[depth].tile_matrix[y][x].get_terrain().has("is_unknown")):
                new_tile = Tile()
                new_tile.add(tile.get_terrain())
                self._memory_map[depth].tile_matrix[y][x] = new_tile
        except IndexError:
            pass
예제 #29
0
파일: level.py 프로젝트: kspi/basement
 def from_strings(lines):
     level = Level()
     for y, line in enumerate(lines):
         for x, ch in enumerate(line):
             if ch != ' ':
                 level[x, y] = Tile.from_symbol(ch)(level, x, y)
     return level
예제 #30
0
    def test_foreground(self):
        creature = CreatureSprite(PLAYER_IMAGE, (0, 0), (60, 60), Direction.up)
        tile = Tile(None, None)
        tile.height = 2
        tile.width = 2
        tile.background.append([0, 0])
        tile.background.append([0, 0])
        tile.foreground.append([0, 0])
        tile.foreground.append([1, 0])
        tile.top.append([0, 0])
        tile.top.append([0, 0])
        
        creature.move(Direction.right, tile)
        self.assertEqual((0, 0), creature.coords)

        creature.move(Direction.down, tile)
        self.assertEqual((0, 1), creature.coords)
예제 #31
0
 def clearTile(self, coordinate):
     if type(coordinate) is str:
         mailbox = Tile.coordinateToMailbox(coordinate)
     self.board[mailbox].piece = None
     print("Tile", coordinate, "cleared successfully.")
예제 #32
0
def test_create_board():
    rows = 10
    cols = 10

    created_board = Board()
    expected_board = {
        0: [
            Tile(0, 0),
            Tile(0, 1),
            Tile(0, 2),
            Tile(0, 3),
            Tile(0, 4),
            Tile(0, 5),
            Tile(0, 6),
            Tile(0, 7),
            Tile(0, 8),
            Tile(0, 9)
        ],
        1: [
            Tile(1, 0),
            Tile(1, 1),
            Tile(1, 2),
            Tile(1, 3),
            Tile(1, 4),
            Tile(1, 5),
            Tile(1, 6),
            Tile(1, 7),
            Tile(1, 8),
            Tile(1, 9)
        ],
        2: [
            Tile(2, 0),
            Tile(2, 1),
            Tile(2, 2),
            Tile(2, 3),
            Tile(2, 4),
            Tile(2, 5),
            Tile(2, 6),
            Tile(2, 7),
            Tile(2, 8),
            Tile(2, 9)
        ],
        3: [
            Tile(3, 0),
            Tile(3, 1),
            Tile(3, 2),
            Tile(3, 3),
            Tile(3, 4),
            Tile(3, 5),
            Tile(3, 6),
            Tile(3, 7),
            Tile(3, 8),
            Tile(3, 9)
        ],
        4: [
            Tile(4, 0),
            Tile(4, 1),
            Tile(4, 2),
            Tile(4, 3),
            Tile(4, 4),
            Tile(4, 5),
            Tile(4, 6),
            Tile(4, 7),
            Tile(4, 8),
            Tile(4, 9)
        ],
        5: [
            Tile(5, 0),
            Tile(5, 1),
            Tile(5, 2),
            Tile(5, 3),
            Tile(5, 4),
            Tile(5, 5),
            Tile(5, 6),
            Tile(5, 7),
            Tile(5, 8),
            Tile(5, 9)
        ],
        6: [
            Tile(6, 0),
            Tile(6, 1),
            Tile(6, 2),
            Tile(6, 3),
            Tile(6, 4),
            Tile(6, 5),
            Tile(6, 6),
            Tile(6, 7),
            Tile(6, 8),
            Tile(6, 9)
        ],
        7: [
            Tile(7, 0),
            Tile(7, 1),
            Tile(7, 2),
            Tile(7, 3),
            Tile(7, 4),
            Tile(7, 5),
            Tile(7, 6),
            Tile(7, 7),
            Tile(7, 8),
            Tile(7, 9)
        ],
        8: [
            Tile(8, 0),
            Tile(8, 1),
            Tile(8, 2),
            Tile(8, 3),
            Tile(8, 4),
            Tile(8, 5),
            Tile(8, 6),
            Tile(8, 7),
            Tile(8, 8),
            Tile(8, 9)
        ],
        9: [
            Tile(9, 0),
            Tile(9, 1),
            Tile(9, 2),
            Tile(9, 3),
            Tile(9, 4),
            Tile(9, 5),
            Tile(9, 6),
            Tile(9, 7),
            Tile(9, 8),
            Tile(9, 9)
        ],
    }

    for i in range(rows):
        for j in range(cols):
            assert created_board.board[i][j].status_code == expected_board[i][
                j].status_code

    assert created_board.board[0][0].x == 0
    assert created_board.board[0][0].y == 0

    assert created_board.board[4][7].x == 4
    assert created_board.board[4][7].y == 7
예제 #33
0
def test__init__():
    tile = Tile(50)
    assert tile.DIAMETER == 50
    assert tile.is_black
예제 #34
0
def test_set_white():
    tile = Tile(50)
    tile.set_white()
    assert not tile.is_black
예제 #35
0
    def __init__(self, items, *args, **kwargs):
        tile = Tile('%', foreground="YELLOW", background="BLACK", bold=True)
        super(ItemPickup, self).__init__(tile, *args, **kwargs)

        self.inventory.extend(items)
예제 #36
0
    def test_initialize_board_padding2(self):
        # Test initializing board with the need for padding less readily apparent

        # Invalid json board representation
        valid_json = json.loads(
            "[[1, 3, 4], [1, 2], [1, 0, 3, 5, 4], [0, 2, 3]]")

        # Board obtained from the initialize_board function
        result_board = xboard.initialize_board(valid_json)

        # Test properties of the board
        self.assertTrue(isinstance(result_board, Board))
        self.assertEquals(result_board.rows, 4)
        self.assertEquals(result_board.cols, 5)
        self.assertEquals(result_board.tile_no, 20)

        # Expected tile dict
        expected_tiles = \
        {
            Position(0, 0): Tile(1),
            Position(0, 1): Tile(3),
            Position(0, 2): Tile(4),
            Position(0, 3): Hole(),
            Position(0, 4): Hole(),
            Position(1, 0): Tile(1),
            Position(1, 1): Tile(2),
            Position(1, 2): Hole(),
            Position(1, 3): Hole(),
            Position(1, 4): Hole(),
            Position(2, 0): Tile(1),
            Position(2, 1): Hole(),
            Position(2, 2): Tile(3),
            Position(2, 3): Tile(5),
            Position(2, 4): Tile(4),
            Position(3, 0): Hole(),
            Position(3, 1): Tile(2),
            Position(3, 2): Tile(3),
            Position(3, 3): Hole(),
            Position(3, 4): Hole()
        }

        # Verify all the positions in the board are the same as expected
        self.assertCountEqual(expected_tiles.keys(), result_board.tiles.keys())

        # Verify that all tiles have the correct number of fish
        for key in expected_tiles:
            tile = expected_tiles[key]

            # Tile on initialized board
            actual_tile = result_board.get_tile(key)

            # Assert both tiles are the same type
            self.assertEqual(tile.is_tile, actual_tile.is_tile)

            # If the tiles are both tiles, assert that the ones on the board
            # have the expected number of fish
            if tile.is_tile:
                self.assertEqual(tile.fish_no, actual_tile.fish_no)
예제 #37
0
 def reinit(self):
     if self.variation == HANGAR:
         self.size = HANGAR_SIZE
         self.ships = [None for _ in range(self.size[0] * self.size[1])]
         self.cells = [
             Tile(
                 self.variation,
                 i,
                 (
                     (i % self.size[0])*(HANGAR_BLOCK_SIZE[0] + HANGAR_BLOCK_PADDING) + HANGAR_RECT_OBJ_POS[0],
                     (i // self.size[0])*(HANGAR_BLOCK_SIZE[1] + HANGAR_BLOCK_PADDING) + HANGAR_RECT_OBJ_POS[1]
                 )
             )
             for i in range(self.size[0] * self.size[1])
         ]
         self.rect = pygame.Rect(HANGAR_RECT_POS, HANGAR_RECT_SIZE)
         self.surf = pygame.Surface(HANGAR_RECT_SIZE)
         self.surf.fill(COLOR_HANGAR)
         self.rect_outline = pygame.Rect(HANGAR_RECT_OUTLINE_POS, HANGAR_RECT_OUTLINE_SIZE)
         self.surf_outline = pygame.Surface(HANGAR_RECT_OUTLINE_SIZE)
         self.surf_outline.fill(COLOR_HANGAR_OUTLINE)
         self.surf.set_alpha(100)
         self.surf_outline.set_alpha(100)
     if self.variation == BATTLE:
         self.size = BATTLE_SIZE
         self.ships = [None for _ in range(self.size[0] * self.size[1])]
         self.cells = [
             Tile(
                 self.variation,
                 i,
                 (
                     (i % self.size[0])*(BATTLE_BLOCK_SIZE[0] + BATTLE_BLOCK_PADDING) + BATTLE_RECT_OBJ_POS[0],
                     (i // self.size[0])*(BATTLE_BLOCK_SIZE[1] + BATTLE_BLOCK_PADDING) + BATTLE_RECT_OBJ_POS[1]
                 )
             )
             for i in range(self.size[0] * self.size[1])
         ]
         self.rect = pygame.Rect(BATTLE_RECT_POS, BATTLE_RECT_SIZE)
         self.surf = pygame.Surface(BATTLE_RECT_SIZE)
         self.surf.fill(COLOR_BATTLE)
         self.rect_outline = pygame.Rect(BATTLE_RECT_OUTLINE_POS, BATTLE_RECT_OUTLINE_SIZE)
         self.surf_outline = pygame.Surface(BATTLE_RECT_OUTLINE_SIZE)
         self.surf_outline.fill(COLOR_BATTLE_OUTLINE)
         self.surf.set_alpha(100)
         self.surf_outline.set_alpha(100)
     if self.variation == MARKET:
         self.size = MARKET_SIZE
         self.ships = [None for _ in range(self.size[0] * self.size[1])]
         self.cells = [
             Tile(
                 self.variation,
                 i,
                 (
                     (i % self.size[0])*(MARKET_BLOCK_SIZE[0] + MARKET_BLOCK_PADDING) + MARKET_RECT_OBJ_POS[0],
                     (i // self.size[0])*(MARKET_BLOCK_SIZE[1] + MARKET_BLOCK_PADDING) + MARKET_RECT_OBJ_POS[1]
                 )
             )
             for i in range(self.size[0] * self.size[1])
         ]
         self.rect = pygame.Rect(MARKET_RECT_POS, MARKET_RECT_SIZE)
         self.surf = pygame.Surface(MARKET_RECT_SIZE)
         self.surf.fill(COLOR_MARKET)
         self.rect_outline = pygame.Rect(MARKET_RECT_OUTLINE_POS, MARKET_RECT_OUTLINE_SIZE)
         self.surf_outline = pygame.Surface(MARKET_RECT_OUTLINE_SIZE)
         self.surf_outline.fill(COLOR_MARKET_OUTLINE)
         self.surf.set_alpha(100)
         self.surf_outline.set_alpha(100)
예제 #38
0
def load_sea_monster():
    lines = sea_monster.splitlines()
    return Tile((np.array([list(k) for k in lines]) == "#").astype(np.int))
예제 #39
0
class Enemy:
    def __init__(self,
                 screen,
                 x,
                 y,
                 enemy_type,
                 colliding_tiles,
                 width,
                 height,
                 images=[]):
        self.tile = Tile(screen, 0, 0, '', width, height, images)

        self.enemy_type = enemy_type

        self.tile.rect.x = x
        self.tile.rect.y = y
        self.colliding_tiles = colliding_tiles
        self.__visible_tiles = []

        self.frame = 0
        self.active = False
        self.alive = True
        self.movement_factor = -1
        self.ground_rect = pygame.Rect(self.tile.rect.x, self.tile.rect.y,
                                       width, height)
        self.ground_rect.top = self.tile.rect.bottom

    def set_visible_tiles(self, visible_tiles):
        self.__visible_tiles = visible_tiles

    def set_max_position(self, total_width, total_height):
        self.total_width = total_width
        self.total_height = total_height

    def update(self):
        if self.active:
            on_ground = False

            for tile in self.__visible_tiles:
                if tile.tile_type in self.colliding_tiles and self.alive:
                    if self.tile.rect.bottom != tile.rect.top:
                        if self.tile.rect.colliderect(tile.rect):
                            if self.movement_factor < 0:
                                self.tile.rect.left = tile.rect.right
                            elif self.movement_factor > 0:
                                self.tile.rect.right = tile.rect.left

                            self.flip()

                    if self.ground_rect.top == tile.rect.top:
                        if self.ground_rect.colliderect(tile.rect):
                            on_ground = True
            if self.alive:
                self.frame += 1
                self.tile.rect.x += self.movement_factor

            if not on_ground and self.alive:
                self.tile.rect.y += 1

            self.ground_rect.top = self.tile.rect.bottom
            self.ground_rect.x = self.tile.rect.x

            if self.frame % 30 == 0 and self.alive:
                if self.enemy_type == "goomba":
                    if self.tile.image is self.tile.images["goomba_two"]:
                        self.tile.image = self.tile.images["goomba_one"]
                    else:
                        self.tile.image = self.tile.images["goomba_two"]

    def render(self, x, y):
        if self.active:
            self.tile.render(x, y)

    def flip(self):
        self.movement_factor *= -1

    def death(self):
        if self.alive:

            if self.enemy_type == "goomba":
                pygame.mixer.Channel(1).play(
                    pygame.mixer.Sound('assets/sound/stomp.ogg'))
                self.tile.image = pygame.image.load(
                    'assets/images/enemies/goomba/goombaDead.gif')
                self.tile.rect.y += 20
            if self.enemy_type == "koopa":
                pygame.mixer.Channel(1).play(
                    pygame.mixer.Sound('assets/sound/kick.ogg'))
                self.tile.image = pygame.image.load(
                    'assets/images/enemies/koopa/shell.gif')
                self.tile.rect.y += 20
                self.enemy_type = "shell"
            self.alive = False
예제 #40
0
 def test_move_down_gives_a_board_with_the_open_tile_in_the_bottom(self):
     layout = [[1, 2, 3], [8, 6, 4], [7, 0, 5]]
     self.assertEqual(Mover.move_down(Tile()).layout, layout)
예제 #41
0
 def test_move_up_yields_nothing(self):
     self.assertEqual(Mover.move_up(Mover.move_up(Tile())), None)
예제 #42
0
 def test_move_up_gives_a_board_when_the_blank_was_moved_up(self):
     expectedTile = [[1, 0, 3], [8, 2, 4], [7, 6, 5]]
     self.assertEqual(Mover.move_up(Tile()).layout, expectedTile)
예제 #43
0
 def initialize_tiles(self):
     tiles = [[Tile(True) for y in range(self.height)]
              for x in range(self.width)]
     return tiles
예제 #44
0
 def test_move_left_gives_a_board_with_a_square_in_the_leftmost_row(self):
     layout = [[1, 2, 3], [0, 8, 4], [7, 6, 5]]
     self.assertEqual(Mover.move_left(Tile()).layout, layout)
예제 #45
0
def test_flip():
    tile = Tile(50)
    tile.flip()
    assert not tile.is_black
예제 #46
0
 def test_move_right_gives_a_board_with_a_square_in_the_left(self):
     layout = [[1, 2, 3], [8, 4, 0], [7, 6, 5]]
     self.assertEqual(Mover.move_right(Tile()).layout, layout)
예제 #47
0
def test_set_black():
    tile = Tile(50)
    tile.is_black = False
    tile.set_black()
    assert tile.is_black
예제 #48
0
 def __init__(self):
     self.tile = None
     self.match = Tile(up=0, right=0, down=0, left=0)
예제 #49
0
def test__eq__():
    tile_1 = Tile(50)
    tile_2 = Tile(50)
    assert tile_1 == tile_2
예제 #50
0
    def update_bounding_box(self):
        '''
        '''

        # first, grab the meta data, then calculate the bounding box
        directory = self._directory
        metadata_file = os.path.join(directory, settings.METADATA_FILE)
        image_coordinates_file = os.path.join(directory,
                                              settings.IMAGE_COORDINATES_FILE)

        #
        # read meta data
        #
        metadata = {}

        with open(metadata_file) as f:
            for l in f.readlines():
                l = l.strip()
                values = l.split()
                metadata[values[0].strip(':')] = values[-1]

        #
        # we do want to parse some of the meta data
        #
        width = int(metadata['Width'].strip('px'))
        height = int(metadata['Height'].strip('px'))

        #
        # index tiles
        #
        tiles = {}

        with open(image_coordinates_file) as f:

            # we need to remove duplicate entries here and only grab the last
            # 61
            lines = FoV.filter_duplicate_lines(f.readlines())[-61:]

            for i, l in enumerate(lines):

                # if i>60:
                #   # only look at the first 61 entries since we do not use
                #   # other thumbnails
                #   break
                tile = Tile.from_string(l)
                # update width and height
                tile.width = width
                tile.height = height
                tiles[tile.id] = tile

        self._tiles = tiles
        self._metadata = metadata

        # now the bounding box
        width = -sys.maxsize
        height = -sys.maxsize

        minX = sys.maxsize
        minY = sys.maxsize
        maxX = -sys.maxsize
        maxY = -sys.maxsize

        for i in self._tiles:
            image = self._tiles[i]
            minX = min(minX, image._tx)
            minY = min(minY, image._ty)
            maxX = max(maxX, image._tx)
            maxY = max(maxY, image._ty)

        width = maxX - minX + image.width
        height = maxY - minY + image.height

        self._tx = minX
        self._ty = minY

        self._width = width
        self._height = height
예제 #51
0
def drunk_walk(width, height, tiles, tiles_data, gen_data):

    # Setup variables needed for the process.
    steps = gen_data['steps']
    room_min_size = math.sqrt(gen_data['modes']['room']['steps']['min'])
    room_max_size = math.sqrt(gen_data['modes']['room']['steps']['max'])
    directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]

    # First start with a map full of walls.
    fill_map_with_walls(width, height, tiles, tiles_data)

    # Pick a random starting point closer to the center of the map.
    start_x = random.randint(width / 4, width - (width / 4))
    start_y = random.randint(height / 4, height - (height / 4))
    current_x = start_x
    current_y = start_y

    # Make a nice open room at the starting point.
    room_width = random.randint(room_min_size, room_max_size)
    room_height = random.randint(room_min_size, room_max_size)
    add_room(start_x, start_y, room_width, room_height, width - 1, height - 1,
             tiles, tiles_data, gen_data)

    while steps > 0:
        # Randomly determine the next course of action to take(random walk or room).
        choice = pick_by_chance(gen_data['modes'])

        # Random/corridor walk.
        if choice != 'room':
            dirr = random.randrange(0, len(directions))
            walk_min = gen_data['modes']['corridor']['steps']['min']
            walk_max = gen_data['modes']['corridor']['steps']['max']
            walk_range = random.randint(walk_min, walk_max)
            if choice == 'random':
                walk_min = gen_data['modes']['random']['steps']['min']
                walk_max = gen_data['modes']['random']['steps']['max']
            for i in range(walk_range):
                if choice == 'random':
                    dirr = random.randrange(0, len(directions))
                new_x = current_x + directions[dirr][0]
                new_y = current_y + directions[dirr][1]
                if new_x > 1 and new_x < width - 1 and new_y > 1 and new_y < height - 1:
                    if not tiles[new_x][new_y].walkable:
                        tiles[new_x][new_y] = create_floor(
                            new_x, new_y, tiles_data, gen_data)
                    current_x = new_x
                    current_y = new_y
                    steps -= 1

        else:
            # Create randomly sized room at current coords.
            room_width = random.randint(room_min_size, room_max_size)
            room_height = random.randint(room_min_size, room_max_size)
            add_room(current_x, current_y, room_width, room_height, width - 1,
                     height - 1, tiles, tiles_data, gen_data)
            steps -= room_width * room_height

        if steps <= 0:
            # Check if enough floors were created
            # If not go back to the start position to create more.
            floor_count = 0
            for x in range(width):
                for y in range(height):
                    if tiles[x][y].walkable:
                        floor_count += 1

            if floor_count < gen_data['steps'] / 2:
                steps += ((gen_data['steps'] / 2) - floor_count)
                current_x = start_x - 1
                current_y = start_y - 1

    # Add stairs to an open position a distance away from the start position.
    while True:
        x = random.randrange(0, width)
        y = random.randrange(0, height)
        if tiles[x][y].distance_to(tiles[start_x][start_y]) > 20:
            if tiles[x][y].walkable:
                tiles[x][y] = Tile(x,
                                   y,
                                   'Stairs',
                                   tiles_data['Stairs']['image'],
                                   tiles_data['Stairs']['color_fg'],
                                   tiles_data['Stairs']['color_bg'],
                                   tiles_data['Stairs']['walkable'],
                                   tiles_data['Stairs']['blocksLOS'],
                                   is_stairs=True)
                tiles[x][y].explored = True
                break

    return start_x, start_y
예제 #52
0
파일: gamemap.py 프로젝트: farzanab/DunGen
    def makemap1(self, spec_dict, monster_dict):
        """
		Use a (mostly) randomised algorithm to generate a map.
		
		Generate number of rooms of each type, and try to fit them.
		"""
        tries = []
        test = 0
        limit = 1
        tim1 = time.process_time()
        while test < limit:
            num_small, num_medium, num_large, is_random = gen_num_rooms(
                spec_dict, tries)

            if num_small is None:
                break
            test += 1
            if is_random:
                limit = 100
                limit2 = 250
            else:
                limit2 = 2000
            num_rooms = num_small + num_medium + num_large

            room_sizes = gen_room_dict(spec_dict, monster_dict, num_small,
                                       num_medium, num_large)
            for test2 in range(limit2):
                self.rooms = []
                self.tiles = [[Tile('wall') for y in range(self.height)]
                              for x in range(self.width)]
                for i in range(num_rooms):
                    if i < num_large:
                        size = 'large'
                    elif i < num_large + num_medium:
                        size = 'medium'
                    else:
                        size = 'small'
                    trial = 0
                    flag = True
                    while flag:
                        trial += 1
                        if trial > 200:
                            break
                        width, height, max_monsters = dimension_gen(
                            size, room_sizes)
                        x = randint(0, self.width - width - 1)
                        y = randint(0, self.height - height - 1)

                        new_room = Room(x, y, width, height, max_monsters)

                        for room in self.rooms:
                            if new_room.intersect(room):
                                break
                        else:
                            flag = False
                            self.create_room(new_room)
                            self.place_obstacles(new_room, size)
                            if i > 0:
                                x1, y1 = new_room.get_point()
                                x2, y2 = self.rooms[-2].get_point()

                                if randint(0, 1):
                                    self.hor_tun(x1, x2, y1)
                                    self.ver_tun(y1, y2, x2)
                                else:
                                    self.ver_tun(y1, y2, x1)
                                    self.hor_tun(x1, x2, y2)
                    if flag:
                        break
                else:
                    test = limit + 1
                    break

        if test == limit or num_small is None:
            print(time.process_time() - tim1)
            sys.exit("Inadequate map size")
        for y in range(self.height):
            for x in range(self.width):
                neighbours = []
                if x > 0 and y > 0:
                    neighbours.extend([
                        self.tiles[x - 1][y - 1], self.tiles[x][y - 1],
                        self.tiles[x - 1][y]
                    ])
                if x < self.width - 1 and y > 0:
                    neighbours.extend([
                        self.tiles[x + 1][y - 1], self.tiles[x][y - 1],
                        self.tiles[x + 1][y]
                    ])
                if x > 0 and y < self.height - 1:
                    neighbours.extend([
                        self.tiles[x - 1][y + 1], self.tiles[x][y + 1],
                        self.tiles[x - 1][y]
                    ])
                if x < self.width - 1 and y < self.height - 1:
                    neighbours.extend([
                        self.tiles[x + 1][y + 1], self.tiles[x][y + 1],
                        self.tiles[x + 1][y]
                    ])
                if all([tile.type == 'wall' for tile in neighbours]):
                    self.tiles[x][y].set_blank()
예제 #53
0
    def movePiece(self, mailbox, destination):
        mailbox = Tile.coordinateToMailbox(mailbox)
        destination = Tile.coordinateToMailbox(destination)
        movingPiece = self.board[mailbox].piece
        if movingPiece is None:
            print('Illegal Move, chosen tile is empty.')
            return False
        if movingPiece.team != self.playerTurnToPlay:
            print('Illegal Move, piece is not yours to move.')
            return False
        targetPiece = self.board[destination].piece
        for (origin, moveType, target) in movingPiece.listAllLegalMoves():
            if destination == target:
                movingPiece.mailbox = destination

                if moveType == 'move':
                    self.board[destination].piece = movingPiece
                    self.board[mailbox].piece = None

                elif moveType == 'doubleMove':
                    self.board[destination].piece = movingPiece
                    self.board[mailbox].piece = None
                    if movingPiece.team == 'white':
                        self.enPassantSquare = destination - 10
                    else:
                        self.enPassantSquare = destination + 10
                    self.generateEnPassantMoves()

                elif moveType == 'capture':
                    self.deadPieces[targetPiece.team][targetPiece.name] += 1
                    self.board[destination].piece = movingPiece
                    self.board[mailbox].piece = None
                    self.pieceList[targetPiece.team][targetPiece.name]

                elif moveType == 'castle':
                    if movingPiece.team == 'white':
                        if destination == 23:
                            targetRook = self.board[21].piece
                            targetRook.mailbox = 23
                            self.board[destination].piece = movingPiece
                            self.board[mailbox].piece = None
                            self.board[23].piece = targetRook
                            self.board[21].piece = None
                        elif destination == 27:
                            targetRook = self.board[28].piece
                            targetRook.mailbox = 25
                            self.board[destination].piece = movingPiece
                            self.board[mailbox].piece = None
                            self.board[25].piece = targetRook
                            self.board[28].piece = None

                    elif movingPiece.team == 'black':
                        if destination == 93:
                            targetRook = self.board[91].piece
                            targetRook.mailbox = 93
                            self.board[destination].piece = movingPiece
                            self.board[mailbox].piece = None
                            self.board[93].piece = targetRook
                            self.board[91].piece = None
                        elif destination == 97:
                            targetRook = self.board[98].piece
                            targetRook.mailbox = 95
                            self.board[destination].piece = movingPiece
                            self.board[mailbox].piece = None
                            self.board[95].piece = targetRook
                            self.board[98].piece = None

                elif moveType == 'enPassant':
                    if movingPiece.team == 'white':  # If a white pawn en passant captures a black one
                        targetPiece = self.board[destination - 10].piece
                        self.board[destination].piece = movingPiece
                        self.board[mailbox].piece = None
                        self.board[destination - 10].piece = None
                        self.deadPieces[targetPiece.team][
                            targetPiece.name] += 1

                    elif movingPiece.team == 'black':  # If a black pawn en passant captures a white one
                        targetPiece = self.board[destination + 10].piece
                        self.board[destination].piece = movingPiece
                        self.board[mailbox].piece = None
                        self.board[destination + 10].piece = None
                        self.deadPieces[targetPiece.team][
                            targetPiece.name] += 1

                return True  # True for success, false for failure
        print('Illegal Move.')
        return False
예제 #54
0
 def createTiles(self):
     for copy_tiles in range(1, 4):
         for shape in Shape:
             for color in Color:
                 tile2 = Tile(shape, color)
                 self.tile_list.append(tile2)
예제 #55
0
 def move_horizontally(tile, direction, rowIndex, squareIndex):
     if (squareIndex == direction + 1):
         return None
     return Tile.swap(Tile.duplicate(tile), rowIndex,
                      squareIndex + direction, rowIndex, squareIndex)
예제 #56
0
 def get_tiles(self) -> list:
     return [Tile(num, self.color) for num in self.numbers]
예제 #57
0
def test_constructor():
    new_tile = Tile(100, 50)
    assert new_tile.x == 100
    assert new_tile.y == 50
예제 #58
0
 def test_move_down_has_the_empty_row_in_the_middle(self):
     expectedTile = [[1, 2, 3], [8, 0, 4], [7, 6, 5]]
     self.assertEqual(
         Mover.move_down(Mover.move_up(Tile())).layout, expectedTile)
예제 #59
0
 def test_move_right_yields_nothing(self):
     layout = [[1, 2, 3], [8, 4, 0], [7, 6, 5]]
     self.assertEqual(Mover.move_right(Tile()).layout, layout)
예제 #60
0
def getRandomizedBoard():
    # Return a list with all the values of the position of each bomb.
    board = []
    for x in range(BOARDWIDTH):
        column = []
        for y in range(BOARDHEIGHT):
            if randint(1, 101) < 16:
                block = Tile(True, 0)
            else:
                block = Tile(False, 0)
            column.append(block)
        board.append(column)
    for x in range(BOARDWIDTH):
        for y in range(BOARDHEIGHT):
            num = 0
            if board[x][y].getMine() == True:
                num = 0
            elif x == 0 and y == 0:
                if board[1][0].getMine() == True:
                    num += 1
                if board[0][1].getMine() == True:
                    num += 1
                if board[1][1].getMine() == True:
                    num += 1
            elif x == 0 and y == BOARDHEIGHT - 1:
                if board[0][BOARDHEIGHT - 2].getMine() == True:
                    num += 1
                if board[1][BOARDHEIGHT - 2].getMine() == True:
                    num += 1
                if board[1][BOARDHEIGHT - 1].getMine() == True:
                    num += 1
            elif y == 0 and x == BOARDWIDTH - 1:
                if board[BOARDWIDTH - 2][0].getMine() == True:
                    num += 1
                if board[BOARDWIDTH - 2][1].getMine() == True:
                    num += 1
                if board[BOARDWIDTH - 1][1].getMine() == True:
                    num += 1
            elif y == BOARDHEIGHT - 1 and x == BOARDWIDTH - 1:
                if board[BOARDWIDTH - 2][BOARDHEIGHT - 1].getMine() == True:
                    num += 1
                if board[BOARDWIDTH - 2][BOARDHEIGHT - 2].getMine() == True:
                    num += 1
                if board[BOARDWIDTH - 1][BOARDHEIGHT - 2].getMine() == True:
                    num += 1
            elif x == 0:
                if board[0][y - 1].getMine() == True:
                    num += 1
                if board[1][y - 1].getMine() == True:
                    num += 1
                if board[1][y].getMine() == True:
                    num += 1
                if board[1][y + 1].getMine() == True:
                    num += 1
                if board[0][y + 1].getMine() == True:
                    num += 1
            elif x == BOARDWIDTH - 1:
                if board[BOARDWIDTH - 1][y - 1].getMine() == True:
                    num += 1
                if board[BOARDWIDTH - 2][y - 1].getMine() == True:
                    num += 1
                if board[BOARDWIDTH - 2][y].getMine() == True:
                    num += 1
                if board[BOARDWIDTH - 2][y + 1].getMine() == True:
                    num += 1
                if board[BOARDWIDTH - 1][y + 1].getMine() == True:
                    num += 1
            elif y == 0:
                if board[x - 1][0].getMine() == True:
                    num += 1
                if board[x - 1][1].getMine() == True:
                    num += 1
                if board[x][1].getMine() == True:
                    num += 1
                if board[x + 1][1].getMine() == True:
                    num += 1
                if board[x + 1][0].getMine() == True:
                    num += 1
            elif y == BOARDHEIGHT - 1:
                if board[x - 1][BOARDHEIGHT - 1].getMine() == True:
                    num += 1
                if board[x - 1][BOARDHEIGHT - 2].getMine() == True:
                    num += 1
                if board[x][BOARDHEIGHT - 2].getMine() == True:
                    num += 1
                if board[x + 1][BOARDHEIGHT - 2].getMine() == True:
                    num += 1
                if board[x + 1][BOARDHEIGHT - 1].getMine() == True:
                    num += 1
            else:
                if board[x - 1][y - 1].getMine() == True:
                    num += 1
                if board[x][y - 1].getMine() == True:
                    num += 1
                if board[x + 1][y - 1].getMine() == True:
                    num += 1
                if board[x + 1][y].getMine() == True:
                    num += 1
                if board[x + 1][y + 1].getMine() == True:
                    num += 1
                if board[x][y + 1].getMine() == True:
                    num += 1
                if board[x - 1][y + 1].getMine() == True:
                    num += 1
                if board[x - 1][y].getMine() == True:
                    num += 1
            board[x][y].changeNumber(num)
    return board