def _setup_default_defenders(self, element=None, name='Defenders'): """ TODO -- remove this -- its either a testing method, which should be in the tests, or a method for initializing fields with some units. """ if self._defenders is not None: raise ValueError('Defenders already set up') if element is None: element = self.field.element s = Stone() s[element] = 4 s[OPP[element]] = 0 for o in ORTH[element]: s[o] = 2 for n in xrange(8): self.silo.imbue(s.copy()) wcomp = Stone().comp units = [] for wep in WEP_LIST: unit = self.form_scient(element, s.comp) units.append(unit) w = self.form_weapon(element, wcomp, wep) self.name_unit(unit.uid, "Ms. " + wep) self.equip_scient(unit.uid, w.stronghold_pos) s = self.form_squad(unit_ids=[u.uid for u in units], name=name) self.defenders = s return s
def max_comp(suit, kind='Scient'): """Returns the maximum composition of 'kind' of element 'suit'""" comp = Stone() if kind == 'Scient': comp[suit] = 255 comp[OPP[suit]] = 0 comp[ORTH[suit][0]] = comp[ORTH[suit][1]] = 127 return comp if kind == 'Weapon': comp2 = Stone() comp2[suit] = comp[suit] = 63 comp2[OPP[suit]] = comp[OPP[suit]] = 0 comp2[ORTH[suit][0]] = comp[ORTH[suit][1]] = 0 comp2[ORTH[suit][1]] = comp[ORTH[suit][0]] = 63 return (comp, comp2) if kind == 'Nescient': comp2 = Stone() comp2[suit] = comp[suit] = 255 comp2[OPP[suit]] = comp[OPP[suit]] = 0 comp2[ORTH[suit][0]] = comp[ORTH[suit][1]] = 0 comp2[ORTH[suit][1]] = comp[ORTH[suit][0]] = 254 return (comp, comp2) if kind == 'Stone': for i in comp: comp[i] = 255 return comp
def __init__(self, data=None, name=None, kind=None, element=None): self.val = 0 self.free_spaces = 8 self.name = name UserList.__init__(self) if data == None: # The code below creates 4 units of element with a comp # of (4,2,2,0). Each unit is equiped with a unique weapon. if kind == 'mins': if element != None: s = Stone() s[element] = 4 s[OPP[element]] = 0 for o in ORTH[element]: s[o] = 2 for wep in WEP_LIST: scient = Scient(element, s) scient.equip(eval(wep)(element, Stone())) scient.name = "Ms. " + wep self.append(scient) else: raise ("Kind requires element from %s." % ELEMENTS) if self.name == None: self.name = element + " " + 'mins' return if isinstance(data, list): for x in data: self.append(x) else: self.append(data)
def init_levels(self): level1 = Level() self.generate_ground(level1) for i in range(2, 8): level1.blocks.add( Crate((1200, self.window_height - 102 * i), (0, 0), 100, 100, "crate")) level1.blocks.add( Stone((1500, self.window_height - 310), (0, 0), 200, 200, "stone")) level1.enemies.add( Sheep((1500, self.window_height - 400), (0, 0), 100, 100, "sheep")) level2 = Level() self.generate_ground(level2) level2.blocks.add( Crate((1200, self.window_height - 200), (0, 0), 100, 100, "crate")) level2.blocks.add( Stone((1300, self.window_height - 200), (0, 0), 100, 100, "stone")) level2.blocks.add( Ice((1400, self.window_height - 200), (0, 0), 100, 100, "Ice")) level2.enemies.add( Sheep((1500, self.window_height - 200), (0, 0), 100, 100, "sheep")) level2.enemies.add( Sheep((1000, self.window_height - 200), (0, 0), 100, 100, "sheep")) level3 = Level() self.generate_ground(level3) level3.enemies.add(Ice((400, 900), (0, 0), 100, 100, "Ice")) level3.enemies.add(Sheep((300, 900), (0, 0), 100, 100, "sheep")) self.levels = [level1, level2, level3]
def __init__(self, element, comp, name=None, weapon=None, weapon_bonus=None, location=None, sex='female'): for orth in ORTH[element]: if comp[orth] > comp[element] / 2: raise ValueError("Scients' orthogonal elements cannot be \ more than half the primary element's value.") Unit.__init__(self, element, comp, name, location, sex) self.move = 4 self.weapon = weapon if weapon_bonus == None: self.weapon_bonus = Stone() else: self.weapon_bonus = weapon_bonus self.equip_limit = Stone({E: 1, F: 1, I: 1, W: 1}) for i in self.equip_limit: self.equip_limit[i] = self.equip_limit[i] + self.comp[i] \ + self.weapon_bonus[i] self.calcstats() #equiping weapons should be done someplace else. self.equip(self.weapon)
def test_board_setitem(self): board = self._get_empty_board() board_obj = Board(board, BOARD_DIM) board_obj[0][0] = Stone(BLACK_STONE) self.assertTrue(Stone(BLACK_STONE), board_obj[0][0]) board_obj[0][0] = Stone(WHITE_STONE) self.assertTrue(Stone(WHITE_STONE), board_obj[0][0])
def _update_comp_value(self): """ Sets self.comp to average of tiles' comps """ c = Stone() for t in self.iter_tiles(): for e, v in t.comp.iteritems(): c[e] = v for e, v in c.iteritems(): self.comp[e] = v / self.size
def parse_move(arr): if isinstance(arr[1], str): return Stone(arr[0]).get_type(), arr[1] else: return Stone(arr[0]).get_type(), [ str_to_point(arr[1][0]), [parse_board(board) for board in arr[1][1]] ]
def __init__(self, element, comp, name=None, weapon=None, sex='female', facing=None, body=None): if body is None: body = {'head': None, 'left': None, 'right': None, 'tail': None} comp = Stone(comp) orth = comp.orth(element) if all(orth): raise ValueError("Nescients' cannot have values greater than zero " "for both orthogonal elements.") for o in orth: if o > comp[element]: raise ValueError("Nescients' orthogonal value cannot exceed " "the primary element value.") super(Nescient, self).__init__(element, comp, name=name, sex=sex) # Set nescient type. if self.element == 'Earth': self.kind = 'p' if self.comp[F] == 0: self.type = 'Avalanche' # AOE Full else: self.type = 'Magma' # ranged Full elif self.element == 'Fire': self.kind = 'p' if self.comp[E] == 0: self.type = 'Firestorm' # ranged DOT self.time = 3 else: self.type = 'Forestfire' # ranged Full elif self.element == 'Ice': self.kind = 'm' if self.comp[E] == 0: self.type = 'Icestorm' # AOE DOT self.time = 3 else: self.type = 'Permafrost' # AOE Full else: # Wind self.kind = 'm' self.time = 3 if self.comp[F] == 0: self.type = 'Blizzard' # AOE DOT else: self.type = 'Pyrocumulus' # ranged DOT self.calcstats() for part in body: # MESSY!!!! body[part] = Part(self) self.body = body self.facing = facing self.weapon = self # hack for attack logic. # state machine first attempt self.afraid = False self.hungry = False self.in_season = False self.found_mate = False self.ready_to_mate = False
def harvest_stones(self): """returns set of stones generated at harvest""" stones = Stone() for x in xrange(self.grid.x): for y in xrange(self.grid.y): for suit, value in self.grid[x][y].comp.iteritems(): stones[suit] += value for suit, value in stones.iteritems(): stones[suit] /= 8 #8 seems like a good number... return stones
def get_tile_comps(self): """returns a list of stones 1/8th the value of the tile comps.""" stone_list = [] for tile in self.grid.iter_tiles(): stone = Stone() for suit, value in tile.comp.iteritems(): stone[suit] += value / 8 # this 8 will need to be tweaked. if stone.value() != 0: stone_list += [stone] return stone_list
def process_stone(frame_desc, id, contour, src_img, result_img, save_stones=None): m = cv2.moments(contour) try: cx = int(m['m10'] / m['m00']) cy = int(m['m01'] / m['m00']) except: return None bbox = cv2.boundingRect(contour) ec, es, ea = cv2.minAreaRect(contour) ec = (int(ec[0]), int(ec[1])) es = (int(es[0]) / 2, int(es[1]) / 2) ea = int(ea) if es[1] > es[0]: es = es[1], es[0] ea += 90 ea = ea % 180 resy, resx, _ = src_img.shape if not preselect_stone((resx, resy), ec, es): return None cutout = src_img[bbox[1]:bbox[1] + bbox[3], bbox[0]:bbox[0] + bbox[2]] b, g, r = cv2.split(cutout) a = np.zeros_like(b, dtype=np.uint8) cv2.drawContours(a, [contour], 0, 255, -1, offset=(-bbox[0], -bbox[1])) cropped = cv2.merge((b, g, r, a)) color = find_dominant_color(cropped) structure = lbp_histogram(cropped) if result_img is not None: dummy = np.array([np.array([color])]) rgb_color = (cv2.cvtColor(dummy, cv2.COLOR_LAB2BGR)[0, 0]).tolist() cv2.drawContours(result_img, [contour], 0, rgb_color, -1) cv2.circle(result_img, ec, 4, (128, 0, 0)) cv2.rectangle(result_img, (bbox[0], bbox[1]), (bbox[0] + bbox[2], bbox[1] + bbox[3]), (255, 0, 0)) cv2.ellipse(result_img, ec, es, ea, 0, 360, (0, 0, 255)) ret = Stone(ec, es, ea, color, structure) if save_stones: cv2.imwrite( 'stones/stone_{}_{:03d}.{}'.format(frame_desc, id, save_stones), cropped) ret.save('stones/stone_{}_{:03d}.data'.format(frame_desc, id)) return ret
def addStone(self,side,pos,variant=NORMAL): stone = Stone(side,(pos[0]*34,pos[1]*34),variant) if side == ATTACKER: self.attack.append(stone) if side == DEFENDER: self.defense.append(stone)
def test_check_valid_move(): WIDTH = 600 stone = Stone(WIDTH) gc = GameController(WIDTH, stone) gc.counter = 2 gc.stone.total_row[3][3].color = 0 gc.stone.total_row[4][4].color = 0 gc.stone.total_row[3][4].color = 1 gc.stone.total_row[4][3].color = 1 assert gc.check_valid_move(4, 2) is True assert gc.check_valid_move(5, 3) is True assert gc.check_valid_move(2, 4) is True assert gc.check_valid_move(3, 5) is True assert gc.check_valid_move(3, 4) is False assert gc.check_valid_move(2, 2) is False assert gc.check_valid_move(0, 0) is False assert gc.check_valid_move(7, 7) is False gc.counter = 1 gc.stone.total_row[3][3].color = 0 gc.stone.total_row[4][4].color = 0 gc.stone.total_row[3][4].color = 1 gc.stone.total_row[4][3].color = 1 assert gc.check_valid_move(3, 2) is True assert gc.check_valid_move(4, 5) is True assert gc.check_valid_move(5, 4) is True assert gc.check_valid_move(2, 3) is True assert gc.check_valid_move(3, 4) is False assert gc.check_valid_move(2, 2) is False assert gc.check_valid_move(0, 0) is False assert gc.check_valid_move(7, 7) is False
def enter(): game_framework.reset_time() global map, player, house, background, avalanche, coin, snows, map_on_coins, game_over, santa, game_clear, distance, stones map = Map() player = Player() house = House() background = Background() avalanche = Avalanche() coin = Coin() game_over = Game_over() santa = Santa() game_clear = Game_clear() distance = Distance() map_on_coins = [Map_on_Coin() for i in range(200)] snows = [Snow() for i in range(20)] stones = [Stone() for i in range(10)] Player.x = 300.0 Player.y = 300.0 Player.unreal_x = 300.0 Player.unreal_y = 0 Player.jump_before_y = 0 Map.map_move_y_minor = 0 Avalanche.game_over = 0 Game_clear.game_clear = 0 Santa.game_clear = 0
def run_game(): #init游戏并创建一个窗口对象 pygame.init() ai_settings=Settings()#创建Settings类的实例 screen=pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height)) pygame.display.set_caption("地球保卫战 v1.0") #创建实例 sscol=Group() stone=Stone(screen) stats=GameStats(ai_settings) bullets=Group() ship=Ship(ai_settings,screen) sscol.add(ship) aliens=Group() button=Button(ai_settings,screen,"Play") score=Score(ai_settings,screen,stats) while True: #帧数 pygame.time.Clock().tick(120) #监视键盘和鼠标事件 func.check_events(ai_settings,screen,ship,aliens,bullets,button,stats,score) #决定游戏是否开始 if stats.game_status: ship.update() func.release_bullet(ai_settings,bullets,screen,aliens,stats,score) func.update_alien(ai_settings,screen,aliens,ship,stats,bullets,score,stone,sscol) #每次循环都重绘屏幕 func.update_screen(ai_settings,screen,ship,bullets,aliens,stats,button,score,stone)
def toggle(self, colour): """Put or remove stone at cursor.""" point = self._cursor.point if point in self._board: del self._board[point] else: self._board[point] = Stone(colour)
def one_three_zeros(value): squad = Squad() for i in ELEMENTS: s = Stone() s[i] = value squad.append(Scient(i, s)) return squad
def t2c(tup): """Converts a tuple to a comp""" if len(tup) != 4: raise Exception("Incorrect number of values in tuple") comp = Stone() for i in range(4): comp[ELEMENTS[i]] = tup[i] return comp
def rand_comp(suit=None, kind=None, max_v=255): """Returns a random comp in 'suit' for use instaniating 'kind' If 'suit' is not valid, random element used. If 'kind' is not valid stone is used if 'kind' is 'Stone' suit ignored""" if not suit in ELEMENTS: suit = rand_element() comp = Stone() if kind is None or kind not in KINDS: kind = 'Stone' if kind == 'Stone': for element in comp: comp[element] = random.randint(0, max_v) return comp else: if kind == 'Scient': comp[suit] = random.randint(1, max_v) for picked in ORTH[suit]: #NOTE: if comp[suit] = 1 orths will be 0. comp[picked] = random.randint(0, (comp[suit] / 2)) return comp else: #Nescient is currently the only other kind comp[suit] = random.randint(1, max_v) comp[random.choice(ORTH[suit])] = \ random.randint(1, comp[suit]) return comp
def process_stone(frame_desc, id, contour, src_img, result_img, save_stones=None): m = cv2.moments(contour) try: cx = int(m['m10'] / m['m00']) cy = int(m['m01'] / m['m00']) except: return None bbox = cv2.boundingRect(contour) ec, es, ea = cv2.minAreaRect(contour) ec = (int(ec[0]), int(ec[1])) es = (int(es[0]) / 2, int(es[1]) / 2) ea = int(ea) if es[1] > es[0]: es = es[1], es[0] ea += 90 ea = ea % 180 resy, resx, _ = src_img.shape if not preselect_stone((resx, resy), ec, es): return None cutout = src_img[bbox[1]:bbox[1] + bbox[3], bbox[0]:bbox[0]+ bbox[2]] b, g, r = cv2.split(cutout) a = np.zeros_like(b, dtype=np.uint8) cv2.drawContours(a, [contour], 0, 255, -1, offset=(-bbox[0], -bbox[1])) cropped = cv2.merge((b, g, r, a)) color = find_dominant_color(cropped) structure = lbp_histogram(cropped) if result_img is not None: dummy = np.array([np.array([color])]) rgb_color = (cv2.cvtColor(dummy, cv2.COLOR_LAB2BGR)[0, 0]).tolist() cv2.drawContours(result_img, [contour], 0, rgb_color, -1) cv2.circle(result_img, ec, 4, (128, 0, 0)) cv2.rectangle(result_img, (bbox[0], bbox[1]), (bbox[0] + bbox[2], bbox[1] + bbox[3]), (255, 0, 0)) cv2.ellipse(result_img, ec, es, ea, 0, 360, (0, 0, 255)) ret = Stone(ec, es, ea, color, structure) if save_stones: cv2.imwrite('stones/stone_{}_{:03d}.{}'.format(frame_desc, id, save_stones), cropped) ret.save('stones/stone_{}_{:03d}.data'.format(frame_desc, id)) return ret
def move(self, stones): num = 0 i = 0 j = 0 if (len(stones[0]) == 0 and len(stones[1]) == 0): return self.grid.center() # Get last stone of opponent opponentLastStone = stones[1][-1] if opponentLastStone.x + 66 < self.grid.WIDTH: finalCoord = Coordinate(opponentLastStone.x + 66, opponentLastStone.y) else: finalCoord = Coordinate(opponentLastStone.x - 66, opponentLastStone.y) for i in range(0, len(self.coordList), self.JUMP): coord = self.coordList[i] x = opponentLastStone.x + coord.x y = opponentLastStone.y + coord.y if x < 0 or y < 0 or x > self.grid.WIDTH or y > self.grid.HEIGHT: continue currStone = Stone(x, y) flag = 0 if not opponentLastStone.getFeasible(currStone): continue for l in range(0, 2): for stone in stones[l]: if not stone.getFeasible(currStone): flag = 1 break if flag == 1: break if flag == 1: continue stones[0].append(currStone) self.grid.setColor(stones) ret = self.grid.getColorDist() stones[0].pop() if (ret[0] > num): num = ret[0] finalCoord = Coordinate(currStone.x, currStone.y) return finalCoord
def test_read_file(): WIDTH = 600 stone = Stone(WIDTH) gc = GameController(WIDTH, stone) assert gc.score_list == [] # The default when scores.txt is blank gc.read_file('test_scores.txt') assert gc.score_list == [['Khai4', 22], ['Khai3', 20]]
def test_can_go(): WIDTH = 600 stone = Stone(WIDTH) gc = GameController(WIDTH, stone) gc.counter = 2 gc.stone.total_row[3][3].color = 0 # 4 starting stones gc.stone.total_row[4][4].color = 0 gc.stone.total_row[3][4].color = 1 gc.stone.total_row[4][3].color = 1 gc.can_go() assert len(gc.moves_list) == 4 # First move: 4 valids moves for player
def load_map(file, move_keys, player_number): # Load map # Load background color f = open(path.join("levels", file + ".txt"), "r") data = f.read() f.close() data = data.split("\n") data[0] = data[0].split(",") color = data[0] tile_chars = {} data.pop(0) # Load tiles while "=" in data[0]: tile_chars[data[0][0]] = data[0].split("=")[1].split(",") data.pop(0) # Initialize objects tiles = [] net = [] walkers = [] climbers = [] stones = [] players = [] # Load objects y = 1 for row in range(len(data)): x = -1 for tile in range(len(data[row])): if data[row][tile] in tile_chars: tiles.append( Tile(x, y, TILE_WIDTH, TILE_HEIGHT, tile_chars[data[row][tile]])) elif data[row][tile] == "p" and len(players) < player_number: players.append( Player(x, y, CHAR_WIDTH, CHAR_HEIGHT, 0, move_keys[len(players)])) elif data[row][tile] == "w": walkers.append(Walker(x, y, CHAR_WIDTH, CHAR_HEIGHT, 0)) elif data[row][tile] == "n": net.append(Net(x, y, TILE_WIDTH, TILE_HEIGHT, 6)) elif data[row][tile] == "c": net.append(Net(x, y, TILE_WIDTH, TILE_HEIGHT, 6)) climbers.append(Climber(x, y, CHAR_WIDTH, CHAR_HEIGHT, 0)) elif data[row][tile] == "s": stones.append(Stone(x, y, TILE_WIDTH, TILE_HEIGHT, 7)) x += TILE_WIDTH y -= TILE_HEIGHT # Return objects return tiles, net, stones, players, walkers, climbers, color
def test_is_corner(): WIDTH = 600 stone = Stone(WIDTH) gc = GameController(WIDTH, stone) assert gc.is_corner(0, 0) is True assert gc.is_corner(7, 7) is True assert gc.is_corner(0, 7) is True assert gc.is_corner(7, 0) is True assert gc.is_corner(1, 8) is None assert gc.is_corner(3, 4) is None assert gc.is_corner(2, 6) is None assert gc.is_corner(5, 5) is None
def __init__(self, color): self.xcoords = [800, 738, 676, 613, 550, 485, 373, 308, 247, 182, 121, 60, 60, 121, 182, 247, 308, 373, 485, 550, 613, 676, 738, 800] self.stones = [] self.movableStones = set() self.color = color self.restrict = False self.victory = False #configuring initial positions of stones per game logic for i in range(2): newStone = Stone(self.color, 1) self.stones.append(newStone) for i in range(3): newStone = Stone(self.color, 17) self.stones.append(newStone) for i in range(5): newStone = Stone(self.color, 12) newStone2 = Stone(self.color, 19) self.stones.append(newStone) self.stones.append(newStone2)
def test_is_edge(): WIDTH = 600 stone = Stone(WIDTH) gc = GameController(WIDTH, stone) assert gc.is_edge(0, 8) is True assert gc.is_edge(3, 0) is True assert gc.is_edge(4, 7) is True assert gc.is_edge(7, 4) is True assert gc.is_edge(1, 8) is None assert gc.is_edge(3, 4) is None assert gc.is_edge(2, 6) is None assert gc.is_edge(5, 5) is None
def update(self, dt): # 读入NUM_SAMPLES个取样 string_audio_data = self.stream.read(self.NUM_SAMPLES) k = max(struct.unpack('1000h', string_audio_data)) # 平均音量 if self.sample_count < 50: self.average_volume = (self.average_volume * self.sample_count + k) / (self.sample_count + 1) self.sample_count += 1 else: self.sample_count = 0 self.average_volume = 0 self.average_volume = (self.average_volume * self.sample_count + k) / (self.sample_count + 1) self.sample_count += 1 # print voice self.voiceBar.scale_x = self.average_volume / 10000.0 if self.role_run_to_right: self.role.x += 4 # self.floor.x -= 5 if self.role_run_to_left: self.role.x -= 4 # self.floor.x += 5 if self.role.can_shot: if self.sample_count == 50 and self.average_volume > 4000: pos = self.role.x + self.role.width * 0.8, self.role.y + self.role.height * 0.6 stone = Stone((self.average_volume - 3000) / 1000.0 + 1, pos, self.role.direction) self.stone = stone self.add(stone) self.role.can_shot = False # if k > 3000: # self.floor.x -= min((k / 20.0), 150) * dt # k > 8000: # self.role.jump((k - 8000) / 1000.0) # destination if (self.role.x + self.role.width / 2) >= self.floor.flag.x: time.sleep(0.5) self.end_game() self.role.pause_scheduler() return # spider trigger if self.role.x > self.floor.spider.x - 50: self.floor.spider.passed = True # collision self.role_collide() self.monster_collide_on_role() if not self.role.can_shot: self.stone_collide() self.monster_collide_on_stone()
def test_is_third_away(): WIDTH = 600 stone = Stone(WIDTH) gc = GameController(WIDTH, stone) assert gc.is_third_away(2, 2) is True assert gc.is_third_away(5, 1) is True assert gc.is_third_away(1, 2) is True assert gc.is_third_away(2, 5) is True assert gc.is_third_away(1, 8) is None assert gc.is_third_away(6, 4) is None assert gc.is_third_away(3, 3) is None assert gc.is_third_away(4, 4) is None
def move(self, position): reverse_stons = [] # 石を打つ self.board[position.y][position.x] = Stone(self.turn.value) # 石をひっくり返す # 各方向に石をひっくり返せるか調べる for dx, dy in Board.DIRS: y = position.y + dy x = position.x + dx enemy = self.turn.invert() if self.in_board(x, y) \ and self.board[y][x] == enemy: # 隣が相手の石 y += dy x += dx while self.in_board(x, y) \ and self.board[y][x] == enemy: y += dy x += dx if self.in_board(x, y) \ and self.board[y][x] == self.turn: # この方向は返せる # 1マス戻る y -= dy x -= dx # 戻りながら返す stons = [] while self.in_board(x, y) \ and self.board[y][x] == enemy: self.board[y][x] = Stone(self.turn.value) stons.append([x, y]) y -= dy x -= dx reverse_stons.append(stons) self.turn = self.turn.invert() # 手番を変更 self.move_num += 1 # 手数を増やす return reverse_stons
def __init__(self, element, comp, name=None, location=None, sex='female'): if not element in ELEMENTS: raise Exception("Invalid element: %s, valid elements are %s" \ % (element, ELEMENTS)) if comp[element] == 0: raise ValueError("Units' primary element must be greater than 0.") if comp[OPP[element]] != 0: raise ValueError("Units' opposite element must equal 0.") Stone.__init__(self, comp) self.element = element if name == None: self.name = self.__hash__() self.name = name self.location = location self.sex = sex self.DOB = datetime.utcnow() self.DOD = None self.val = self.value() def __repr__(self): return self.name
def equip(self, weapon): #TODO move to battlefield """ A function that automagically equips items based on element. should be moved someplace else. """ if weapon == None: if self.element == 'Earth': self.weapon = Sword(self.element, Stone()) elif self.element == 'Fire': self.weapon = Bow(self.element, Stone()) elif self.element == 'Ice': self.weapon = Wand(self.element, Stone()) else: self.weapon = Glove(self.element, Stone()) else: ''' if weapon.value() > self.equip_limit[weapon.type]: raise Exception("This unit cannot equip this weapon") else: self.weapon = weapon ''' self.weapon = weapon
def start(self): while 1: serverResponse = self.s.recv(1024) data = serverResponse.split() # Check if the game has ended if int(data[0]) == 1: break self.noOfMoves = int(data[1]) - 1 self.playersMovedTillNow = int(data[1]) if (self.playersMovedTillNow < self.NUMBER_OF_PLAYERS): for i in range(0, self.playersMovedTillNow): self.lastMoveOfOpponent_x = int(data[2 + i * 3]) self.lastMoveOfOpponent_y = int(data[2 + i * 3 + 1]) self.stones[1].append( Stone(self.lastMoveOfOpponent_x, self.lastMoveOfOpponent_y)) self.greedy.updatePull(self.stones, 1) else: startIndex = self.playersMovedTillNow - self.NUMBER_OF_PLAYERS + 1 for i in range(startIndex, self.playersMovedTillNow): self.lastMoveOfOpponent_x = int(data[2 + i * 3]) self.lastMoveOfOpponent_y = int(data[2 + i * 3 + 1]) self.stones[1].append( Stone(self.lastMoveOfOpponent_x, self.lastMoveOfOpponent_y)) self.greedy.updatePull(self.stones, 1) nextMove = self.greedy.move(self.stones) self.stones[0].append(Stone(nextMove.x, nextMove.y)) self.greedy.updatePull(self.stones, 0) self.s.sendall(str(nextMove.x) + " " + str(nextMove.y)) self.s.close()
def max_squad_by_value(value): """Takes an integer, ideally even because we round down, and returns a squad such that comp[element] == value, comp[orth] == value/2, comp[opp] == 0""" squad = Squad() value = value / 2 #more logical, really. half = value / 2 for i in ELEMENTS: s = Stone() s[i] = value s[OPP[i]] = 0 for o in ORTH[i]: s[o] = half squad.append(Scient(i, s)) return squad
def __init__(self, comp=Stone(), x=16, y=16, tiles=None): Stone.__init__(self, comp) self.x, self.y = self.size = (x, y) if self.value() == 0: if tiles == None: self.tiles = {} for i in range(x): row = {} for j in range(y): row.update({j: Tile()}) self.tiles.update({i: row}) else: for x in xrange(self.x): for y in xrange(self.y): for suit, value in tiles[x][y].iteritems(): self.comp[suit] += value for suit in self.comp.keys(): self.comp[suit] /= self.x * self.y self.tiles = tiles else: #needs to check for comp/tiles match currently assumes if comp, no tiles. #creates a pool of comp points to pull from. pool = {} for suit, value in self.comp.iteritems(): pool[suit] = value * self.x * self.y #pulls comp points from the pool using basis and skew to determine the range of random #values used create tiles. Tiles are then shuffled. tiles_l = [] for i in xrange(x-1): row_l = [] for j in xrange(y): """This is pretty close, needs tweeking.""" new_tile = {} for suit, value in pool.iteritems(): '''This determines the range of the tile comps.''' #good enough for the time being. basis = self.comp[suit] skew = 2*random.randint(2,8) pull = random.randint(basis-skew, basis+skew) nv = min(pull, pool[suit]) pool[suit] -= nv new_tile[suit] = nv row_l.append(new_tile) row = {} random.shuffle(row_l) #shuffles tiles in temp. row. tiles_l.append(row_l) #special error correcting row row_e = [] for k in xrange(y): new_tile = {} for suit, value in pool.iteritems(): if pool[suit] != 0: fract = pool[suit]/max(1, k) else: fract = 0 nv = min(fract, pool[suit]) pool[suit] -= nv new_tile[suit] = nv row_e.append(new_tile) #hacks upon hacks pt2 del row_e[-1] half = {} for suit, value in row_e[-1].iteritems(): half[suit] = int(value/2) row_e[-1][suit] -= half[suit] row_e.append(half) tiles_l.append(row_e) self.tiles = {} random.shuffle(tiles_l) #shuffles temp rows. for x in xrange(self.x): row = {} for y in xrange(self.y): #This shuffles the tiles before putting them in the grid. r_index = random.choice(range(len(tiles_l))) # pick a row c_index = random.choice(range(len(tiles_l[r_index]))) #pick a tile row.update({y: Tile(tiles_l[r_index][c_index])}) #place tile in grid del tiles_l[r_index][c_index] #remove used tile if len(tiles_l[r_index]) == 0: #remove empty rows from tiles_l del tiles_l[r_index] self.tiles.update({x: row}) del tiles_l
def __init__(self, comp=Stone(), contents=None): Stone.__init__(self, comp) self.contents = contents
def __init__(self, element, comp, wep_type): #this should return the correct weapon based on . (?) Stone.__init__(self, comp) self.type = wep_type self.element = element