def advance(self): map_name = self.old.map.name item_name = self.fields.pop('Name') ######################## NAME POPPED # Popping Off Empty, Converting Rest to Int ############################ [self.fields.pop(key) for key, val in self.fields.items() if val == ""] [self.fields.__setitem__(key, int(val)) for key, val in self.fields.items()] # Save Image to Image Folder new_path = util.local_path('source/Maps/%s/items/%s.gif' % (map_name, item_name)) self.image.save( util.local_path(new_path), 'GIF', transparency=1 ) self.image.close() # Create Image Item if self.enemy: type = 'enemy' else: type = 'pickup' new_item = itemClass.MapItem(map_name, item_name, type, self.fields) # Place Image Item cur_x = self.old.posit[0] cur_y = self.old.posit[1] # Check If Item with this name Exisits for i, item in enumerate(self.old.map.items): if item.name == item_name: self.old.map.items[i] = new_item self.old.draw() self.master(self.old) return self.old.map.items += [new_item] self.old.map.spawn[cur_x][cur_y] = len(self.old.map.items) self.old.item_pos.max = (1, self.old.item_pos.max[1] + 1) # Change Mode self.old.draw() self.master(self.old)
def __load__(self): this_path = util.local_path('source/Maps/' + self.name) self.img = PhotoImage(file=this_path + '/background.gif') temp_file = open( this_path + '/config', 'r') # FILE OPENED # Read from the load file x, y = temp_file.readline().split(',') # READ LINE 1 self.size = (int(x), int(y)) line = temp_file.readline() # READ LINE 2 self.walls = util.BitGrid(int(x), int(y)) self.spawn = util.Grid(int(x), int(y)) self.items = [] # READ WALLS ##############################################<#<#<#<#<#<#< for row in range(self.size[1]): line = temp_file.readline() for col, value in enumerate(line.split(",")): self.walls[col][row] = int(value) line = temp_file.readline() # READ DIVIDE # READ ITEM SPAWNS ########################################<#<#<#<#<#<#< item_count = 0 for row in range(self.size[1]): line = temp_file.readline() for col, value in enumerate(line.split(",")): self.spawn[col][row] = int(value) item_count = max(item_count, int(value)) line = temp_file.readline() # READ DIVIDE # READ ITEM DEFENITIONS ###################################<#<#<#<#<#<#< for item in range(item_count): self.__load_item__(temp_file) temp_file.readline() # READ DIVIDE temp_file.close() # CLOSE FILE
def __create__(self, file, name, size): # Open the generation Image: temp_file = util.load_image(file, util.config.settings['Screen_Size']) # Create new Folder self.name = name this_path = util.local_path('source/Maps', self.name) if os.path.exists( this_path ): return -1 os.makedirs( this_path ) os.makedirs( this_path + '/items') # Save Background temp_file.save( this_path + '/background.gif' ) temp_file.close() # Write Config temp_file = open( this_path + '/config', 'w') ## Write Dimensions temp_file.write("%d, %d\n\n" % (size[0], size[1])) ## Write wall positions for i in range(size[1]): temp_file.write((' 0,' * size[0])[1:-1] + '\n') temp_file.write('\n') ## Write Object Start positions for i in range(size[1]): temp_file.write((' 0,' * size[0])[1:-1] + '\n') temp_file.write('\n') ## Write Object Defenitions: None ## Close config file and load from created files. temp_file.close() self.__load__()
def __init__(self, map, name, type, args): self.name = name self.image = util.load_image( util.local_path("source/Maps/%s/items/%s.gif" % (map, name)), alt=True) util.type_check(dict, args) # Instantiate type with args. self.type = type for key, value in args.items(): self.__setattr__(key.lower(), value)
def test_maps(): import mapClass as m util.sprint("\n#!# LOCAL TESTS: mapClass.py:") # Creating Testing Resources test = Tester() root = m.Tk() # Attempt to create Map Class try: test_map = m.Map() except Exception as err: util.sprint("Failed to Initialize map::Terminating") return # Attempt to make that Map class realize it's potential try: test_map.__create__(util.local_path("rsc/basicMap.gif"), '__temp__', (10, 5)) except Exception as err: util.sprint("Failed to Create Map::Terminating") return #Test creation test.assertion("Directory creation test", path.exists(temp_path), "Failed to create directory") test.assertion("Background creation test", path.exists(temp_path + '/background.gif'), "Failed to create Background image") test.assertion("Config creation test", path.exists(temp_path + '/config'), "Failed to create Config File") # Rearrange testing resources: for i in range(10): test_map.walls[randint(0,9)][randint(0,4)] = i try: test_map.__save__('__temp2__') temp_map = m.Map('__temp2__') except Exception as err: util.sprint("Failed during Load/Save") # Continue testing: test.assertion("Save/Load test", test_map.walls == temp_map.walls, "Grid comparison failed, ") # Cleanup testing resources: clean_map(file_name) clean_map('__temp2__') root.destroy() # End Message util.sprint("Map Class testing Complete! Failed: [" + str(test.failed) + "/" + str(test.run) + "]") # Return Testing Object return test
def __save__(self, name=None): if name is None: name = self.name this_path = util.local_path('source/Maps/', name) ## SAVE AS: if not os.path.exists( this_path ): orig_path = util.local_path('source/Maps/', self.name) os.makedirs( this_path ) os.makedirs( this_path + '/items') w_image = util.load_image("%s/background.gif" % (orig_path)) w_image.save(this_path + '/background.gif', format='gif') for item in self.items: w_image = util.load_image("%s/items/%s.gif" % (orig_path, item.name)) w_image.save( "%s/items/%s.gif"%(this_path, item.name), 'GIF', transparency = 1) w_image.close() ## SAVE: temp_file = open(this_path + '/config', 'w') temp_file.write("%d, %d\n\n" % (self.size[0], self.size[1])) temp_file.write(str(self.walls) + '\n\n') temp_file.write(str(self.spawn)) temp_file.write('\n\n') for item in self.items: temp_file.write(str(item) + '\n')
def __select__(self): if path.exists(util.local_path('source/Maps', self.text)): self.master.host.game.level.map.name = self.text self.master.host.game.level.map.__load__() self.master(Editor(self.master)) #This looks Sick-lical, it isn't # If input is invalid: else: self.text = "" if not self.errored: self.errored = True self.create_text( ( int(self['width'] )/2, int(self['height'])/2 + 20), text = "Map not Found! Try Again.", font = util.config.settings['Font'], fill = 'white' )
def __select__(self): if not path.exists(util.local_path('source/Maps', self.text)): next_mode = TileDimension(self.master) next_mode.load_from = self.load_from next_mode.load_to = self.text self.master(next_mode) # If input is invalid: else: self.text = "" if not self.errored: self.errored = True self.create_text( ( int(self['width'] )/2, int(self['height'])/2 + 20), text = "Already Exists! Try Again.", font = util.config.settings['Font'], fill = 'white' )
def __select__(self): if not path.exists(util.local_path('source/Maps', self.text)): self.old.menu = False self.old.map.__save__(self.text) self.old.map.name = self.text self.old.draw() self.master(self.old) # If input is invalid: else: self.text = "" if not self.errored: self.errored = True self.create_text( ( int(self['width'] )/2, int(self['height'])/2 + 20), text = "Already Exists! Try Again.", font = util.config.settings['Font'], fill = 'white' )
def get_database_path(): return local_path('store.sqlite3')
def __keypress__(self, event): # Up Key pressed: ###################################################### if event.keysym in util.config.keys['Menu_Up']: if self.lock_level == -1:############ MENU self.menu_pos[1] -= 1 elif self.lock_level == 0:############ GRID self.posit[1] -= 1 elif self.lock_level == 1:############ TILE self.map.walls[self.posit[0]][self.posit[1]] = 'Up' elif self.lock_level == 2:############ ITEM self.item_pos[1] -= 1 else:################################### ERROR raise AttributeError('lock_level out of range') # Down Key Pressed: #################################################### elif event.keysym in util.config.keys['Menu_Down']: if self.lock_level == -1: # MENU self.menu_pos[1] += 1 elif self.lock_level == 0: # GRID self.posit[1] += 1 elif self.lock_level == 1: # TILE self.map.walls[self.posit[0]][self.posit[1]] = 'Down' elif self.lock_level == 2: # ITEM self.item_pos[1] += 1 else: # ERROR raise AttributeError('lock_level out of range') # Left Key Pressed: #################################################### elif event.keysym in util.config.keys['Menu_Left']: if self.lock_level == -1:############ MENU pass elif self.lock_level == 0:############ GRID self.posit[0] -= 1 elif self.lock_level == 1:############ TILE self.map.walls[self.posit[0]][self.posit[1]] = 'Left' elif self.lock_level == 2:############ ITEM pass else:################################### ERROR raise AttributeError('lock_level out of range') # Right Key Pressed: ################################################### elif event.keysym in util.config.keys['Menu_Right']: if self.lock_level == -1:############ MENU pass elif self.lock_level == 0:############ GRID self.posit[0] += 1 elif self.lock_level == 1:############ TILE self.map.walls[self.posit[0]][self.posit[1]] ='Right' elif self.lock_level == 2:############ ITEM pass else:################################### ERROR raise AttributeError('lock_level out of range') # Select Key Pressed: ################################################## elif event.keysym in util.config.keys['Menu_Select']: if self.lock_level == -1:############ MENU if self.menu_items[self.menu_pos[1]] == 'Save': self.map.__save__() elif self.menu_items[self.menu_pos[1]] == 'Save As': self.master(SaveAs(self)) elif self.menu_items[self.menu_pos[1]] == 'Save and Exit': self.map.__save__() self.close() return elif self.menu_items[self.menu_pos[1]] == 'Exit': self.close() return elif self.lock_level == 0:############ GRID self.lock_level += 1 elif self.lock_level == 1:############ TILE self.lock_level += 1 elif self.lock_level == 2:############ ITEM self.lock_level -= 2 if self.item_pos[1] == self.item_pos.max[1] - 1: self.master(NewItemFile(self.master, self)) else: self.map.spawn[self.posit[0]][self.posit[1]] = \ self.item_pos[1] + 1 else:################################### ERROR raise AttributeError('lock_level out of range') # Back Key Pressed: #################################################### elif event.keysym in util.config.keys['Menu_Back']: if self.lock_level == -1:############ MENU self.lock_level += 1 elif self.lock_level == 0:############ GRID self.lock_level -= 1 elif self.lock_level == 1:############ TILE self.lock_level -= 1 elif self.lock_level == 2:############ ITEM self.lock_level -= 2 else:################################### ERROR raise AttributeError('lock_level out of range') # Alternate Key Pressed: ############################################### elif event.keysym in util.config.keys['Menu_Alt']: if self.lock_level == -1:############ MENU pass elif self.lock_level == 0:############ GRID pass elif self.lock_level == 1:############ TILE self.map.spawn[self.posit[0]][self.posit[1]] = 0 elif self.lock_level == 2:############ ITEM item = self.map.items[self.item_pos[1]] image = util.load_image( util.local_path('source/Maps/%s/items/%s.gif' % (self.map.name, item.name))) edit_prompt = NewItemStats(self.master, image, self) edit_prompt.fields['Name'] = item.name if item.type == 'enemy': edit_prompt.enemy = True edit_prompt.fields['Health'] = item.health edit_prompt.fields['Attack'] = item.attack edit_prompt.fields['Speed'] = item.speed edit_prompt.fields['Range'] = item.range else: print edit_prompt.enemy edit_prompt.enemy = False print edit_prompt.enemy edit_prompt.fields['Count'] = item.count edit_prompt.draw() self.master(edit_prompt) else:################################### ERROR raise AttributeError('lock_level out of range') self.draw()
def test_util(): util.sprint("\n#!# LOCAL TESTS: util.py:") # Creating Testing Resources test = Tester() iList = [ 4, "hi", [1], (2, 3), False, list ] tList = [ type(i) for i in iList ] tFileName = util.local_path('temp_config') tFile = open(tFileName, 'w') tFile.write("# Graphics Options:\n Test Setting : 123\n Other:(12,foo)\n" + "#### Keybinds Options \n #### EOF") tFile.close() tConfig = util.Config(file=tFileName) tPos = util.LoopPos((5,10), (2, 3)) tGrid = util.Grid(5, 5, "Hello") tGrid[1][2] += "!" tBGrid = util.BitGrid() # Run Tests # Testing: type_check: for i in range(len(iList)): test.assertion("type_check test " + str(i), util.type_check(tList[i], iList[i]), "single item check: " + type(iList[i]).__name__) # type_check: Type List Tests for i in range(len(iList)): test.assertion("type_check list test " + str(i), util.type_check(tList, iList[i]), "Type-List input with: " + str(iList[i])) # Multi-Item Test test.assertion("type_check item list test", util.type_check( tList, iList[0], iList[1], iList[2], iList[3] ), "Type-List, Multi-Item Input.") # type_check: Fail Tests for i in range(len(tList)): test.assertion("type_check failure test " + str(i), not util.type_check(tList[:i] + tList[i+1:], iList[i]), "negative test for: " + type(iList[i]).__name__) for i in range(len(tList)): test.assertion("type_check multi-item failure test " + str(i), not util.type_check( tList[:i] + tList[i+1:], iList[0], iList[1], iList[2], iList[3], iList[4], iList[5] ), "negative test excluding: " + type(iList[i]).__name__) # type_check: Exception Test errorMsg = "type_check given int, where it needs type or list of types" test.error_assertion("type_check exception test", lambda: util.type_check(1, int), TypeError(errorMsg), "exception test") # Testing config file reader: test.assertion("Config file test 0", tConfig.settings['Test Setting'] == 123, "Integer setting failed to load" ) test.assertion("Config file test 1", type(tConfig.settings['Other']) is tuple, "Tuple type not discovered" ) test.assertion("Config file test 2", type(tConfig.settings['Other'][0]) is int, "Integer type not discovered" ) test.assertion("Config file test 3", type(tConfig.settings['Other'][1]) is str, "Str type not Discovered" ) # Testing LoopPos: test.assertion("LoopPos Starting Value Test", tPos[0] == 2 and tPos[1] == 3, "Starting values mismatched") tPos[0] += 11 tPos[1] -= 19 test.assertion("LoopPos Addition Test", tPos[0] == 3 and tPos[1] == 4, "Addition didn't loop correctly") # Testing Grid & BitGrid: test.assertion("Grid Default Test", tGrid[0][0] == "Hello", "Default was not loaded into grid") test.assertion("Grid Assignment Test", tGrid[1][2] == "Hello!", "Item did not assign to Grid") test.assertion("BitGrid Default Test", tBGrid[0][0] == [], "BitGrid Default was %s not 0" % (str(tBGrid[0][0]))) tAssignments = [ 'Right', 'Left', 'Down', 'Up'] for i, t in enumerate(tAssignments): tBGrid[0][0] = t test.assertion("BitGrid Directional Assignment Test: %s" % (t), t in tBGrid[0][0], "Directional Assignment Failed for %s" % (t)) tBGrid[0][0] = 1 << i test.assertion("BitGrid Numeric Assignment Test: %s" % (t), t in tBGrid[0][0], "Directional Assignment Failed for %s" % (t)) test.assertion("BitGrid Other Item Test %s" % (t), False not in [ o not in tBGrid[0][0] for o in tAssignments if not o == t], "Directional Assignment Failed for %s" % (t)) # Clean-up testing resources remove(util.local_path('temp_config')) # End Message util.sprint("Util testing Complete! Failed: [" + str(test.failed) + "/" + str(test.run) + "]") # Return testing object return test
def clean_map(dir_name): dir_path = util.local_path('source/Maps/' + dir_name) if path.exists(dir_path): rmtree(dir_path)
def test_engine(): import engineClass as e util.sprint("\n#!# LOCAL TESTS: engineClass.py:") # Creating Testing Resources up, down, left, right, select = [lambda: e.Event() for i in range(5)] test = Tester() up.keysym = 'Up' down.keysym = 'Down' left.keysym = 'Left' right.keysym = 'Right' select.keysym = 'Return' # Run a Simulation of the Editor try: util.sprint("Creating Editor Simulation") # Build and Handle Prompt 1 engine = e.Engine(e.ImgFileName, "Testing!") key = e.Event() util.sprint("Simulating Image location prompt") for char in util.local_path("rsc/basicMap.gif"): if char == '.': char = 'period' elif char == '\\': char = 'backslash' elif char == ':': char = 'colon' elif char == '/': char = 'slash' key.keysym = char engine.GUI.mode.__keypress__(key) engine.GUI.mode.__keypress__(select) except: util.sprint("Excepetion raised during prompt simulation 1") test.assertion("ImgFileName completion test", util.type_check(e.NewFileName, engine.GUI.mode), "Prompt failed to advance " + str(type(engine.GUI.mode))) # Handle Prompt 2 try: util.sprint("Simulating new file name prompt") for char in file_name: if char == '_': char = 'underscore' key.keysym = char engine.GUI.mode.__keypress__(key) engine.GUI.mode.__keypress__(select) except: util.sprint("Exception raised during prompt simulation 2") test.assertion("NewFileName completion test", util.type_check(e.TileDimension, engine.GUI.mode), "Prompt failed to advance") # Handle Prompt 3 try: util.sprint("Simulating tile dimension prompt") for char in "10,11": if char == ',': char = 'comma' key.keysym = char engine.GUI.mode.__keypress__(key) engine.GUI.mode.__keypress__(select) except: util.sprint("Exception raised during prompt simulation 3") test.assertion("TileDimension completion test", util.type_check(e.Editor, engine.GUI.mode), "Prompt failed to advance") # Handle Main Editor: try: # Placing a 5 in [9][8] and a 4 in [9][10] util.sprint("Simulating main Editor") engine.GUI.mode.__keypress__(up) engine.GUI.mode.__keypress__(left) engine.GUI.mode.__keypress__(select) # Select Bottom Right Tile engine.GUI.mode.__keypress__(down) engine.GUI.mode.__keypress__(right) key.keysym = 'BackSpace' engine.GUI.mode.__keypress__(key) engine.GUI.mode.__keypress__(up) engine.GUI.mode.__keypress__(up) engine.GUI.mode.__keypress__(select) # Select Tile 2 Up from BotRight engine.GUI.mode.__keypress__(down) engine.GUI.mode.__keypress__(select) engine.GUI.mode.__keypress__(select) # Create New Item except: util.sprint("Exception raised during prompt simulation 3") # Simulate NewItemFile Prompt try: util.sprint("\tSimulating NewItemFile Prompt") for char in util.local_path("rsc/add.gif"): if char == '.': char = 'period' elif char == '\\': char = 'backslash' elif char == ':': char = 'colon' elif char == '/': char = 'slash' key.keysym = char engine.GUI.mode.__keypress__(key) engine.GUI.mode.__keypress__(select) except: util.sprint("Exception Raised during NewItemFile simulation") # Simulate NewItemStats Prompt; then Save and Exit try: util.sprint("\tSimulating NewItemStats Prompt") engine.GUI.mode.__keypress__(down) engine.GUI.mode.__keypress__(select) # Select Name Field key.keysym = 'Z' engine.GUI.mode.__keypress__(key) key.keysym = 'e' engine.GUI.mode.__keypress__(key) key.keysym = 'd' engine.GUI.mode.__keypress__(key) engine.GUI.mode.__keypress__(select) # Progress to Health engine.GUI.mode.__keypress__(select) key.keysym = '1' engine.GUI.mode.__keypress__(key) key.keysym = '0' engine.GUI.mode.__keypress__(key) engine.GUI.mode.__keypress__(select) # Progess to Attack engine.GUI.mode.__keypress__(select) key.keysym = '2' engine.GUI.mode.__keypress__(key) engine.GUI.mode.__keypress__(select) # Progress to Speed engine.GUI.mode.__keypress__(select) key.keysym = '4' engine.GUI.mode.__keypress__(key) engine.GUI.mode.__keypress__(select) # Progress to Range engine.GUI.mode.__keypress__(select) key.keysym = '3' engine.GUI.mode.__keypress__(key) engine.GUI.mode.__keypress__(select) # Progress to Done engine.GUI.mode.__keypress__(select) util.sprint("\tSimulating Save&Exit") key.keysym = 'BackSpace' engine.GUI.mode.__keypress__(key) engine.GUI.mode.__keypress__(down) engine.GUI.mode.__keypress__(down) except: util.sprint("Exception raised during prompt simulation (item creation)") # Save and Exit needs to be outside of 'Try': engine.GUI.mode.__keypress__(select) try: test_file = open( temp_path + '/config' ) except: util.sprint("Exception raised while reading config file") contents = test_file.readlines() test.assertion("config contents test", int(contents[10].split(",")[9]) == 4 and int(contents[12].split(",")[9]) == 5 and int(contents[22].split(",")[9]) == 1 and "ENEMY: Zed" in contents[26] and "10" in contents[27] and "2" in contents[28] and "4" in contents[29] and "3" in contents[30], "bad config file contents") # Clean-up testing resources test_file.close() clean_map(file_name) # End Message util.sprint( "Engine testing Complete! Failed: [" + str(test.failed) + "/" + str(test.run) + "]" ) # Return testing object return test
#!/usr/bin/end python """ testClass.py * part of the IAI project. Performs testing on the IAI modules. * * * Last Edited: 02/02/16 """ # IMPORTS: import util from os import path, remove from shutil import rmtree from random import randint file_name = '__temp__' temp_path = util.local_path('source/Maps/' + file_name) #### CLASSES #### """ Tester: class used for testing a section of source code. * Runs assertions well tracking the tests run and failed. """ class Tester(): # Storage for the results: run = 0 failed = 0 failed_tests = [] """ assertion: an assertion test with accompanying (s)print statements """ def assertion(self, name, truth, message): # When testing is off this function becomes trivial if not util.config.mode['testing']: return