async def discard_tile(self): dm = self.disc.dm_channel hand_picture = player_image(self, False, False) hand = discord.File(hand_picture, filename="hand.png") if not dm: dm = await self.disc.create_dm() await dm.send('your hand', file=hand) discard = Tile('8', 'z') query = "What tile do you want to discard?\n" + str(self.hand) while discard not in self.hand.tiles: try: discard = await self.user_input(query) discard = Tile(discard[0], discard[1]) except asyncio.exceptions.TimeoutError: discard = random.choice(self.hand.tiles) except ValueError: discard = Tile('8', 'z') except IndexError: discard = Tile('8', 'z') query = "Invalid discard, please try again." self.temp_furiten = False self.hand.remove_tiles(discard) hand_picture = player_image(self, True, True, str(discard)) return discard, hand_picture
async def riichi(self, draw, game): #this *should* check the hand to make sure its closed opened = [meld for meld in self.melds.melds if meld.opened] if opened: return False #determine what tiles are discardable to be in tenpai shanten = shanten_calculator(str(self.hand) + str(draw)) if (shanten == 0 or shanten == -1) and self.points >= 1000 and not self.in_riichi: riichi_tiles = [] temp_hand = Tiles() temp_hand.tiles = self.hand.tiles[:] temp_hand.add_tiles(draw) for tile in temp_hand.tiles: temp = Tiles() temp.tiles = temp_hand.tiles[:] temp.remove_tiles(tile) if winning_tiles(str(temp)) and tile not in riichi_tiles: riichi_tiles.append(tile) if riichi_tiles: try: reach = await self.user_input('Would you like to riichi?') except asyncio.exceptions.TimeoutError: reach = 'n' if reach != 'y' and reach != 'yes': return False else: return False discard = Tile('8', 'z') while discard not in self.hand.tiles and discard != draw: try: query = "Which tile would you like to riichi on? Type cancel to cancel riichi.\n" + ' '.join( map(str, riichi_tiles)) discard = await self.user_input(query) discard = Tile(discard[0], discard[1]) except asyncio.exceptions.TimeoutError: return False except ValueError: discard = Tile('8', 'z') except IndexError: discard = Tile('8', 'z') #self.discard_tile(choice) if game.tenhou and game.wall.remaining > 65: self.double_riichi = True self.in_riichi = True self.ippatsu = True self.points -= 1000 game.riichi += 1 return discard else: return False '''
def setup(self): """STEP 2: Sets up the two dimentional list of tiles""" print("Generating tiles...") # List of calculated spaces and the rooms self.spacelist = [] self.roomlist = [] self.corridorlist = [] self.wall_image = pg.image.load("images/wall2.png").convert_alpha() self.wall_image = pg.transform.scale(self.wall_image, (TILESIZE, TILESIZE)) self.floor_image = pg.image.load("images/floor2.png").convert_alpha() self.floor_image = pg.transform.scale(self.floor_image, (TILESIZE, TILESIZE)) self.hordoor = pg.image.load("images/hor_door.png").convert_alpha() self.hordoor = pg.transform.scale(self.hordoor, (TILESIZE, TILESIZE)) self.vertdoor = pg.image.load("images/vert_door.png").convert_alpha() self.vertdoor = pg.transform.scale(self.vertdoor, (TILESIZE, TILESIZE)) self.rockimage = pg.image.load("images/rock.png").convert_alpha() self.rockimage = pg.transform.scale(self.rockimage, (TILESIZE, TILESIZE)) self.enterimage = pg.image.load("images/enter.png").convert_alpha() self.enterimage = pg.transform.scale(self.enterimage, (TILESIZE, TILESIZE)) self.exitimage = pg.image.load("images/exit.png").convert_alpha() self.exitimage = pg.transform.scale(self.exitimage, (TILESIZE, TILESIZE)) self.playerimage = pg.image.load("images/alfa.png").convert_alpha() self.playerimage = pg.transform.scale(self.playerimage, (TILESIZE, TILESIZE)) self.map = [[Tile(w*TILESIZE, h*TILESIZE, 0, self.rockimage, self.wall_image, self.floor_image, self.vertdoor, self.hordoor, self.enterimage, self.exitimage, self.playerimage) for h in range(self.height_tiles)] for w in range(self.width_tiles)] self.playerx = 0 self.playery = 0 self.new_level_x = 0 self.new_level_y = 0 print("Done")
def load(self, filename, world): for y, line in enumerate(open(filename, 'r')): for x, column in enumerate(line): if column not in TileType.__dict__: continue t = Tile(getattr(TileType, column), world, x=x, y=y) self.tiles[(x, y)] = t
def construct_bag(self): """ adds tile objects to bag object """ testing = self._are_we_testing() alphabet = self.config['test']['bag']['word'].lower() if testing \ else self.config['bag']['letters'].keys() for letter in alphabet: bag_amount = self.config['test']['bag']['letters'][letter]['bag_amount'] if testing \ else self.config['bag']['letters'][letter]['bag_amount'] point_val = self.config['test']['bag']['letters'][letter]['point_val'] if testing \ else self.config['bag']['letters'][letter]['point_val'] count = 0 while count < bag_amount: tile = Tile(letter=letter.upper(), point_val=point_val, id=count + 1, bag_amount=bag_amount) self.contents.append(tile) count += 1 # check tile amount tile_count = len(self.contents) if tile_count < 100 and not testing: raise ValueError( "Letter bag only contains {} tiles. Must contain a total of 100." .format(tile_count)) return None
def _loadTilestacks(self): ret = [] for y in xrange(self.heightInTiles): for x in xrange(self.widthInTiles): ts = Tilestack() ts.addBaseTile(Tile(self.tileFactory, self.baseTile)) ret.append(ts) return ret
def idx_to_tiles(list_idx): ''' @param: list_idx list of index @return: list of tile obejcts ''' tiles = [] for i in list_idx: tiles.append(Tile(i % 35, None)) return tiles
def createTileList(self, filename): layout = numpy.loadtxt(filename, dtype=str) col, row = layout.shape for i in range(row): for j in range(col): value = layout[j][i] if (value == '0'): pos = (i*self.width, j*self.height) self.tilelist.append(Tile((self.width, self.height), pos)) return self.tilelist
def defend(self, damage): if random.randint(1, 20) > self.defense: self.health -= damage self.health = max(0, self.health) if self.health <= 0: self.level.floor.add( Tile("images/monsters/grave.gif", (self.rect.x - 15, self.rect.y - 25))) self.image = pygame.image.load("images/terrain/bones.gif") self.alive = False
def defend(self, damage): if random.randint(1, 20) > self.defense: self.health -= damage self.heath = max(0, self.heath) self.level.messages.add(movingMessage("--{}".format(damage), self.rect.topleft, (255, 0, 0))) if self.heath <= 0: self.level.message.add(Message("rip", self.ract.center)) self.level.floor.add(Tile("images/monsters/grave.gif", (self.rect.x-15, self.rect.y-25))) self.image = pygame.image.load("images/terrain/bones.glf") self.alive= False
def test_end_of_path(self): paths = [('s1', 'e2'), ('s2', 'w1'), ('e1', 'n2'), ('n1', 'w2')] tile = Tile(paths) self.assertAlmostEqual(tile.end_of_path('s1'), 'e2') self.assertAlmostEqual(tile.end_of_path('e2'), 's1') hand_tile = HandTile(paths) self.assertAlmostEqual(hand_tile.end_of_path('e1'), 'n2') self.assertAlmostEqual(hand_tile.end_of_path('n2'), 'e1')
def construct_tile(tile_dict): ''' :param tile_dict: dict containing tile obj :return: constructed tile obj ''' tile = Tile(tile_dict['idx'], None) if not tile_dict['position'] == None: tile.position = (tile_dict['position'][0], tile_dict['position'][1]) tile.list_of_path = tile_dict['list_of_path'] return tile
def player_pick_tile_from_middle(self) -> None: """ Handle everything if a player choses to draw from the middle. This includes taking the starting player marker, but also removing tile type from the middle and adding it to the pattern lines """ if self.the_middle.is_untouched: self.starting_player = self.current_player self.the_middle.is_untouched = False minus_counter = TileCounter(Tile(99), 1) self.players[self.current_player].board.floor_line += minus_counter style = int( input( "What tile type or you picking? (0=black, 1=blue, 2=red, 3=yellow, 4=white) " )) tile = Tile(style) tile_count = self.the_middle.pop(tile) tile_counter = TileCounter(tile, tile_count) self.players[self.current_player].board.add_tile_count(tile_counter)
def generate(self): sea_tile = TILE_TYPES.get('water') land_tile = TILE_TYPES.get('land') seeds = self.place_seeds() for x in range(self.width): new_row = list() for y in range(self.height): new_tile = Tile(sea_tile, x, y) if (x, y) not in seeds else Tile( land_tile, x, y) new_row.append(new_tile) self._tiles.append(new_row) self.generate_continents() self.generate_bioms() self.clear_glitches() self.place_resources() self.place_states(6) return { 'tiles': self._tiles, 'cities': self._cities, 'resources': self._resources }
def setup_level(self, layout): self.tiles = pygame.sprite.Group() self.player = pygame.sprite.GroupSingle() for row_index, row in enumerate(layout): for col_index, cell in enumerate(row): x = col_index * tile_size y = row_index * tile_size if cell == 'X': tile = Tile((x, y), tile_size) self.tiles.add(tile) elif cell == "P": player_sprite = Player((x, y), self.display_surface) self.player.add(player_sprite)
def construct_obj(res): ''' :param res: response received from client :return: constructed tile, and avatar object received from client ''' tile_dict = res[0] avatar_dict = res[1] tile = Tile(tile_dict['idx'], None) if not tile_dict['position'] == None: tile.position = (tile_dict['position'][0], tile_dict['position'][1]) tile.list_of_path = tile_dict['list_of_path'] avatar = Avatar(avatar_dict['color'], None) if not avatar_dict['position'] == None: pos = avatar_dict['position'][0] port = avatar_dict['position'][1] avatar.position = ((pos[0], pos[1]), port) return tile, avatar
def __init__(self, sizeMAze, WIDTH, HEIGHT): Maze.widthMaze = WIDTH Maze.heightMaze = HEIGHT Maze.size_maze = sizeMAze Maze.cost_walk = 10 tileWidth = WIDTH // sizeMAze tileHeight = HEIGHT // sizeMAze # gonna make N * N maze, each position being a tile ID mode = sizeMAze # used to check each colum each tile belongs to yPos = 0 # everytime we change column, it increases by tileHeight xPos = 0 # calculate x and y positions for each tile for idMaze in range(1, (sizeMAze * sizeMAze) + 1): if ( idMaze // mode < 1 ): # if it's the number by itself, the tile still belongs to that column x = xPos * tileWidth y = yPos xPos += 1 else: if (idMaze // mode == 1): # update y position and reset X variables x = xPos * tileWidth y = yPos xPos = 0 yPos += tileHeight mode += sizeMAze Maze.tilesMaze[idMaze] = Tile(tileWidth, tileHeight, x, y) pygame.Rect.__init__(self, Maze.xPos, Maze.yPos, Maze.widthMaze, Maze.heightMaze) self._setNeighbors(sizeMAze) self._setWalls(sizeMAze) # get a cell(node) randomly randomNode = random.randrange(sizeMAze * sizeMAze) + 1 self._generateMazeDFS(Maze.tilesMaze[randomNode]) #self._createMultiplePathsBFS( ) Not good, runs exponetial time by doing BFS from every node to all nodes self._createMultiplePathsRandom()
def score_floor_line(self) -> List[TileCounter]: """ Score and flush the minus point area. Returns a list with TileCounter that represent the discarded tiles. The method makes sure that the minus-tile (=Tile(99)) does not end up in the discarded tiles. The minus-point tile implicitly returns to TheMiddle (actually it is recreated whenever somebody takes a 'first draw' from TheMiddle) """ self.point_total -= self.floor_line.count_minus_points discarded_tile_list = self.floor_line[:] self.floor_line = FloorLine() return [ TileCounter(tile, 1) for tile in discarded_tile_list if tile != Tile(99) # Tile(99) is the minus-point tile ]
def importer(name, texture_size): with open(name, "r") as file: lines = file.readlines() size = lines[0].split(",") size = int(size[0]), int(size[1]) grid = Grid(size) useless = None collision = False x, y = 0, 0 state = "new" for line in lines[1:]: if "/" in line: state = "new" x += 1 if x >= size[0]: y += 1 x = 0 continue if "|" in line: useless, collision = line.split(",") continue if state == "new": texture, position = line.split(",") tile = Tile(Texture(texture, int(position), texture_size)) tile.collision = bool(int(collision)) grid.put(x, y, tile) state = "added" continue if state == "added": texture, position = line.split(",") grid.get(x, y).add(Texture(texture, int(position), texture_size)) return grid
def player_pick_tile_from_factory(self) -> None: factory_nr = int(input("What factory are you choosing from? ")) style = int( input( "What tile type or you picking? (0=black, 1=blue, 2=red, 3=yellow, 4=white) " )) tile = Tile(style) tile_count = self.factories[factory_nr].pop(tile) tile_counter = TileCounter(tile, tile_count) # Add factory leftovers to the middle factory_leftover = self.factories[factory_nr] for k, v in factory_leftover.items(): self.the_middle[k] += v # Make sure that the factory is empty self.factories[factory_nr] = Factory() # Add tiles to player's pattern lines self.players[self.current_player].board.add_tile_count(tile_counter)
async def draw_discard(self, game): draw = game.wall.draw_tile(self) discard = Tile('8', 'z') dm = self.disc.dm_channel hand_picture = player_image(self, False, False, draw) hand_picture.seek(0) hand = discord.File(hand_picture, filename="your hand.png") if not dm: dm = await self.disc.create_dm() await dm.send('your hand', file=hand) tsumo = self.tsumo(draw, game) if tsumo: try: choice = await self.user_input("Would you like to tsumo?") except asyncio.exceptions.TimeoutError: choice = 'y' if choice == 'y' or choice == 'yes': result = dict() result[self] = tsumo raise GameOver(result, draw) ckan = self.ckan_tiles(draw) if ckan and game.num_kan < 4: try: choice = await self.user_input("Would you like to closed kan?") except asyncio.exceptions.TimeoutError: choice = 'n' if choice == 'y' or choice == 'yes': call = await self.ckan(draw) if call: await game.add_dora() discard, hidden_picture = await self.draw_discard(game) self.rinshan = False return discard, hidden_picture if self.in_riichi: self.ippatsu = False discard = draw else: discard = await self.riichi(draw, game) if not discard: discard = Tile('8', 'z') query = "What tile do you want to discard?\n" + str( self.hand) + ' ' + str(draw) while discard not in self.hand.tiles and discard != draw: try: discard = await self.user_input(query) discard = Tile(discard[0], discard[1]) #dumb workaround to prevent players from discarding non-existant #red fives when they have a five in hand, or discarding #non-existant fives when they have a red five in hand in_hand = [ tile for tile in self.hand.tiles if tile.suit == discard.suit and tile.value == discard.value ] is_draw = discard.value == draw.value and discard.suit == draw.suit if not (in_hand or is_draw): discard = Tile('8', 'z') except asyncio.exceptions.TimeoutError: discard = draw except ValueError: discard = Tile('8', 'z') except IndexError: discard = Tile('8', 'z') query = "Invalid discard, please try again." if discard == draw: hidden_picture = player_image(self, True, True, str(discard)) else: hidden_picture = player_image(self, True, False, str(discard)) self.temp_furiten = False self.hand.add_tiles(draw) self.hand.remove_tiles(discard) self.total_discards.add_tiles(discard) hand_picture = player_image(self, False, False) final_hand = discord.File(hand_picture, filename="hand.png") await dm.send('final hand', file=final_hand) return discard, hidden_picture
def createMapContainer(self, contents, x=-1, y=-1): """Creates a container object at the specified pixel coordinates that can then be interacted with by the player. """ if x == -1: x = self.player.px+self.player.width if y == -1: y = self.player.py print "adding %s to tile at (%s,%s)" % (contents, x, y) if not isinstance(contents, list): contents = [contents] ts = self.getTilestackAt(x,y) if ts.triggerId: if ts.triggerId != "container_search": raise Exception, "Cannot create container on tile containing existing trigger (%d,%d)" % (x,y) else: ts.contents += contents else: ts.addBaseTile(Tile(self.tileFactory, self.tileFactory.specialTiles['generic_container'])) ts.triggerId = "container_search" if not ts.contents: ts.contents = contents else: for item in contents: if item not in ts.contents: ts.contents += [item] def save(self, filename): """Saves the scene to the specified filename.""" # What all needs to be saved for a scene?: # map info (tileset, tile index, trigger, etc) # actor info (player and npcs) # script info # anything else? if os.path.exists(filename):
def get_pos(img, pos_x, pos_y, depth): res = img.copy() h, w = img.shape[:2] M = cv2.getRotationMatrix2D((w / 2, h / 2), (imu_yaw) * 180 / math.pi, 1) img = cv2.warpAffine(img, M, (w, h)) # circle mask circle_mask = np.zeros_like(img) circle_mask = cv2.circle(circle_mask, (int(w / 2), int(h / 2)), int(h / 2), [255, 255, 255], -1) circle_mask = circle_mask[:, :, 0] # print(h,w) img = img_correction(img) blur = cv2.GaussianBlur(img, (7, 7), 0) hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV) mask = cv2.adaptiveThreshold(hsv[:, :, 2], 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, \ cv2.THRESH_BINARY, 21, 2) kernel = np.ones((5, 5), np.uint8) opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) opening = 255 - opening opening = cv2.dilate(opening, None, iterations=1) contour_mask = 255 - opening opening[circle_mask == 0] = 0 # fit lines to extract major direction minLineLength = 100 lines = cv2.HoughLinesP(image=opening, rho=1, theta=np.pi / 180, threshold=100, lines=np.array([]), minLineLength=minLineLength, maxLineGap=12) grad = np.zeros((len(lines), 1)) i = 0 for line in lines: # find two major gradients x1, y1, x2, y2 = line[0][0], line[0][1], line[0][2], line[0][3] theta = math.atan(float(y2 - y1) / (x2 - x1)) * 180 / math.pi grad[i] = theta i += 1 # cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 3, cv2.LINE_AA) cv2.line(contour_mask, (x1, y1), (x2, y2), 0, 1, cv2.LINE_AA) hist, bin_edges = np.histogram(grad, density=False) ind = np.argmax(hist) best_grad = round((bin_edges[ind] + bin_edges[ind + 1]) / 2, 2) ind = np.where(np.abs(grad - best_grad) < 10) good_grads = grad[ind] best_grad = np.mean(good_grads) # contour_mask=self.mask_correction(contour_mask) M = cv2.getRotationMatrix2D((w / 2, h / 2), best_grad, 1) contour_mask = cv2.warpAffine(contour_mask, M, (w, h)) (contours, _) = cv2.findContours(contour_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) contour_mask = cv2.cvtColor(contour_mask, cv2.COLOR_GRAY2BGR) areas = [] border = 0 r = [] for contour in contours: rect = cv2.boundingRect(contour) if rect[0] > border and rect[0] + rect[2] < w - border and rect[ 1] > border and rect[3] + rect[1] < h - border: area = int(rect[3] * rect[2]) # print(area) ar = float(rect[2]) / rect[3] real_ar = 0.25 / 0.12 if area > 1000 and area < 120000 and abs(ar / real_ar - 1) < 0.3: cv2.rectangle(contour_mask, (rect[0], rect[1]), (rect[2] + rect[0], rect[3] + rect[1]), (0, 255, 0), 2) areas.append(area) r.append(rect) areas = np.asarray(areas) hist, bin_edges = np.histogram(areas, bins='fd', density=False) ind = np.argmax(hist) # best_area=(bin_edges[ind]+bin_edges[ind+1])/2 best_area = round((bin_edges[ind] + bin_edges[ind + 1]) / 2, 2) ind = np.where(np.abs(areas - best_area) < 0.1 * best_area) if len(ind) > 5: good_areas = areas[ind] best_area = np.mean(good_areas) pred_depth = predict_depth(best_area) pred_depth = pred_depth * math.cos(imu_pitch) * math.cos(imu_roll) for tile in tiles: r = tile.one_step_update(r) for rect in r: tiles.append(Tile(rect, ind_count)) ind_count += 1 for tile in tiles: if tile.alive == False: tiles.remove(tile) del_x = [] del_y = [] for tile in tiles: color = colors[tile.ind % 20] color = tuple([int(x) for x in color]) if len(tile.centers) > 2: del_x.append(tile.centers[-1][1] - tile.centers[-2][1]) del_y.append(tile.centers[-1][0] - tile.centers[-2][0]) contour_mask = cv2.circle( contour_mask, (int(tile.centers[-1][0]), int(tile.centers[-1][1])), 5, color, -1) cv2.putText(contour_mask, str(tile.ind), (tile.bb[0] + 10, tile.bb[1] + 10), font, 0.8, color, 1, cv2.LINE_AA) hist, bin_edges = np.histogram(np.asarray(del_x), bins='fd', density=False) ind = np.argmax(hist) best_del_x = round((bin_edges[ind] + bin_edges[ind + 1]) / 2, 2) hist, bin_edges = np.histogram(np.asarray(del_y), bins='fd', density=False) ind = np.argmax(hist) best_del_y = round((bin_edges[ind] + bin_edges[ind + 1]) / 2, 2) # tile real world dimension fov_w, fov_h = 48 * math.pi / 180, 36 * math.pi / 180 px_W, px_H = 640, 480 W = 2 * pred_depth * math.tan(fov_w / 2) + 0.0001 ppm = px_W / W pos_x -= best_del_x / ppm pos_y -= best_del_y / ppm return pos_x, pos_y, pred_depth
# -*- coding: utf-8 -*- from tiles import Tile from shanten import Shanten import utils hand_str = input("input your hand tiles: ") your_tile = Tile(hand_str) your_shanten = 8 error_state = your_tile.error_state rest_tiles = your_tile.rest_card if error_state: print("please input right 14 tiles") hand_tiles = your_tile.hand_tiles discard_list = [] while not error_state: shanten_data = Shanten.get_shanten_data(hand_tiles) your_shanten = shanten_data["all_shanten"] if your_shanten == -1: print("win") break print("hand_str:", utils.codes_to_str(hand_tiles)) Shanten.print_shanten_message(shanten_data, rest_tiles) print("------") discard = input("to discard: ") discard_code = utils.str_to_code(discard) hand_tiles.remove(discard_code) discard_list.append(discard_code) remove_tiles = input("to remove form deck: ") remove_card = Tile(remove_tiles).hand_tiles rest_tiles = Shanten.remove_item(remove_card, rest_tiles) in_tile = input("in: ")
else: print("shanten include kokushi and chiitoitsu:", shanten_data["all_shanten"]) print("shanten without kokushi and chiitoitsu:", shanten_data["normal_shanten"]) keys = Shanten.count_tiles(shanten_data, rest_of_136_tiles) print("[How to discard]:") for key_count in keys: k = key_count[1] a = "discard: %s, to wait:[" % (k, ) a += utils.codes_to_str(shanten_data["discard"][k]) a += '] ' + str(key_count[0]) + ' tiles' print(a) if __name__ == '__main__': import time start = time.time() strdata = '234m68m13579p1s 789s' print("input:", strdata) tile_1 = Tile(strdata) hand_tiles_1 = tile_1.hand_tiles print("sorted:", tile_1.tiles_sorted_str) print("hand_tiles:", hand_tiles_1) print("------") shanten_data_1 = Shanten.get_shanten_data(hand_tiles_1) rest_of_136_tiles_1 = tile_1.rest_card Shanten.print_shanten_message(shanten_data_1, rest_of_136_tiles_1) print("------") print('time:', time.time() - start)
def addBaseTile(self, tileIndex, x, y): ts = self.tilestacks[y*self.widthInTiles+x] ts.addBaseTile(Tile(self.tileFactory, tileIndex)) ts.isWalkable = False
def __init__(self, root,app,tile_size=50): ttk.Frame.__init__(self, root) self.root=root self.app=app self.size_x=self.size_y=400 self.tile_size=tile_size self.total_size_y=1000 self.total_size_x=1400 self.canvas = tk.Canvas(self, width=self.size_x, height=self.size_y, background="#7A7A7a") self.xsb = ttk.Scrollbar(self, orient="horizontal", command=self.canvas.xview) self.ysb = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.ysb.set, xscrollcommand=self.xsb.set) self.canvas.configure(scrollregion=(0,0,self.total_size_x,self.total_size_y)) self.xsb.grid(row=1, column=0, sticky="ew") self.ysb.grid(row=0, column=1, sticky="ns") self.canvas.grid(row=0, column=0, sticky="nsew") self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self.tiles=[[Source(root,self,r,i) if r==0 else Tile(root,self,r,i) for i in range(self.total_size_y//self.tile_size)] for r in range(self.total_size_x//self.tile_size)] for a in self.tiles: for b in a: b.generate_shortcuts() self.flags={} self.relay_states=[] self.relay_groups=[] self.canvas.bind("<ButtonPress-1>", self.click) self.canvas.bind("<Shift-ButtonPress-1>", self.shift_click) self.canvas.bind("<Control-ButtonPress-1>", self.scroll_start) self.canvas.bind("<Control-B1-Motion>", self.scroll_move) self.canvas.bind("<MouseWheel>", self.on_mousewheel_y) self.canvas.bind("<Shift-MouseWheel>", self.on_mousewheel_x) self.bind("s", lambda x:self.app.tools.change_tool("select")) self.bind("a", lambda x:self.app.tools.change_tool("auto")) self.bind("f", lambda x:self.app.tools.change_tool("flag")) self.bind("h", lambda x:self.app.tools.change_tool("hswitch")) self.bind("x", lambda x:self.app.tools.change_tool("delete")) self.root.bind("<Left>", lambda x:self.move_selection('l')) self.root.bind("<Down>", lambda x:self.move_selection('d')) self.root.bind("<Up>", lambda x:self.move_selection('u')) self.root.bind("<Right>", lambda x:self.move_selection('r')) # self.canvas.bind("", lambda event: self.focus_set()) self.previous_shift_comand=False # self.canvas.bind('<Motion>',self.motion) #Manual Initial selection self.sel_x=1 self.sel_y=0 self.canvas.create_rectangle(self.sel_x*self.tile_size,self.sel_y*self.tile_size, self.sel_x*self.tile_size+self.tile_size,self.sel_y*self.tile_size+self.tile_size, tags="selection_box",outline="#0000FF") self.tiles[self.sel_x][self.sel_y].frame.grid(column=1,row=1, sticky="nsew")
# -*- coding: utf-8 -*- from shanten import Shanten from tiles import Tile import time if __name__ == '__main__': print("Enter '!end' to end this program") print("Made by Zachary") print("1-9m:万子,1-9p:饼/筒, 1-9s:索/条,1-7z:东南西北白发中") print("鸣牌用空格隔开,暗杠用五个来表示,例:123m456s22z 11111z 234m") print("------" * 6) while True: tile_str = input("Input your tiles:\n") if tile_str == "!end": break start = time.time() your_tile = Tile(tile_str) if your_tile.error_state: print("[Error]:Please input right tiles.") else: hand_tiles = your_tile.hand_tiles rest_tiles = your_tile.rest_card shanten_data = Shanten.get_shanten_data(hand_tiles) Shanten.print_shanten_message(shanten_data, rest_tiles) print("[time_use:]", round(time.time() - start, 3), "s") print("------" * 6)
def addRoofTile(self, tileIndex, x, y): self.tilestacks[y*self.widthInTiles+x].addRoofTile(Tile(self.tileFactory, tileIndex))
def runGame(): """Runs the game, duh!""" #initialize window and such settings = Settings() game.init() game.font.init() screen = game.display.set_mode( (settings.screenWidth, settings.screenHeight)) game.display.set_caption(settings.title) character = boy(screen) game.display.set_icon(character.image) font = Fonts(character) total = 2 #create a path pathList = [] for i in range(0, 20): path = Tile('OverworldPath.png', screen.get_rect().centerx, screen.get_rect().bottom - (i * 32), screen, 0) pathList.append(path) #create a wall wallList = [] for i in range(0, 8): for j in range(0, 8, 2): wall = Tile('OverworldWall.png', (screen.get_rect().centerx * 1.5) + (i * 32), (screen.get_rect().centery * 1.5) + (j * 32), screen, 1) wallList.append(wall) for i in range(0, 15): wall = Tile('OverworldWall.png', 240, 0 + (32 * i), screen, 1) wallList.append(wall) for i in range(0, 4): wall = Tile('OverworldWall.png', 272 + (32 * i), 96 + (32 * i), screen, 1) wallList.append(wall) #generate some rocks rockList = [] for i in range(0, total): randX = randint(0, 1200 - 32) randY = randint(0, 800 - 32) rock = Tile('OverworldRock.png', randX, randY, screen, 1) rockList.append(rock) usedMinerals = [] mineral = -1 bossPresent = False bossCounter = 0 #main loop for game while True: if len(usedMinerals) % total == 0 and bossPresent == False and len( usedMinerals) != 0: boss1 = Tile('BossRock.png', 583, 120, screen, 1) bossPresent = True bossCounter += 1 while len(rockList) > 0: rockList.pop() rockList.append(boss1) if character.stage == "OVERWORLD": character.walkAnimate() character.checkCollision(wallList) if character.checkCollision(rockList) == True: while True: mineral = randint(1, 10) if mineral not in usedMinerals: break if bossPresent == True: enemy = Rock(11 * bossCounter, screen) else: enemy = Rock(mineral, screen) character.stage = "BATTLE" character.setBattleImage("Battle.png") character.updatePos() if character.stage == "BATTLE": gf.checkEvents(character, font, enemy, rockList, mineral, usedMinerals, bossPresent) gf.updateScreen(settings, screen, character, pathList, wallList, rockList, font, enemy) else: gf.checkEvents(character, font) gf.updateScreen(settings, screen, character, pathList, wallList, rockList, font)