def add_deco(self, tile_map, max_x, max_y): """ Add the decorative object. Note that the decoration is a GameObject! :param tile_map: :param max_x: :param max_y: :return: nothing """ list_doors = [door_def[0] for door_def in self.doors] for i in range(20): place = random.choice(self.places) weight = self.compute_tile_weight(place[0], place[1], [Tile.FLOOR], tile_map, max_x, max_y) near_door = (place[0], place[1] - 1) in list_doors or \ (place[0], place[1] + 1) in list_doors or \ (place[0] - 1, place[1]) in list_doors or \ (place[0] + 1, place[1]) in list_doors if not (near_door or not (tile_map[place].floor_type == Tile.FLOOR) or tile_map[ place].has_things) and weight == 15: a_deco = random.choice(self.building.decoration_list["1x1"]) decoration = GameObject(a_deco[0], GameObject.DECORATION, town=self.town, weight=random.randint(1, 10), volume=random.randint(1, 5), regular_value=random.randint(2, 10), displayable_object=DisplayableObject(movable=False, blocking=a_deco[1], position_on_tile=place, graphical_representation= AnimatedSpriteObject( Constants.DAWNLIKE_STYLE, "Objects", "Decor", a_deco[2]))) GameData.register_object(decoration)
def parse(self, game): type = game.attrib["type"] score = int(game.attrib["score"]) if type == "SingleImage": img = game.find("./img") image = img.attrib["src"] image = os.path.join(self.dataPath, "img", image) return GameData.SingleImageGameData(image, score) elif type == "ImageReveal": img = game.find("./img") image = img.attrib["src"] image = os.path.join(self.dataPath, "img", image) return GameData.ImageRevealGameData(image, score) elif type == "WhoIsLying": quote = game.find("./quote").text answerlistTag = game.find("./answerList") answerList = [] answerKey = [] for answerTag in answerlistTag: key = True if answerTag.attrib["isLying"] == "True" else False answer = answerTag.text answerKey.append(key) answerList.append(answer) #TODO return GameData.WhoIsLyingGameData(quote, answerList, answerKey, None, score) elif type == "Sound": soundfile = game.find("./sound").attrib["src"] soundfile = os.path.join(self.dataPath, "snd", soundfile) image = os.path.join("data", "res", "music.png") return GameData.SoundGameData(soundfile, image, score)
def main(): #Config gameData = GameData() gameData.setupCLA() pygame.init() gameData.screen = pygame.display.set_mode((600, 600)) pygame.display.set_caption('Snake') gameData.appleimage = pygame.Surface((10, 10)) gameData.appleimage.fill((0, 255, 0)) gameData.img = pygame.Surface((20, 20)) gameData.img.fill((255, 0, 0)) gameData.font = pygame.font.SysFont('Arial', 20) if gameData.playData and gameData.loadData: replayRoutine( gameData ) if gameData.humanTrain and not gameData.trainPause: if gameData.loadWeights: playSnake = MLP(2, 1) loadWeights(playSnake,gameData) criterion = NLLLoss(gameData.lin1M) else: if gameData.loadData: gameData.interpretFromFile() playSnake = MLP(2, 1) playSnake.add(Linear( gameData.lin1M, gameData.lin1N)) playSnake.add(Sigmoid(gameData.lin1N)) playSnake.add(Linear(gameData.lin1N,gameData.lin2N)) playSnake.add(Softmax(gameData.lin2N)) criterion = NLLLoss(gameData.lin1M) train(np.asarray(gameData.trainData[:-2]), np.asarray(gameData.trainTargetOutput[1:]) , playSnake, criterion) print "Done Training" if gameData.customFileName != "": writeWeights(playSnake, gameData) aiGameRoutine( gameData, playSnake) else: regularGameRoutine( gameData )
def run(self): try: self.gameState = self.loader.gameManager.gameState self.datafile = self.gameState.gameFile self.dataPath = self.gameState.gameFilePath self.restore = self.gameState.restore_from_savefile self.saveFile = self.gameState.savefile self.loader.setText("Parse Datei") tree = ET.parse(self.datafile) root = tree.getroot() self.checkVersion(root.attrib["file-format-version"]) categoryNames = [] gameData = [] for categoryRoot in root: gameDataInCategory = [] catName = categoryRoot.attrib["name"] self.loader.setText("Erzeuge Kategorie " + catName) categoryNames.append(catName) for i in range(5): game = categoryRoot[i] gameDataInCategory.append(self.parse(game)) gameData.append(gameDataInCategory) self.gameState.menuGameData = GameData.MenuGameData( categoryNames, None, None) self.gameState.gameData = gameData except: self.loader.gameManager.needQuit = True
def next_turn(self): self.ticks += 1 # print("Tick {} - Future Actions: {}".format(self.ticks, self.schedule)) actions = self.schedule.pop(self.ticks, []) for object_id in actions: if GameData.object_exist(object_id): GameData.game_dict[object_id].take_action() return
def main(): #初始化公共数据 GameData.InitGameData() from twisted.internet import reactor reactor.listenTCP(port, GameData.gameFactory) print("start!!!") reactor.run() print("end!!!")
def initialize(self, base_info, diff_data, game_setting): self.base_info = base_info self.diff_data = diff_data self.game_setting = game_setting # GameDataのインスタンスを生成 self.GameData = gd.GameData(self.base_info, self.diff_data, self.game_setting) self.agent = pr.Pumpkin_random(self.GameData) print("-----------------新しいゲーム-------------------") print("生存者: %s" % self.GameData.aliveAgent) print("自分の陣営:%s陣営" % self.GameData.myCamp) print("自分の役職:%s" % self.GameData.myRole) print("ゲームの設定:%s人人狼" % self.GameData.playerNum)
tempDF = self.df[(self.df[self.secondary] > 0) & (~ self.df[CREW_ID_COL].isin(used_crew))] seats.assign(SKILL_SEAT_MAP[self.secondary][0], tempDF.iloc[0][CREW_ID_COL]) seats.assign(SKILL_SEAT_MAP[self.secondary][1], tempDF.iloc[1][CREW_ID_COL]) # Then do the primary skill seats used_crew = set(seats.seats.values()).difference({None}) tempDF = self.df[(self.df[self.primary] > 0) & (~ self.df[CREW_ID_COL].isin(used_crew))] seats.assign(SKILL_SEAT_MAP[self.primary][0], tempDF.iloc[0][CREW_ID_COL]) seats.assign(SKILL_SEAT_MAP[self.primary][1], tempDF.iloc[1][CREW_ID_COL]) return seats, self.__calc_duration(seats) if __name__ == "__main__": sample_config = ['sec', 'cmd', 2700] game_data = GameData.load_game_data(max_days_old=7) opt = Optimizer(game_data, *sample_config) results = {SKILLMAX_COL: opt.optimize_crew_skillmax_strategy(), VOYTOTAL_WEIGHTED_COL: opt.optimize_crew_voytotal_strategy(use_weighted=True), VOYTOTAL_COL: opt.optimize_crew_voytotal_strategy(use_weighted=False), PRISEC_COL: opt.optimize_crew_prisec_strategy()} for strategy, (seats, durations) in results.items(): print() print(strategy) print(seats) print(seats.pretty_skill_totals()) print(seats.pretty_skill_totals_for_bot(*sample_config)) print(', '.join([time_format(t) for t in durations]))
import cocos import GameData import Map import buildMenu cocos.director.director.init(width=800, height=600, autoscale=True, resizable=True) # Create the scenes map = Map.MainMap(None) game_data = GameData.GameData(10, 10, 10, 10, 10, 10, map) map.add_hex(Map.Hex(10, 7, GameData.tile_information['LaunchPad'])) #map.addBSS(building_select_layer, buildingSelect_scene) map_scene = cocos.scene.Scene(map) # And now, start the application, starting with main_scene cocos.director.director.run(map_scene) # or you could have written, without so many comments: # director.run( cocos.scene.Scene( HelloWorld() ) )
def computeIntervalPeaks (interval, threshold=1.6, npeaks=3, impute=False): ''' For a given interval in days, and a given threshold, peaks are detected according to the method specified in the 2016 spec. The multiplier is the multiple of the stdev that defines a peak. Output is a list of triples, each containing the timeslot index (starting at the start of boot), the threshold, and the amount by which the peak exceeded the threshold in kWh. If impute is True, then boot data is not used, but rather imputed by sampling the game data. This is needed to get good results from pre-2016 games where demand elasticity was excessively high. ''' # start by finding the mean consumption in the boot sim records, so we # can normalize the boot numbers. Necessary only for records prior to # 2016 if gameData.dataType != 'net-demand': gameData.reset('net-demand') if impute: gameData.imputeBootData() else: gameData.ensureBootData() gameData.ensureGameData() #bootScale = {} bc = copy.deepcopy(gameData.bootDict) gc = copy.deepcopy(gameData.gameDict) print('{} games, {} boots'.format(len(gc), len(bc))) #for gameId in bc.keys(): # bootMean = st.mean(bc[gameId]) # gameMean = st.mean([x[1] for x in gc[gameId]]) # bootScale[gameId] = gameMean / bootMean # Get the production numbers #gameData.reset('production') #gameData.ensureBootData() #gameData.ensureGameData() #bp = gameData.bootDict #gp = gameData.gameDict # For each game, walk the boot record, then walk the game and collect # peak events for each interval, as specified by the interval, threshold, # and npeaks values. Each peak is recorded as [ts, val] where val is the # amount by which the peak exceeds the threshold results = {} for gameId in gc.keys(): print('game {}'.format(gameId)) runningMean = 0.0 runningVar = 0.0 runningSigma = 0.0 runningCount = 0 scale = 1.0 # process a single boot record by the method of Welford, as outlined # in Knuth ACP, vol 2 Seminumerical Algorithms, Sec. 4.2.2 Eq. 15, 16. for net in bc[gameId]: #net = prod + scale * cons if runningCount == 0: # first time through runningMean = net runningCount = 1 else: lastM = runningMean runningCount += 1 runningMean = lastM + (net - lastM) / runningCount runningVar = runningVar + (net - lastM) * (net - runningMean) runningSigma = math.sqrt(runningVar / (runningCount -1)) # process the corresponding game nets = [] remaining = interval * 24 result = [] results[gameId] = result for net in gc[gameId]: #net = prod[1] + cons[1] nets.append([runningCount, net[1]]) lastM = runningMean runningCount += 1 runningMean = lastM + (net[1] - lastM) / runningCount runningVar = runningVar + (net[1] - lastM) * (net[1] - runningMean) runningSigma = math.sqrt(runningVar / (runningCount -1)) remaining -= 1 if remaining == 0: # time to assess nets.sort(reverse=True, key=lambda x: x[1]) thr = runningMean + threshold * runningSigma for i in range(npeaks): ev = nets[i] if ev[1] > thr: result.append([ev[0], thr, ev[1] - thr]) remaining = interval * 24 nets = [] return results
generated as pc.plotContours(pc.weekdayData, [.02,.25,.5,.75,.98]) ''' import numpy as np import scipy as sp import matplotlib.pyplot as plt import matplotlib.lines as mline import pylab as pl from scipy import stats import statistics as st import math, copy import GameData as gc # fill in with an appropriate GameData instance gameData = gc.GameData() def plotMeans (dataInterval='Daily', dataType='net-demand', showTitle=False): ''' Reduces the raw data into means and 1-sigma error bars, plots result ''' if gameData.dataType != dataType: gameData.reset(dataType) data = gameData.dataArray(dataInterval) d = [np.array(c) for c in data] print('Shape:', np.shape(d)) means = [c.mean() for c in d] stds = [c.std() for c in d] x = range(np.shape(d)[0]) if showTitle:
import GameData gamedata = GameData.GameData() while 1: hs = gamedata.getHabitats() print("You have " + str(gamedata.getHabitats()) + " habitats") print("You have " + str(gamedata.getHabitatMaterial()) + " Habitat Materal") hconsume = raw_input("How Much Habitat Material do you want to order?") gamedata.addHabitatMaterial(hconsume) tiles = raw_input("How many habitats do you want to create?") gamedata.makeHabitats(tiles) gamedata.produce()
def start_new_game(cls, number_town): Util.DebugEvent("Initializing Time") GameData.time_ticker = Util.Ticker() Util.DebugEvent("Building new world") GameData.town_graph = Places.TownGraph([Places.Town(random.randint(2, 7)) for x in range(number_town)]) Util.DebugEvent("Choosing the initial town") GameData.current_town = random.choice(GameData.town_graph.towns) GameData.current_town.build_tile_map() Util.DebugEvent("Setting up player") GameData.player = Player.Player(GameData.current_town, graphical_representation=AnimatedSpriteObject(Constants.DAWNLIKE_STYLE, "Characters", "Player", (16, 112)), position_on_tile=GameData.current_town.tile_map.default_start_player_position) Util.DebugEvent("Setting up objects in the towns...") for town in GameData.town_graph.towns: for i in range(5): image_coordinate_x = [x * 16 for x in range(0, 7)] image_coordinate_y = [y * 16 for y in (3, 4, 7, 8)] coordinates = (random.choice(image_coordinate_x), random.choice(image_coordinate_y)) # npc = Player.TraderNPC(town, # position_on_tile=town.tile_map.get_place_in_building(Places.Building.TRADING_POST), # graphical_representation=Player.AnimatedSpriteObject(True, "Characters", "Player", coordinates)) npc = Player.NonPlayableCharacter(town, speed=(1, 3), position_on_tile=(i * 1, i * 2), graphical_representation=AnimatedSpriteObject( Constants.DAWNLIKE_STYLE, "Characters", "Player", coordinates)) GameData.register_object(npc) for i in range(25): """ name, object_type, weight=None, volume=None, regular_value=None, action_when_player=None, equipment=None, usable_part=None, breakable_parts=None, part_of_inventory=None, displayable_object=None): """ an_object = GameObject("A leftover object " + str(i), GameObject.JUNK, town=town, weight=random.randint(1, 10), volume=random.randint(1, 5), regular_value=random.randint(2, 10), displayable_object=DisplayableObject(movable=False, blocking=False, position_on_tile=( random.randint(0, town.tile_map.max_x - 1), random.randint(0, town.tile_map.max_y - 1)), graphical_representation=AnimatedSpriteObject( Constants.DAWNLIKE_STYLE, "Objects", "Ground", (16, 48)))) GameData.register_object(an_object) # a door is an open object for room in town.tile_map.rooms: for door in room.doors: GameData.register_object(Door(town, door[1], door[0], closed=True, locked=False)) Util.DebugEvent("Setting up objects in the other places (To be done later)...")