def decide_drop_tile(self, player, new_tile, neighbors, game): self.begin_decision() state = utils.dnn_encode_state(player, neighbors) if self.__model.history_waiting: self.__model.update_transition(state, self.__pending_reward) valid_actions = [] tiles = player.hand if new_tile is None else player.hand + [new_tile] for tile in tiles: valid_actions.append(Tile.convert_tile_index(tile)) action_filter = np.zeros(n_decisions) action_filter[valid_actions] = 1 h_drop_tile = self.__hmodel.decide_drop_tile(player, new_tile, neighbors, game) drop_tile = self.__model.decide_drop_tile(player, new_tile, neighbors, game) action = Tile.convert_tile_index(drop_tile) if self.__is_train: self.__model.update_history(state, action, action_filter) if drop_tile == h_drop_tile: self.__pending_reward = REWARD_SAME else: self.__pending_reward = REWARD_DIFF self.end_decision() return drop_tile
def test_LetterScoringHeuristicScoreWord_QUEEN_ReturnsFourteen(self): # Arrange expected = 14 hand = [] q = "Q" u = "U" e = "E" n = "N" tiles = [] qTile = Tile(q) uTile = Tile(u) eTile = Tile(e) nTile = Tile(n) tiles.append(qTile) tiles.append(uTile) tiles.append(eTile) tiles.append(eTile) tiles.append(nTile) word = Word(tiles) heuristic = LetterScoringHeuristic(0) # Act result = heuristic.ScoreWord(word, hand) # Assert self.assertEqual(result, expected)
def setupGame(): #Setting up tiles in deck typesOfTile = ("Special", "Stick", "Circle", "Char") for types in typesOfTile: if (types == "Special"): for specialNum in range( 1, 8 ): # from 1 to 7: "East","South","West","North","Zhong","Fa cai","Bai ban" allTiles[Tile(types, specialNum)] = 4 else: for num in range(1, 10): allTiles[Tile(types, num)] = 4 for initialTile in list(allTiles.keys()): availableTiles.append(initialTile) #Setup starting hand for each player, East seat player gets the first turn for drawing in range(0, 3): for playerDrawing in playerList: for numtoDraw in range(0, 4): playerDrawing.draw() for playerDrawing in playerList: if (playerDrawing.seat == "East"): for numToDraw in range(0, 2): playerDrawing.draw() else: playerDrawing.draw()
def newRandomTile(): """ Fait apparaitre une nouvelle tuile et check si on perd """ # random.randrange(0,4) => 0,1,2,3 x = random.randrange(0, 4) y = random.randrange(0, 4) while tiles[x][y] != None: x = random.randrange(0, 4) y = random.randrange(0, 4) if random.randrange(0, 10) == 1: tiles[x][y] = Tile.Tile(4) else: tiles[x][y] = Tile.Tile(2) for x in range(0, 4): for y in range(0, 4): if (tiles[x][y] == None): return # GRILLE COMPLETE, CHECK LOOSE for x in range(0, 3): for y in range(0, 4): if (tiles[x][y].getValue() == tiles[x + 1][y].getValue()): return for x in range(0, 4): for y in range(0, 3): if (tiles[x][y].getValue() == tiles[x][y + 1].getValue()): return loose()
def draw_universe_view(self): self.drawn_systems.clear() for system in self.universe.universe_map: #white tiling behind systems points = Tile.polygon_corners( self.layout, self.universe.universe_map[system].location) new_points = self.hex_point_to_pygame_point(points) self.draw_polygon(Colour.white, new_points) for system in self.universe.universe_map: #systems with spacing in between points = Tile.polygon_corners_with_spacing( self.layout_rim, self.universe.universe_map[system].location, 1.155) new_points = self.hex_point_to_pygame_point(points) if (self.universe.universe_map[system].controlling_faction != None): self.drawn_systems.append( [new_points, self.universe.universe_map[system]]) self.draw_polygon( self.universe.universe_map[system].controlling_faction. colour, new_points) #print(universe.universe_map[system].faction.colour) else: self.drawn_systems.append( [new_points, self.universe.universe_map[system]]) self.draw_polygon(Colour.black, new_points)
def generate_dragon_nests(self): # generates nests, one of each type, loops until it can spawn it is_set=False while is_set!=True: xPos = random.randint(1, self.size) # random index of tile yPos = random.randint(1, self.size) if self.tile_array[xPos][yPos].is_set==False: self.map_array[xPos][yPos] = 'D' self.tile_array[xPos][yPos] = Tile(xPos, yPos, xPos*tile_size, yPos*tile_size, "dragon nest", 0, self.dragon_image1, True) is_set=True is_set=False while is_set!=True: xPos = random.randint(1, self.size) # random index of tile yPos = random.randint(1, self.size) if self.tile_array[xPos][yPos].is_set==False: self.map_array[xPos][yPos] = 'D' self.tile_array[xPos][yPos] = Tile(xPos, yPos, xPos*tile_size, yPos*tile_size, "dragon nest", 0, self.dragon_image2, True) is_set=True is_set=False while is_set!=True: xPos = random.randint(1, self.size) # random index of tile yPos = random.randint(1, self.size) if self.tile_array[xPos][yPos].is_set==False: self.map_array[xPos][yPos] = 'D' self.tile_array[xPos][yPos] = Tile(xPos, yPos, xPos*tile_size, yPos*tile_size, "dragon nest", 0, self.dragon_image3, True) is_set=True
def test_LongestWordHeuristicScoreWord_FourLetterWord_ReturnsFour(self): # Arrange expected = 4 hand = [] f = "F" o = "O" u = "U" r = "R" tiles = [] fTile = Tile(f) oTile = Tile(o) uTile = Tile(u) rTile = Tile(r) tiles.append(fTile) tiles.append(oTile) tiles.append(uTile) tiles.append(rTile) word = Word(tiles) heuristic = LongestWordHeuristic(0) # Act result = heuristic.ScoreWord(word, hand) # Assert self.assertEqual(result, expected)
def test_one_to_nine(self): character_1 = Tile.Tile("characters", 1) character_2 = Tile.Tile("characters", 2) character_3 = Tile.Tile("characters", 3) character_4 = Tile.Tile("characters", 4) character_5 = Tile.Tile("characters", 5) character_6 = Tile.Tile("characters", 6) character_7 = Tile.Tile("characters", 7) character_8 = Tile.Tile("characters", 8) character_9 = Tile.Tile("characters", 9) west = Tile.Tile("honor", "west") fixed_hand = [("pong", False, tuple([character_4, character_4, character_4]))] hand = [ character_1, character_2, character_3, character_5, character_6, character_7, character_8, character_9, west, west ] self.assertEqual( ScoringRules.HKRules.calculate_total_score(fixed_hand, hand, character_7, "draw", game=None)[1], 4)
def add(self, letter): if len(self.tiles) < self.rows * self.cols: used_positions = [t for t in self.tile_positions] for i in range(self.rows * self.cols): if i not in used_positions: print("Assigning {} to position {}".format(letter, i)) next_avail_coord = self.grid.coord_from_pos(i) break else: print("Hand is full.") return color = RANK_COLOR[LETTER_RANK[letter]] new_tile = Tile(self.canvas, self.grid.pxcoord_from_coord(next_avail_coord), grid=self.grid, color=color, text=letter, width=self.twidth, height=self.theight, frozen=False) new_tile.reveal() self.tiles.append(new_tile) self.tile_positions.append(i) self.changed = True print("Hand: {}".format(self.tiles))
def generate_single_chance_terrain(self): # generates terrain that takes only one tile and has its own spawn % chance forest_chance = random.randint(self.forest_chance_min, self.forest_chance_max) # random spawn chance from between given values mountain_chance = random.randint(self.mountain_chance_min, self.mountain_chance_max)+forest_chance # its cumulative for i in range(0, self.size+2): for j in range(0, self.size+2): if self.tile_array[i][j].is_set==False: chance = random.randint(1, 100) if chance <= forest_chance: # forest self.map_array[i][j] = 'F' t = random.randint(1, 3) # selecting random forest tile (there are 3 forest tiles) if t==1: self.tile_array[i][j] = Tile(i, j, i*tile_size, j*tile_size, "forest", 0, self.forest_image1, True) elif t==2: self.tile_array[i][j] = Tile(i, j, i*tile_size, j*tile_size, "forest", 0, self.forest_image2, True) else: self.tile_array[i][j] = Tile(i, j, i*tile_size, j*tile_size, "forest", 0, self.forest_image3, True) elif chance <= mountain_chance: # mountain self.map_array[i][j] = 'M' t = random.randint(1, 2) # selecting random forest tile (there are 3 forest tiles) if t==1: self.tile_array[i][j] = Tile(i, j, i*tile_size, j*tile_size, "mountain", 0, self.mountain_image1, True) else: self.tile_array[i][j] = Tile(i, j, i*tile_size, j*tile_size, "mountain", 0, self.mountain_image2, True) else: # remains grass pass
def __init__(self, difficulty): self.height = -1 self.width = -1 if difficulty == 1: self.height = 8 self.width = 8 self.mines = 10 elif difficulty == 2: self.height = 16 self.width = 16 self.mines = 40 else: self.height = 16 self.width = 30 self.mines = 99 self.board = [[Tile(-1,-1) for x in range(self.width)] for y in range(self.height)] for x in range(self.height): for y in range(self.width): tile = Tile(x,y) self.board[x][y] = Tile(x, y) #place the mine for i in range(self.mines): x = random.randint(0, self.width-1) y = random.randint(0, self.height-1) if self.board[x][y].hasBomb == True: i-=1 self.board[x][y].setBomb() neighbors = self.getNeighbors(self.getTile(x,y)) for tile in neighbors: tile.bombsNearby += 1
def loadLevel(self, level, doors, switches): tiles = [] x = 0 y = 0 print(level) file = open(level) lines = file.read().split() for line in lines: chars = list(line) for char in chars: if char == '#': tiles.append(Tile.Wall(x, y, 32, 32)) elif char == '.': tiles.append(Tile.Floor(x, y, 32, 32)) x += 32 y += 32 x = 0 doors_list = [] for d in doors: chars = str(d[1]).split() door = Tile.Door(int(chars[0]), int(chars[1]), int(chars[2]), int(chars[3]), chars[4]) tiles.append(door) doors_list.append(door) for s in switches: chars = str(s[1]).split() for do in doors_list: if do.id == chars[4]: tiles.append( Tile.Switch(int(chars[0]), int(chars[1]), int(chars[2]), int(chars[3]), do, chars[5])) return tiles
def dropEvent(self, event): #print("drop event occurred") #msg = 'dropping at {0} {1}'.format(event.pos().x(), event.pos().y()) actions = event.dropAction() #print(msg,translate_actions(actions)) if actions & Qt.CopyAction: event.acceptProposedAction() if (event.mimeData().hasImage() and event.mimeData().hasText()): pixmap = QPixmap(event.mimeData().imageData()) name = event.mimeData().text() tile = Tile(name,pixmap) tile.setCanMove(True) tile.setCanStretch(True) self.tileList.append(tile) self.layout().addWidget(tile) event.accept() elif actions & Qt.MoveAction: #print("move tile") targ = self.layout().itemAtPos(event.pos()) if targ is not None: self.layout().swapWidgets(self.curTile, targ) temp = targ.getName() targ.setName(self.curTile.getName()) self.curTile.setName(temp) event.acceptProposedAction() else: event.ignore()
def decide_drop_tile(self, player, new_tile, neighbors, game): self.begin_decision() fixed_hand, hand = player.fixed_hand, player.hand state = utils.extended_dnn_encode_state(player, neighbors, new_tile=new_tile) if self.display_step: self.print_game_board(fixed_hand, hand, neighbors, game, new_tile) q_network = get_network[self.network_type](self.q_network_path) valid_actions = [] tiles = player.hand if new_tile is None else player.hand + [new_tile] for tile in tiles: valid_actions.append(Tile.convert_tile_index(tile)) action_filter = np.zeros(n_decisions) action_filter[valid_actions] = 1 action = None if not self.skip_history and self.history_waiting: self.update_transition(state, REWARD_NON_TERMINAL, action_filter) while True: if action is not None and not self.skip_history: self.update_history(state, action, action_filter) self.update_transition(state, REWARD_INVALID_DECISION, action_filter) action, value = q_network.choose_action( state, action_filter=action_filter, eps_greedy=self.is_train, return_value=True, strict_filter=not self.is_train) if action in valid_actions: break elif not self.is_train: action = random.choice(valid_actions) break if not self.skip_history: self.update_history(state, action, action_filter) drop_tile = Tile.convert_tile_index(action) self.print_msg( "%s [%s] chooses to drop %s. [%.2f]" % (self.player_name, display_name, drop_tile.symbol, value)) self.end_decision(True) if game.lang_code is not None: game.add_notification( get_text(game.lang_code, "NOTI_CHOOSE_DISCARD") % (self.player_name, drop_tile.get_display_name(game.lang_code, is_short=False))) return drop_tile
def generate_tiles(unpacked_healpix, rescaled_pixels_90, rescale_detector, all_sky_coords, fudge_factor=0.75): t1 = time.time() good_tiles = [] # Extract pixel coords as tuples, then sort coords by RA, then Dec pix_coords = [(p.coord.ra.degree, p.coord.dec.degree) for p in rescaled_pixels_90] sorted_pix_coords = sorted(pix_coords, key=lambda p: (p[0], p[1])) # Construct 2D binary tree and define nearest-neighbor threshold between pixel/tile tree = spatial.cKDTree(sorted_pix_coords) threshold = np.sqrt(rescale_detector.deg_height**2 + rescale_detector.deg_width**2) # query tree and extract indices of tiles within threshold r = tree.query(all_sky_coords) good_indices = np.where(r[0] <= threshold)[0] # extract coords and create tiles all_sky_coords_arr = np.asarray(all_sky_coords) good_coords = all_sky_coords_arr[good_indices] # coord.SkyCoord(gc[0], gc[1], unit=(u.deg,u.deg)) for gc in good_coords: t = Tile(gc[0], gc[1], rescale_detector.deg_width, rescale_detector.deg_height, unpacked_healpix.nside) good_tiles.append(t) t2 = time.time() print("\n********* start DEBUG ***********") print("`generate_tiles.good_tiles` execution time: %s" % (t2 - t1)) print("********* end DEBUG ***********\n") t1 = time.time() # Parallelize initialization of good tiles pool = mp.Pool() initialized_tiles = pool.map(invoke_enclosed_pix, good_tiles) cum_prob = 0.0 for t in initialized_tiles: t.net_prob = np.sum( unpacked_healpix.prob[t.enclosed_pixel_indices]) cum_prob += t.net_prob t2 = time.time() print("\n********* start DEBUG ***********") print("`generate_tiles.enclosed_pixel_indices` execution time: %s" % (t2 - t1)) print("********* end DEBUG ***********\n") # return cum_prob, good_tiles return cum_prob, initialized_tiles
def __validate_helper(tile_map, suit_map, tile_count, grouped_hand=[]): result = [] if tile_count == 0: return [list(grouped_hand)] for suit in Tile.suit_order: suit_count = suit_map[suit] if suit_count == 0: continue iter_items = sorted(list(tile_map[suit].items()), key=lambda x: x[0]) for tile_val, count in iter_items: if count == 0: continue tile = Tile.Tile(suit, tile_val) if count >= 3: grouped_hand.append(("pong", (tile, tile, tile))) tile_map[suit][tile_val] -= 3 suit_map[suit] -= 3 tmp_result = __validate_helper(tile_map, suit_map, tile_count - 3, grouped_hand) grouped_hand.pop() tile_map[suit][tile_val] += 3 suit_map[suit] += 3 result.extend(tmp_result) if suit != "honor" and count >= 1 and int(tile_val) <= 7: succeeding_tile_1 = Tile.Tile(suit, int(tile_val) + 1) succeeding_tile_2 = Tile.Tile(suit, int(tile_val) + 2) if tile_map[suit][str( succeeding_tile_1.value)] >= 1 and tile_map[suit][str( succeeding_tile_2.value)] >= 1: grouped_hand.append( ("chow", (tile, succeeding_tile_1, succeeding_tile_2))) tile_map[suit][tile_val] -= 1 tile_map[suit][str(succeeding_tile_1.value)] -= 1 tile_map[suit][str(succeeding_tile_2.value)] -= 1 suit_map[suit] -= 3 tmp_result = __validate_helper(tile_map, suit_map, tile_count - 3, grouped_hand) grouped_hand.pop() tile_map[suit][tile_val] += 1 tile_map[suit][str(succeeding_tile_1.value)] += 1 tile_map[suit][str(succeeding_tile_2.value)] += 1 suit_map[suit] += 3 result.extend(tmp_result) return result
def decide_drop_tile(self, player, new_tile, neighbors, game): self.begin_decision() #print("drop") fixed_hand, hand = player.fixed_hand, player.hand state = utils.dnn_encode_state(player, neighbors) if not self.skip_history and self.history_waiting: self.update_transition(state, REWARD_NON_TERMINAL) if self.display_step: self.print_game_board(fixed_hand, hand, neighbors, game, new_tile) #model here #pg_model = get_MJPolicyGradient(self.pg_model_path) valid_actions = [] tiles = player.hand if new_tile is None else player.hand + [new_tile] for tile in tiles: valid_actions.append(Tile.convert_tile_index(tile)) action_filter = np.zeros(n_decisions) action_filter[valid_actions] = 1 action, value = self.actor.choose_action( state, action_filter=action_filter, return_value=True, strict_filter=not self.is_train) if action not in valid_actions: #print("invalid") if self.is_train: action = random.choice(valid_actions) if not self.skip_history: self.update_history(state, action, action_filter) self.update_transition(state, REWARD_INVALID_DECISION) else: raise Exception("Invalid action when not training") if not self.skip_history: self.update_history(state, action, action_filter) drop_tile = Tile.convert_tile_index(action) self.print_msg( "%s [%s] chooses to drop %s. [%.2f]" % (self.player_name, display_name, drop_tile.symbol, value)) self.end_decision(True) if game.lang_code is not None: game.add_notification( get_text(game.lang_code, "NOTI_CHOOSE_DISCARD") % (self.player_name, drop_tile.get_display_name(game.lang_code, is_short=False))) return drop_tile
def makePicLayout(self, picList): picLayout = QVBoxLayout() for pic in picList: tile = Tile(pic) if tile not in self.tileList: tile.setCanCopy(True) self.tileList.append(tile) for tile in self.tileList: picLayout.addWidget(tile) return picLayout
def __init__(self): self.tile_array = [[Tile.Tile() for _ in range(3)], [Tile.Tile() for _ in range(4)], [Tile.Tile() for _ in range(5)], [Tile.Tile() for _ in range(4)], [Tile.Tile() for _ in range(3)]] self.connect_tiles() self.add_edges() self.add_vertices() self.connect_edges_to_edges() self.connect_vertices_to_vertices()
def __init__(self, boardArr): # Elimiate magic ints with some class consants! # Specifies the size of the board in a 2D matrix self.SIZE = 9 # Main Key - Board Array self.boardArr = [[ Tile(0) for col in range(self.SIZE)] for row in range(self.SIZE)] # Convert boardArr ints to self.boardArr Tile objects for x in range(self.SIZE): for y in range(self.SIZE): # Set Tile and Solved State If Not 0 self.boardArr[x][y] = Tile( boardArr[x][y] )
def test_one_suit_wo_honor(self): dots_1 = Tile.Tile("dots", 1) dots_2 = Tile.Tile("dots", 2) dots_6 = Tile.Tile("dots", 6) dots_7 = Tile.Tile("dots", 7) dots_9 = Tile.Tile("dots", 9) hand = [ dots_1, dots_1, dots_1, dots_2, dots_2, dots_2, dots_6, dots_6, dots_6, dots_7, dots_7, dots_7, dots_9 ] grouped_hands = ScoringRules.HKRules.validate_hand([], hand, dots_9) score, _ = ScoringRules.HKRules.score_one_suit([], grouped_hands[0]) self.assertEqual(score, 7)
def test_all_pongs(self): character_1 = Tile.Tile("characters", 1) bamboo_2 = Tile.Tile("bamboo", 2) dots_5 = Tile.Tile("dots", 5) character_7 = Tile.Tile("characters", 7) dots_9 = Tile.Tile("dots", 9) hand = [ character_1, character_1, character_1, bamboo_2, bamboo_2, bamboo_2, dots_5, dots_5, dots_5, character_7, character_7, character_7, dots_9 ] grouped_hands = ScoringRules.HKRules.validate_hand([], hand, dots_9) self.assertEqual(len(grouped_hands), 1)
def setupBoard(self, level): lines=open("level_"+str(level)+".txt", "r").readlines() if lines: for j, line in enumerate(lines): kva=list() for i, type in enumerate(line.strip('\n')): if type=='0': frame=[0, 0, 32, 32] kva.append(t.Tile(self.tileSurfaces['tiles'], pygame.Rect(i*32, j*32, 32, 32), frame)) else: frame=[32, 0, 32, 32] kva.append(t.Tile(self.tileSurfaces['tiles'], pygame.Rect(i*32, j*32, 32, 32), frame)) self.board.append(kva)
def generate_mountains(self): # for each tile there is a chance of it being a mountain # mountains can't generate on water for i in range(0, self.size+2): for j in range(0, self.size+2): chance = random.randint(1, 100) if self.tile_array[i][j].is_set==False and chance<=self.mountain_chance: self.map_array[i][j] = 'M' t = random.randint(1, 2) # selecting random forest tile (there are 3 forest tiles) if t==1: self.tile_array[i][j] = Tile(i, j, i*tile_size, j*tile_size, "mountain", 0, self.mountain_image1, True) else: self.tile_array[i][j] = Tile(i, j, i*tile_size, j*tile_size, "mountain", 0, self.mountain_image2, True)
def buildMap(self): mapData = LevelHandler.loadMapFile(self.level) mapList = LevelHandler.parseMap(mapData) tileData = LevelHandler.parseData(mapData) try: stockTypes = LevelHandler.getStockBoxes(tileData) except: stockTypes = [] boxCount = 0 y = -1 for line in mapList: x=-1 y+=1 for char in line: x+=1 if char == "v": self.tiles.append(Tile((x*80,y*80), "Images/Tiles/stove_front.png", True, False)) if char == "s": try: food = stockTypes[boxCount] except: food = None self.tiles.append(StockBox((x*80,y*80), food, True)) boxCount += 1 if char == "#": try: top = mapList[y-1][x] bottom = mapList[y+1][x] left = mapList[y][x-1] right = mapList[y][x+1] except: pass if y == 0 and x != 0 and x!= 11: self.tiles.append(Counter((x*80,y*80), None,"Images/Tiles/counter_front.png")) elif x == 0 and y != 0: self.tiles.append(Counter((x*80,y*80), None,"Images/Tiles/counter_side_left.png")) elif x == 11 and y!= 0: self.tiles.append(Counter((x*80,y*80), None,"Images/Tiles/counter_side_right.png")) elif x == 0 and y == 0: self.tiles.append(Counter((x*80,y*80), None,"Images/Tiles/counter_corner_tl.png")) else: self.tiles.append(Counter((x*80,y*80), None,"Images/Tiles/counter_top.png")) if char == "t": self.tiles.append(Trash((x*80,y*80))) if char == "d": self.tiles.append(DeliveryTable((x*80,y*80), None)) if char == "c": self.tiles.append(ChoppingBoard((x*80,y*80), None)) if char == "-": self.tiles.append(Tile((x*80,y*80), "Images/Tiles/floor.png"))
def generate_level(self, images): level_grid = [] screen_info = pygame.display.Info() for i in range((screen_info.current_w // 32) + 1): level_grid.append(["w"] * ((screen_info.current_h // 32) + 1)) num_floors = (len(level_grid) * len(level_grid[0]) * 0.6) floor_count = 0 x = len(level_grid) // 2 y = len(level_grid[0]) // 2 while floor_count < num_floors: if level_grid[x][y] != "f": level_grid[x][y] = "f" floor_count += 1 dir = random.randint(1, 4) if dir == 1 and x > 2: x -= 1 if dir == 2 and x < len(level_grid) - 4: x += 1 if dir == 3 and y > 2: y -= 1 if dir == 4 and y < len(level_grid[0]) - 4: y += 1 self.place_start(level_grid) self.place_end(level_grid) for x in range(len(level_grid)): for y in range(len(level_grid[0])): if level_grid[x][y] == "w": self.walls.add(Tile(images["w"], (x * 32, y * 32))) if level_grid[x][y] == "f": self.floors.add(Tile(images["f"], (x * 32, y * 32))) if level_grid[x][y] == "s": self.start = Door(images["door"], (x * 32, y * 32), False) self.walls.add(self.start) if level_grid[x][y] == "e": self.end = Door(images["door"], (x * 32, y * 32), False) self.walls.add(self.end) for i in range(5): self.enemies.add( Enemy("images/enemy1.png", random.choice(self.floors.sprites()).rect.center, self))
def generate_empty(self): # first loop that creates all the tiles with is_set = false and borders for i in range(0, self.size+2): for j in range(0, self.size+2): if i==0 or i==self.size+1 or j==0 or j==self.size+1: # generates map outline, overwrites everthing (TO DO) self.map_array[i][j] = 'B' self.tile_array[i][j] = Tile(i, j, i*tile_size, j*tile_size, "border", 0, self.mountain_image2, True) else: # generates grass if a tile is empty self.map_array[i][j] = 'G' t = random.randint(1, 2) # selecting random forest tile (there are 3 forest tiles) if t==1: self.tile_array[i][j] = Tile(i, j, i*tile_size, j*tile_size, "grass", 0, self.grass_image1, False) else: self.tile_array[i][j] = Tile(i, j, i*tile_size, j*tile_size, "grass", 0, self.grass_image2, False)
def test_big_honors(self): dots_1 = Tile.Tile("dots", 1) dots_2 = Tile.Tile("dots", 2) red = Tile.Tile("honor", "red") green = Tile.Tile("honor", "green") white = Tile.Tile("honor", "white") hand = [ red, red, red, green, green, green, white, white, white, dots_1, dots_1, dots_1, dots_2 ] grouped_hands = ScoringRules.HKRules.validate_hand([], hand, dots_2) score, _ = ScoringRules.HKRules.score_honor_tiles([], grouped_hands[0]) self.assertEqual(score, ScoringRules.HKRules.get_score_upper_limit())
def test_one_nines(self): bamboo_1 = Tile.Tile("bamboo", 1) bamboo_9 = Tile.Tile("bamboo", 9) dots_1 = Tile.Tile("dots", 1) east = Tile.Tile("honor", "east") character_9 = Tile.Tile("characters", 9) hand = [ bamboo_1, bamboo_1, bamboo_1, bamboo_9, bamboo_9, bamboo_9, dots_1, dots_1, dots_1, east, east, east, character_9 ] grouped_hands = ScoringRules.HKRules.validate_hand([], hand, character_9) self.assertEqual(len(grouped_hands), 1)
def RotateType5(tiles, y_size, x_size, rotation_index): y_offset, x_offset = FindOffset(tiles, y_size, x_size) if rotation_index == 0: if y_offset >= (y_size - 2): Tile.upMove(tiles, y_size, x_size) y_offset -= 1 ChangeTile(tiles, y_offset, x_offset + 1, y_offset + 1, x_offset + 1) ChangeTile(tiles, y_offset + 2, x_offset, y_offset + 1, x_offset + 2) if rotation_index == 1: if x_offset == 0: Tile.rightMove(tiles, y_size, x_size) x_offset += 1 ChangeTile(tiles, y_offset + 1, x_offset + 1, y_offset + 1, x_offset) ChangeTile(tiles, y_offset, x_offset - 1, y_offset + 2, x_offset) if rotation_index == 2: if y_offset == 0: Tile.downTile(tiles, y_size, x_size) y_offset += 1 x_offset += 2 ChangeTile(tiles, y_offset - 1, x_offset, y_offset + 1, x_offset) ChangeTile(tiles, y_offset - 2, x_offset, y_offset, x_offset - 2) if rotation_index == 3: if x_offset >= (x_size - 2): for i in range(x_offset - (x_size - 2) + 1): Tile.leftMove(tiles, y_size, x_size) x_offset -= 1 ChangeTile(tiles, y_offset + 2, x_offset + 1, y_offset + 2, x_offset - 1) ChangeTile(tiles, y_offset + 2, x_offset + 2, y_offset, x_offset) rotation_index += 1 if rotation_index == 4: rotation_index = 0 return rotation_index
def load_tile(self, tile: namedtuple, x, y): if 'sides' in tile.type: Tile.Tile(tile, self.tiles, self.all_sprites, self.side_sprites, x, y) elif tile.type.startswith('floor'): Tile.Tile(tile, self.tiles, self.all_sprites, self.floor_sprites, x, y) elif tile.type.startswith('animated'): if tile.name.startswith('spikes'): AnimatedTile.AnimatedTile(self.tiles[tile.type][tile.name], 1, 4, x, y, self.animated_sprites, self.all_sprites) elif tile.type.startswith('items'): Tile.Tile(tile, self.tiles, self.all_sprites, self.boxes_sprites, x, y)
def dnn_encode_state(player, neighbors): state = np.zeros((9, 34, 1)) for tile in player.hand: state[0, Tile.convert_tile_index(tile), :] += 1 players = [player] + list(neighbors) for i in range(len(players)): p = players[i] for _, _, tiles in p.fixed_hand: for tile in tiles: state[1 + 2 * i, Tile.convert_tile_index(tile), :] += 1 for tile in p.get_discarded_tiles(): state[2 + 2 * i, Tile.convert_tile_index(tile), :] += 1 return state
def addTiles(self,path): levelF = open(path,'r') data = levelF.read() x=0 y=0 data = string.split(data,"@") header = string.split(data[0],",") self.width = int(header[0]) self.height = int(header[1]) self.tiles = [0]*(self.width*self.height) for i in data[1]: if i =='\n': continue if i ==';': x=0 y+=1 continue try: #self.setTile(x,y,Tile.tiles[Tile.getID(i)]) self.tiles[x+(y*self.width)]=Tile.tiles[Tile.getID(i)].id except: print "Fail at",x,y x+=1
def isPixelWall( self, point ): x = point[0]/Globals.TILESIZE y = point[1]/Globals.TILESIZE if(x >= self.width or y >= self.height): return True if(Globals.DEBUG): pygame.draw.rect(Globals.CANVAS, (255, 0, 255), pygame.Rect((x*Globals.TILESIZE, y*Globals.TILESIZE), (Globals.TILESIZE,Globals.TILESIZE))) return self.tileset.getTile(self.level[PLAYLAYER][x][y]).isWall(Tile.pointToTilePoint(point))
def draw_tiles(screen): """ draw_tiles() this function draws both computer's and human's tiles """ # Print the human Tiles on the screen for i in range(len(HUMAN_TILES)): current_tile = HUMAN_TILES[i][0] current_position = HUMAN_TILES[i][1] temp_tile = Tile(current_tile[0], current_tile[1], screen, current_position[0], current_position[1]) temp_tile.show_vertical() # Print the Computer Tiles (up-side-down) # TODO (DONE) changing the Computer tiles image for i in range(len(COMPUTER_TILES)): current_position = COMPUTER_TILES[i][1] temp_tile = Tile(9, 8, screen, current_position[0], current_position[1]) temp_tile.show_vertical()
def play(tile, screen, place=None): """ play(tile, screen, place) this function takes a tile as a "tuple", display and a place ("left" or "right"). then draws the tile on the screen. """ # Initialize the flag that determines the orientation of the tile orientation = "horizontal" # Initialize the flag that determines if the tile would be painted reversed reverse_tile = 0 # Initialize the place of the tile tile_x = 0 tile_y = 0 # make python recognize these variables as global global this_is_first_DOWN_tile global this_is_first_LEFT_tile global this_is_first_UP_tile global this_is_first_RIGHT_tile # set a variables determines if the tile is DUO or not tile_is_DUO = 0 if tile[0] == tile[1]: tile_is_DUO = 1 # check if this tile is the first tile to be played if len(PLAYED_TILES) == 0: # check if the tile is DUO, then place it in the right place if tile_is_DUO: tile_x = main_window_resolution[0] / 2 - 17 tile_y = main_window_resolution[1] / 2 - 34 orientation = "vertical" else: tile_x = main_window_resolution[0] / 2 - 34 tile_y = main_window_resolution[1] / 2 - 17 # append the tile to the PLAYED_TILES list PLAYED_TILES.append([tile, (tile_x, tile_y)]) # if the tile is going to be played in the left direction elif place == "left": # make some variables to ease understanding the code previous_tile = PLAYED_TILES[0][0] previous_position = PLAYED_TILES[0][1] previous_tile_is_DUO = 0 if previous_tile[0] == previous_tile[1]: previous_tile_is_DUO = 1 # PLAY TO THE LEFT DIRECTION if TOTAL_X["left"] < main_window_resolution[0] / 2 - 150: if tile_is_DUO: TOTAL_X["left"] += 36 orientation = "vertical" tile_x = previous_position[0] - 36 tile_y = previous_position[1] - 17 else: if previous_tile_is_DUO: TOTAL_X["left"] += 70 tile_x = previous_position[0] - 70 tile_y = previous_position[1] + 17 else: TOTAL_X["left"] += 70 tile_x = previous_position[0] - 70 tile_y = previous_position[1] # reached the left end of the window else: # PLAY TO THE UP DIRECTION if TOTAL_Y["up"] < main_window_resolution[1] / 4 - 110: # this is the first tile going to be played UP if this_is_first_UP_tile: this_is_first_UP_tile = 0 # previous tile is DUO if previous_tile_is_DUO: TOTAL_Y["up"] += 104 # 34 + 70 orientation = "vertical" tile_x = previous_position[0] tile_y = previous_position[1] - 70 # previous tile is NOT DUO else: if tile_is_DUO: orientation = "vertical" tile_x = previous_position[0] - 36 tile_y = previous_position[1] - 17 # act like the next tile will be the first UP, # because if it didn't, the computer would think that # this tile was horizontal, which causes calculation error this_is_first_UP_tile = 1 else: TOTAL_Y["up"] += 87 # 17 + 70 orientation = "vertical" tile_x = previous_position[0] tile_y = previous_position[1] - 70 # this is NOT the first tile that is going to be played UP else: # previous tile is DUO if previous_tile_is_DUO: TOTAL_Y["up"] += 70 orientation = "vertical" tile_x = previous_position[0] + 17 tile_y = previous_position[1] - 70 # previous tile is NOT DUO else: if tile_is_DUO: TOTAL_Y["up"] += 36 tile_x = previous_position[0] - 17 tile_y = previous_position[1] - 36 else: TOTAL_Y["up"] += 70 orientation = "vertical" tile_x = previous_position[0] tile_y = previous_position[1] - 70 # PLAY TO THE RIGHT DIRECTION else: # this is the first tile to be played RIGHT if this_is_first_RIGHT_tile: this_is_first_RIGHT_tile = 0 # the previous tile was DUO if previous_tile_is_DUO: tile_x = previous_position[0] + 70 tile_y = previous_position[1] reverse_tile = 1 # the previous tile was NOT DUO else: if tile_is_DUO: TOTAL_Y["up"] += 36 tile_x = previous_position[0] - 17 tile_y = previous_position[1] - 36 # act like the next tile will be the first UP, # because if it didn't, the computer would think that # this tile was horizontal, which causes calculation error this_is_first_RIGHT_tile = 1 else: # we will add 36 to TOTAL_Y["up"] because if we didn't, next # time it would be considered "first time right" again TOTAL_Y["up"] += 36 tile_x = previous_position[0] + 36 tile_y = previous_position[1] reverse_tile = 1 # this is NOT the first tile to be played RIGHT else: # the previous tile was DUO if previous_tile_is_DUO: tile_x = previous_position[0] + 36 tile_y = previous_position[1] + 17 reverse_tile = 1 # the previous tile was NOT DUO else: if tile_is_DUO: orientation = "vertical" tile_x = previous_position[0] + 70 tile_y = previous_position[1] - 17 else: tile_x = previous_position[0] + 70 tile_y = previous_position[1] reverse_tile = 1 # APPEND THE PLAYED TILE TO THE PLAYED_TILES LIST PLAYED_TILES.insert(0, [tile, (tile_x, tile_y)]) # if the tile is going to be played in the right direction elif place == "right": # make some variables to ease understanding the code previous_tile = PLAYED_TILES[-1][0] previous_position = PLAYED_TILES[-1][1] previous_tile_is_DUO = 0 if previous_tile[0] == previous_tile[1]: previous_tile_is_DUO = 1 # PLAY TO THE RIGHT DIRECTION if TOTAL_X["right"] < main_window_resolution[0] / 2 - 150: # if this tile is DUO if tile_is_DUO: TOTAL_X["right"] += 36 orientation = "vertical" tile_x = previous_position[0] + 70 tile_y = previous_position[1] - 17 # if this tile is NOT DUO else: if previous_tile_is_DUO: TOTAL_X["right"] += 70 tile_x = previous_position[0] + 36 tile_y = previous_position[1] + 17 else: TOTAL_X["right"] += 70 tile_x = previous_position[0] + 70 tile_y = previous_position[1] # reached the right end of the window else: # PLAY TO DOWN DIRECTION if TOTAL_Y["down"] < main_window_resolution[1] / 4 - 110: # this is the first tile to be played in the DOWN direction if this_is_first_DOWN_tile: this_is_first_DOWN_tile = 0 # if the previous tile was DUO if previous_tile_is_DUO: TOTAL_Y["down"] += 104 # 34 + 70 orientation = "vertical" tile_x = previous_position[0] tile_y = previous_position[1] + 70 # if the previous tile was NOT DUO else: if tile_is_DUO: orientation = "vertical" tile_x = previous_position[0] + 70 tile_y = previous_position[1] - 17 # act like the next tile will be the first DOWN, # because if it didn't, the computer would think that # this tile was horizontal, which causes calculation error this_is_first_DOWN_tile = 1 else: TOTAL_Y["down"] += 87 # 17 + 70 orientation = "vertical" tile_x = previous_position[0] + 34 tile_y = previous_position[1] + 36 # this is NOT the first tile to be played in the DOWN direction else: # if the previous tile was DUO if previous_tile_is_DUO: TOTAL_Y["down"] += 70 orientation = "vertical" tile_x = previous_position[0] + 17 tile_y = previous_position[1] + 36 # if the previous tile was NOT DUO else: if tile_is_DUO: TOTAL_Y["down"] += 36 tile_x = previous_position[0] - 17 tile_y = previous_position[1] + 36 else: TOTAL_Y["down"] += 70 orientation = "vertical" tile_x = previous_position[0] tile_y = previous_position[1] + 70 # PLAY TO LEFT DIRECTION (REVERSED TILES) else: # if this tile is the first tile to be played LEFT if this_is_first_LEFT_tile: this_is_first_LEFT_tile = 0 # if the previous tile was DUO if previous_tile_is_DUO: TOTAL_Y["down"] += 36 tile_x = previous_position[0] - 70 tile_y = previous_position[1] reverse_tile = 1 ##if the previous tile was NOT DUO else: if tile_is_DUO: TOTAL_Y["down"] += 36 tile_x = previous_position[0] - 17 tile_y = previous_position[1] + 70 # act like the next tile will be the first LEFT, # because if it didn't, the computer would think that # this tile was vertical, which causes calculation error this_is_first_LEFT_tile = 1 else: # we will add 36 to TOTAL_Y["up"] because if we didn't, next # time it would be considered "first time right" again TOTAL_Y["down"] += 36 tile_x = previous_position[0] - 70 tile_y = previous_position[1] + 34 reverse_tile = 1 # if this tile is NOT the first tile to be played LEFT else: # if the previous tile was DUO if previous_tile_is_DUO: TOTAL_Y["down"] += 36 tile_x = previous_position[0] - 70 tile_y = previous_position[1] + 17 reverse_tile = 1 # if the previous tile was NOT DUO else: if tile_is_DUO: orientation = "vertical" tile_x = previous_position[0] - 36 tile_y = previous_position[1] - 17 else: TOTAL_Y["down"] += 36 tile_x = previous_position[0] - 70 tile_y = previous_position[1] reverse_tile = 1 # ADD THE PLAYED TILE TO THE PLAYED_TILES LIST PLAYED_TILES.append([tile, (tile_x, tile_y)]) # if the programmer didn't pass the place variable, raise an exception else: raise ValueError # Create a Tile object if reverse_tile: temp_tile = Tile(tile[1], tile[0], screen, tile_x, tile_y) else: temp_tile = Tile(tile[0], tile[1], screen, tile_x, tile_y) # show the tile according to it's suitable orientation if orientation == "horizontal": temp_tile.show_horizontal() else: temp_tile.show_vertical()