def enter(): hide_cursor() global background, cursor, x, y, isCollide, isBattle, rooms, font, start, play_turn, font_size_30 isCollide = False isBattle = False play_turn = battle_state.turn background = Background() cursor = Cursor() font = load_font('font\\gothic.ttf', 20) font_size_30 = load_font('font\\gothic.ttf', 30) cursor.x, cursor.y = x, y rooms = [Room() for i in range(7)] for i in range(0, 7): rooms[i].num = i rooms[i].x, rooms[i].y = room_location_table[i][ 0], room_location_table[i][1] if not start: create_room(1, 7) else: rooms = battle_state.rooms if rooms[i].boss: del rooms rooms = [Room() for i in range(7)] for i in range(0, 7): rooms[i].num = i rooms[i].x, rooms[i].y = room_location_table[i][ 0], room_location_table[i][1] create_room(1, 7)
class File(object): def __init__(self, path, base, index, size, fmap, piece_size, client): self._client = client self.path=path self.base=base self.index=index self.size=size self.piece_size=piece_size self.full_path= os.path.join(base,path) self.first_piece=fmap.piece self.offset=fmap.start self.last_piece=self.first_piece + max((size-1+fmap.start),0) // piece_size self.cursor = None def create_cursor(self, offset=None): self.cursor = Cursor(self) if offset: self.cursor.seek(offset) return self.cursor def map_piece(self, ofs): return self.first_piece+ (ofs+self.offset) // self.piece_size , (ofs+self.offset) % self.piece_size def update_piece(self, n, data): if self.cursor: self.cursor.update_piece(n,data) def __str__(self): return self.path
def select_all_rows(self, table): cursor = Cursor(table) leaf_node = Leaf_Node(table.get_page(cursor.page_num)) while cursor.end_of_table == False: leaf_node.get_row(cursor.cell_num).print() cursor.advance(leaf_node.num_cells)
def __refresh_new_target(self, resp): warning("Refresh Checking") Parser.get_next_target next_path = Parser.get_next_target(resp) self.__sid = Parser.get_sid(resp, self.__sid) if next_path: parse_res = urlparse(next_path) domain = parse_res.netloc query = parse_res.query if domain and self.__domain != domain: self.__domain = domain info(f"Find New Domain: {self.__domain}") Cursor.create_new_domain(self.__domain) return self.session.get(self.__main_url) if query: query = dict((item.split("=") for item in query.split("&"))) if "autim" in query: self.__autim = int(query["autim"]) info(f"autim: {self.__autim}") self.__make_links() next_url = urljoin(resp.url, next_path) warning(f"Refresh To: {next_url}") return self.__refresh_new_target(self.session.get(next_url)) return resp
def __login(self): try: """ ### 再次尝试 1.因为网络问题重试 ### 重新注册 2.因为账户被封重试 3.因为账户认证错误重试 """ warning(f"Login -> [{self.usr}:{self.pwd}]") self.__login_payload.update({ "password": self.pwd, "username": self.usr }) resp = self.__refresh_new_target( self.session.post( self.__login_url, data=self.__login_payload, verify=False, timeout=120, )) if self.usr in resp.text and "暗网欢迎您" in resp.text: success("Auth Success") self.types = Parser.get_current_type(resp) # assert self.types != {} else: error(f"Auth Faild: {self.__clean_log(resp)}") self.__save_error("__login.html", resp) if "已被封禁" in resp.text: Cursor.ban_user(self.usr) self.__reg() raise ValueError except KeyboardInterrupt: exit()
class Document: """Represents document""" def __init__(self): """Initializes variables""" self.characters = [] self.cursor = Cursor(self) self.filename = '' def insert(self, character): """Insert character on cursor's position (limitations described in document_test.py)""" if not hasattr(character, 'character'): character = Character(character) self.characters.insert(self.cursor.position, character) self.cursor.forward() def delete(self): """Delete character on cursor's position (limitations described in document_test.py)""" del self.characters[self.cursor.position] def save(self): """Save file but we should input filename in __init__()""" f = open(self.filename, 'w') f.write(''.join(self.characters)) f.close() @property def string(self): "Returns string of characters" return ''.join((str(c) for c in self.characters))
def process(self): # load data data = self.load() # index to elastic search print "\nStart processing" cursor = Cursor(self.es, self.data_from) cursor_num = cursor.get_new_cursor() for each_data in data: key_string = '' for each_key_string in key_value: key_string += each_data[each_key_string] hashkey = mmh3.hash(key_string) print "parsing id: ", hashkey # try to read record try: res = self.es.get( index="deltadb", doc_type="data", id=hashkey) if res["found"]: node = self.update_node(res["_source"], each_data, cursor_num) else: node = self.create_node(each_data, cursor_num) except: node = self.create_node(each_data, cursor_num) # insert back to es try: res = self.es.index(index="deltadb", doc_type="data", id=hashkey, body=node) except: continue print "\nProcess finish."
class File(object): def __init__(self, path, base, index, size, fmap, piece_size, client): self._client = client self.path = path self.base = base self.index = index self.size = size self.piece_size = piece_size self.full_path = os.path.join(base, path) self.first_piece = fmap.piece self.offset = fmap.start self.last_piece = self.first_piece + max( (size - 1 + fmap.start), 0) // piece_size self.cursor = None def create_cursor(self, offset=None): self.cursor = Cursor(self) if offset: self.cursor.seek(offset) return self.cursor def map_piece(self, ofs): return self.first_piece + (ofs + self.offset) // self.piece_size, ( ofs + self.offset) % self.piece_size def update_piece(self, n, data): if self.cursor: self.cursor.update_piece(n, data) def __str__(self): return self.path
def register(self): try: warning("register confirm") resp = self.refresh_new_target( self.session.get( self.register_url, headers={ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3", "Content-Type": "application/x-www-form-urlencoded", "Referer": self.register_url, }, ) ) token, creation_time = Parser.get_token_and_creation_time(resp) warning("start register") resp = self.session.post( self.register_url, data={ "agreed": "===好的,我已明白,请跳转到下一页继续注册====", "autim": self.autim, "change_lang": "", "creation_time": creation_time, "form_token": token, }, headers=self.make_reg_headers(resp), ) token, creation_time = Parser.get_token_and_creation_time(resp) confirm_code, confirm_id = Parser.get_captcha(self.get_pic, resp) self.create_random_author() data = { "username": self.usr, "new_password": self.pwd, "password_confirm": self.pwd, "email": "*****@*****.**", "lang": "zh_cmn_hans", "tz_date": "UTC+08:00 - Antarctica/Casey - " + moment.now().format("YYYY-MM-DD HH:mm"), "tz": "Asia/Hong_Kong", "agreed": "true", "change_lang": "0", "confirm_code": confirm_code, "confirm_id": [confirm_id, confirm_id], "creation_time": creation_time, "form_token": token, "submit": " 用户名与密码已填好, 点此提交 ", "autim": self.autim, } resp = self.session.post( self.register_url, data=data, headers=self.make_reg_headers(resp) ) assert "感谢注册" in resp.text success("register success") Cursor.create_new_user({"user": self.usr, "pwd": self.pwd}) except KeyboardInterrupt: exit() except AssertionError as e: error("register failed") error(self.clean_log(resp)) raise e
def __init__(self): """ inits a new instance of Document class with attributes characters, cursor and filename """ self.characters = [] self.cursor = Cursor(self) self.filename = ''
def __init__(self): self.__message_queue = [] self.__cur_stat_surf = None self.__actors = [] self.__items = [] self.__gfx = None self.__quit_loop = False self.__last_id = 0 self.__id_gen = self.__gen_id() self.__actors_on_screen = [] self.__timer = 0 self.__world_time = 0 self.__load_fonts() self.__build_surf_cache() self.__set_game_instance() self.__player_actions = PlayerActions(self) self.__state_worker = StateWorker(self) self.__actor_grid = [] self.__item_grid = [] for y in xrange(200): aline = [] iline = [] for x in xrange(200): aline.append([]) iline.append([]) self.__actor_grid.append(aline) self.__item_grid.append(iline) self.map = None self.dungeon = dungeon.DungeonsOfGogadan() self.quit_mes = QUIT self.stats = [ att.Att('Strength', 'Important for Melee-Fighter', 20), att.Att('Endurance', 'Important for Melee-Fighter'), att.Att('Mind', 'Important for Spellcaster'), att.Att('Health', 'How much can you take?', 45) ] self.camera = Camera(20, 26) self.state = S_RUN self.__await_target = None Debug.init_debug(self) Debug.debug('init pygame') pygame.init() self.screen = pygame.display.set_mode((1024, 768)) self.__clock = pygame.time.Clock() self.item_to_throw = None self.cursor = Cursor(self) self._items_to_choose = {} self._symbols = [] c = 'abcdefghijklmonpqrstuvwxyz' for s in c: self._symbols.append(s)
def __init__(self): self._window = sf.RenderWindow( sf.VideoMode(settings.windowWidth, settings.windowHeight), "BaconBulb") self._window.vertical_synchronization = True self._window.framerate_limit = 60 self._window.mouse_cursor_visible = False self._cursor = Cursor(self._window) self._game_menu = GameMenu(self._window)
def build_until_square_satisfies_criteria(end, check, calculate): squares = SquareMap() cursor = Cursor(mode=Mode.build_x, x=0, y=0, max_degree=0) square: Square while cursor.id == 1 or not check(square, end): square = Square(id=cursor.id, x=cursor.x, y=cursor.y, data=calculate(squares, cursor.x, cursor.y)) squares.add(square) cursor.move_cursor() return squares
def parse_non_empty(self, start, level): grammars = Cursor(self.grammars) result = False end = start while grammars.not_empty() and not result: (result, end) = grammars.head().parse(start, level + 1) if not result: grammars = grammars.tail() return (result, end)
def login(self): try: """ ### 再次尝试 1.因为网络问题重试 ### 重新注册 2.因为账户被封重试 3.因为账户认证错误重试 """ warning(f"login -> [{self.usr}:{self.pwd}]") self.login_payload.update({ "password": self.pwd, "username": self.usr }) resp = self.session.post( self.login_url, data=self.login_payload, headers={ "Content-Type": "application/x-www-form-urlencoded", "Referer": f"http://{self.domain}/ucp.php?mode=login", }, allow_redirects=False, ) debug(f"login[1] requests header: {resp.request.headers}") debug(f"login[1] response header: {resp.headers}") if resp.status_code == 302 and "Location" in resp.headers: resp = self.refresh_new_target( self.session.get( resp.headers.get("Location"), headers={ "Referer": f"http://{self.domain}/ucp.php?mode=login&sid={self.sid}", "Cookie": self.get_cookie_string(), }, )) else: Cursor.ban_user(self.usr) self.update_random_user() return debug(f"login[2] requests header: {resp.request.headers}") debug(f"login[2] response header: {resp.headers}") if self.usr in resp.text and "暗网欢迎您" in resp.text: success("Auth Success") self.types = Parser.get_current_type(resp) else: error(f"Auth Faild: {self.clean_log(resp)}") if re.findall("已被封禁|无效的|违规被处理", resp.text): Cursor.ban_user(self.usr) self.update_random_user() # if not self.register(): # return # else: # raise ValueError except KeyboardInterrupt: exit()
class Document: def __init__(self): """ inits a new instance of Document class with attributes characters, cursor and filename """ self.characters = [] self.cursor = Cursor(self) self.filename = '' @property def string(self): """ returns a string of styled chars """ return "".join((str(c) for c in self.characters)) """ c. збереження файлу без імені d. введення декількох символів """ def insert(self, character): """ insters the character to the position, where the cursor is located now """ if not hasattr(character, 'character'): character = Character(character) if len(character.character) > 1: raise NotChar self.characters.insert(self.cursor.position, character) self.cursor.forward() def delete(self): """ deletes the character from the position, where the cursor is located now """ try: del self.characters[self.cursor.position] except: raise CharacterDontExist def save(self): """ saves the document to the file with its filename """ if not self.filename: raise NoFilename f = open(self.filename, 'w') f.write(''.join(self.characters)) f.close()
def __init__(self, opciones): self.fondo = pygame.image.load("imagen/fondo-menu.jpg").convert() self.fuente = pygame.font.Font('fuentes/ninja-turtles-regular.otf', 80) self.texto = self.fuente.render('TURTLE NINJA ', True, Color.VERDE) self.opciones = list() self.cursor = Cursor() self.seleccionado = 0 self.total = len(opciones) self.mantiene_pulsado = False self.sonido_menu = pygame.mixer.Sound('audio/an_8_bit_story.ogg') self.sonido_menu.play(loops=-1) self.construir_opciones(opciones)
def __init__(self, stdscr): # Set member values self.screen = stdscr self.height, self.width = self.screen.getmaxyx() self.file = text.TextFile("cursor.py") self.quit = False self.cursor = Cursor(self.file) self.status = "" # Set curses to non-blocking input self.screen.nodelay(True) self.screen.timeout(0)
def __init__(self, _engine): super(Scene, self).__init__() self._ais = [] self._engine = _engine self._resx, self._resy = _engine.getResolution() self.surface = pygame.Surface((self._resx, self._resy)) drawText(self.surface, "Wczytywanie mapy...", 48, (255, 255, 255), (self._resx / 2, self._resy / 2)) self._map = Map(_engine) self._hub = Hub(_engine, self._map) self._cursor = Cursor(_engine, self._map) self._ais.append(AI(_engine, self._map, _engine.players[0], 0)) self._ais.append(AI(_engine, self._map, _engine.players[1], 1))
def __init__(self, size=9): self.players = [Player('B', 300), Player('W', 300)] self.currentPlayer = 0 self.board = Board(size) self.territories = Board(size) self.previousBoard = self.board.getMatrix() self.currentBoard = self.board.getMatrix() self.cursor = Cursor(self.board) self.attemptedPlace = False self.handler = EventHandler() self.UI = UIMatch(size, self.handler) self.newGame = False self.exit = False
def main(stdscr): cursor = Cursor(stdscr) url = utils.ip + "token/get" token = utils.request(url)['token'] grid = Grid(stdscr, x_limit, y_limit, cursor) sel_bool = False sel_soldiers = [] while True: key = stdscr.getch() # quit game if key == ord('q'): exit(stdscr) # create soldier elif key == ord('c'): create_soldier(token) # move cursor elif key in directions: cursor.move_cursor(key) # select tiles elif key == ord('s') and not sel_bool: cursor.select() key = 0 sel_bool = True sel_soldiers = [] # finish selecting elif key is ord('s') and sel_bool: cursor.deselect() x_r = sorted((cursor.select_coords[0], cursor.x)) y_r = sorted((cursor.select_coords[1], cursor.y)) debug_file.write(str(x_r) + "\n" + str(y_r) + "\n") for x in range(x_r[0], x_r[1]+1): for y in range(y_r[0], y_r[1]+1): if (x,y) in grid.grid: debug_file.write("inserting") sel_soldiers.append(grid.grid[(x,y)]) sel_bool = False if key is ord('q'): exit(stdscr) # move soldiers (soldiers must be selected first) elif key == ord('m'): key = 69 debug_file.write(str(sel_soldiers)) if sel_soldiers: debug_file.write("moving soldiers\n") move_soldiers(cursor.position(), sel_soldiers) sel_bool = False elif key == ord('d'): raise Exception(grid.request()) grid.debug(str(key)) grid.update(key, sel_bool) grid.display()
def __init__(self, cancion=None): """ Pre: Recibe una cancion (ubicacion de un archivo.plp). Post: incia un reproductor con la cancion recibida cargada. Si no se recibe cancion, el reproductor inicia con una cancion vacia. """ self.canales = 0 self.tracks = [] self.info_tracks = [] self.cancion = ListaEnlazada() self.cursor = Cursor(self.cancion) if cancion: self.cargar(cancion)
class TestCursorMovement(unittest.TestCase): @vals([Cursor.MoveLeft, Cursor.MoveRight, Cursor.MoveUp, Cursor.MoveDown]) def test_MovementEmptyContent(self, cursorFunc): contents = [[]] expectedCursor = Cursor(0, 0) cursor = Cursor(0, 0) cursorFunc(cursor, contents) self.assertEqual(cursor, expectedCursor) def name_test(original_name, cursorFunc, expectedCursor): return '{0}_Cursor_{1}_{2}_{3}'.format(original_name, cursorFunc.__name__, str(expectedCursor.x), str(expectedCursor.y)) @vals([(Cursor.MoveLeft, Cursor(0, 0)), (Cursor.MoveRight, Cursor(1, 0)), (Cursor.MoveUp, Cursor(0, 0)), (Cursor.MoveDown, Cursor(0, 0))], name=name_test) def test_MovementOneChar_StartLeft(self, cursorFunc, expectedCursor): contents = [['a']] cursor = Cursor(0, 0) cursorFunc(cursor, contents) self.assertEqual(cursor, expectedCursor) @vals([(Cursor.MoveLeft, Cursor(0, 0)), (Cursor.MoveRight, Cursor(1, 0)), (Cursor.MoveUp, Cursor(0, 0)), (Cursor.MoveDown, Cursor(0, 0))], name=name_test) def test_MovementOneChar_StartRight(self, cursorFunc, expectedCursor): contents = [['a']] cursor = Cursor(1, 0) cursorFunc(cursor, contents) self.assertEqual(cursor, expectedCursor)
def __init__(self, name): super(Game, self).__init__() self.name = name self.keys_pressed = set() self.projectiles = list() self.background = Sprite( image=get_background_path() ) # à cacher global BACKGROUND_RECT BACKGROUND_RECT = self.background.get_rect() offset = BACKGROUND_RECT.width/2, BACKGROUND_RECT.height/2 load_wall_array() global SPAWN self.cursor = Cursor(SPAWN) ## self.background.position = offset spawn_delayed([self], [self.cursor]) self.add(self.background) self.adstop = AdStop(self.cursor) self.add(self.adstop) self.bullettime = BulletTime(self.cursor) self.add(self.bullettime) self.add(self.cursor) # adding stuff to the collision world global COL_MGR COL_MGR = cocos.collision_model.CollisionManagerGrid( BACKGROUND_RECT.x + BACKGROUND_RECT.width/2, BACKGROUND_RECT.x + 3*BACKGROUND_RECT.width/2, BACKGROUND_RECT.y + BACKGROUND_RECT.height/2, BACKGROUND_RECT.y + 3*BACKGROUND_RECT.height / 2, 16, 16 ) # self.debug() self.schedule(self.update)
def __login(self): try: """ ### 再次尝试 1.因为网络问题重试 ### 重新注册 2.因为账户被封重试 3.因为账户认证错误重试 """ warning(f"Login -> [{self.usr}:{self.pwd}]") self.__login_payload.update({"password": self.pwd, "username": self.usr}) resp = self.__refresh_new_target( self.session.post( self.__login_url, data=self.__login_payload, verify=False, timeout=120, # headers={ # "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3", # "Accept-Encoding": "gzip, deflate", # "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", # "Cache-Control": "no-cache", # "DNT": "1", # "Host": self.__domain, # "Pragma": "no-cache", # "Origin":self.__main_url, # "Referer": f"{self.__main_url}/ucp.php?mode=login&autim={self.__login_payload['autim']}", # "Upgrade-Insecure-Requests": "1", # "User-Agent": "Mozilla/5.0 (Windows NT 6.1; rv:60.0) Gecko/20100101 Firefox/60.0" # } ) ) debug(resp.history) debug(resp.request.headers) if self.usr in resp.text and "暗网欢迎您" in resp.text: success("Auth Success") self.types = Parser.get_current_type(resp) # assert self.types != {} else: error(f"Auth Faild: {self.__clean_log(resp)}") self.__save_error("__login.html", resp) if "已被封禁" in resp.text: Cursor.ban_user(self.usr) self.__reg() raise ValueError except KeyboardInterrupt: exit()
def __init__(self): self._window = sf.RenderWindow(sf.VideoMode(settings.windowWidth, settings.windowHeight), "BaconBulb") self._window.vertical_synchronization = True self._window.framerate_limit = 60 self._window.mouse_cursor_visible = False self._cursor = Cursor(self._window) self._game_menu = GameMenu(self._window)
def draw_troparion(self, neumes_list: List[Neume], lyrics_list: List[Lyric], dropcap: Dropcap): """Draws a troparion with the passed text attributes. :param neumes_list: A list of neumes. :param lyrics_list: A list of Lyrics. :param dropcap: A dropcap object. """ dropcap_offset = 0 # Pop off first letter of lyrics, since it will be drawn as a dropcap if dropcap and len(lyrics_list) > 0: lyrics_list[0].text = lyrics_list[0].text[1:] lyrics_list[0].recalc_width() dropcap_offset = dropcap.width + dropcap.x_padding if neumes_list: neume_chunks = self.make_neume_chunks(neumes_list) glyph_line: List[Glyph] = self.make_glyph_list( neume_chunks, lyrics_list) lines_list: List[GlyphLine] = self.line_break( glyph_line, Cursor(dropcap_offset, 0), self.doc.width, self.styleSheet['Neumes'].leading, self.styleSheet['Neumes'].wordSpace) if len(lines_list ) > 1 or self.styleSheet['Neumes'].alignment is TA_JUSTIFY: lines_list: List[GlyphLine] = self.line_justify( lines_list, self.doc.width, dropcap_offset) tropar = Troparion(lines_list, dropcap, self.doc.width) self.story.append(tropar)
def __init__(self, screen, camera, organizer, controllernr, lastState): self.camera = camera self.screen = screen self.lastState = lastState self.backToLastState = False self.backToCalibration = False self.organizer = organizer self.firstCheck = False self.cursor = Cursor(0, 0, 20, self.organizer) self.upperLeftButton = CursorRecognition("1", 20, [50, 50, 200, 200], self.organizer) self.upperRightButton = CursorRecognition("2", 20, [1850 - 250, 50, 200, 200], self.organizer) self.lowerRightButton = CursorRecognition( "3", 20, [1850 - 250, 1080 - 250, 200, 200], self.organizer) self.lowerLeftButton = CursorRecognition( "4", 20, [50, 1080 - 250, 200, 200], self.organizer) # I hate hardcoding, resolution is 1850,1080 self.controllernr = controllernr self.objectCoordinates, self.cameraImage = OR.getCoords( self.camera, 0) # Get the coordinates for controller '0' self.allowedTime = 15 # Time to complete the calibration self.startTime = time.time( ) # Starttime when the program gets initialized self.elapsedTime = time.time() # gets updated every loop self.timer = self.elapsedTime - self.startTime # Time left
def cursor(self, query=None, order_by=None, reply=None, page_size=18, **filters): """Query resource objects. :param query: full text search query string in Xapian format :param order_by: name of property to sort by; might be prefixed by either `+` or `-` to change order's direction :param reply: list of property names to return for found objects; by default, only GUIDs will be returned; for missed properties, will be sent additional requests to a server on getting access to particular object. :param page_size: number of items in one cached page, there are might be several (at least two) pages :param filters: a dictionary of properties to filter resulting list """ from cursor import Cursor return Cursor(self.mountpoint, self.document, query, order_by, reply, page_size, **filters)
def test_traversal(self): items = [] cursor = Cursor([1, 2, 3]) items.append(cursor.head()) tail1 = cursor.tail() items.append(tail1.head()) tail2 = tail1.tail() items.append(tail2.head()) tail3 = tail2.tail() self.assertEqual(items, [1, 2, 3]) self.assertTrue(tail3.empty())
def main(): file = sys.argv[1] contents = [[y for y in x] for x in open(file).read().split('\n')] cursor = Cursor() done = False draw(contents, cursor) while not done: if msvcrt.kbhit(): a = msvcrt.getch() b = b'\x00' if a == b'\x00' or a == b'\xe0': b = msvcrt.getch() if a == b'\x11': done = True if a == b'\xe0': { Keys.LeftArrow: cursor.MoveLeft, Keys.RightArrow: cursor.MoveRight, Keys.UpArrow: cursor.MoveUp, Keys.DownArrow: cursor.MoveDown }[b](contents) print("Last Key: {},{}".format(a, b)) print("Cursor: {}".format(cursor)) print('_________________________') draw(contents, cursor) time.sleep(0.01)
def __init__(self, organizer, screenSize, camera, clock, fps): self.organizer = organizer self.screenSize = screenSize self.width = screenSize[0] self.height = screenSize[1] self.closePlatform = False #The main while loop looks if this is true or false to break out of the while loop self.clock = clock self.fps = fps self.cursor = Cursor( 0, 0, 20, self.organizer ) # Initialize a cursor in coord (0,0) with radius 20 self.pongButton = CursorRecognition( "Pong", 30, [100, 200, 200, 200], self.organizer ) # Make a button for the areaSurveillance with left corner coords (100,200) & length/width = 200 self.spaceInvadersButton = CursorRecognition("Space Invaders", 30, [500, 200, 400, 200], self.organizer) self.calibrationButton = CursorRecognition(" Calibrate", 30, [1000, 200, 300, 200], self.organizer) self.closeButton = CursorRecognition("CLOSE", 30, [1500, 50, 200, 150], self.organizer) self.camera = camera OR.calibrate(self.screenSize, self.camera, 0) # Initialize the color for controller '0' organizer.state = "calibrationTest" self.objectCoordinates, self.cameraImage = OR.getCoords( self.camera, 0) # Get the coordinates for controller '0' self.controllernr = 0
def __init__(self): self.tablero = Tablero(80, 80) self.screen = pygame.display.set_mode((len(self.tablero.matrix[0]) * 10, len(self.tablero.matrix) * 10 + 32), pygame.DOUBLEBUF) pygame.display.set_caption("Pathfinder") self.clock = pygame.time.Clock() self.pausa = True self.velocidad = 100 self.velocidad_algoritmo = 8 # a star self.pathfinder = PathFinder(self.tablero) # cursor self.cursor = Cursor(self.tablero, self.pathfinder) #fuente pygame.font.init() self.fuente = pygame.font.SysFont("default", 24) self.texto = self.fuente.render("Pausado", True, (255, 0, 255)) self.texto_algo = self.fuente.render("Velocidad: " + str(self.velocidad_algoritmo), True, (255, 0, 255))
def enter(): global boss_exist, middle_boss_exist boss_exist = 0 middle_boss_exist = 0 global boss_gauge boss_gauge = 0 global hero global cursor global boss global boss_right_arm global boss_left_arm global enemy_genarate global middle_boss map = Map() cursor = Cursor() boss = Boss() boss_right_arm = Boss_right_arm() boss_left_arm = Boss_left_arm() middle_boss = Middle_boss() hero = Hero() hide_cursor() game_world.add_object(map, 0) enemy_genarate = Enemy_genarate() game_world.add_object(hero, 1) game_world.add_object(cursor, 4) game_world.add_object(enemy_genarate, 0)
class OverworldUI(ui.TacticsUI): def __init__(self, *args, **kwargs): super(OverworldUI, self).__init__(*args, **kwargs) self.size = SCREEN_SIZE self.board = Board((20, 20, 30), (40, 20, 10), self.size) player = Unit("trainee") self.cursor = Cursor(player) self.board.set_unit(0, 0, player) self.board.redraw() self.board.set_display_position(*self.cursor.board_pos) self.keys = set() def redraw(self): pass def reblit(self, screen): self.board.reblit(screen) def keydown(self, event): if self.cursor.handle_key(event.key, self.board): self.board.set_display_position(*self.cursor.board_pos) self.board.redraw() self.keys.add(event.key) def keyup(self, event): self.keys.discard(event.key) def keep_moving(self): if self.cursor.keep_moving(): self.board.set_display_position(*self.cursor.board_pos) elif self.cursor.unit.tile is None: self.board.set_unit(*self.cursor.set_unit_here()) self.board.redraw() try: e = self.keys.pop() self.keys.add(e) x = Stupid() x.key = e self.keydown(x) except KeyError: print "no key" @staticmethod def name(): return "overworld"
def __init__(self, screen): self.clock = pygame.time.Clock() self.screen = screen self.buffer = pygame.Surface(self.screen.get_size()) self.font = pygame.font.Font(FONT, FONT_SIZE) self.menu_items = ['Items','Equip','Magic','Status','Save','Close','Quit'] self.menu_image = pygame.image.load(IMAGES_DIR+'menu.png').convert_alpha() self.cursor = Cursor(ypos=[5,30,55,80,105,130,155])
def open_status(self): menu = True statuscursor = Cursor(ypos=[25, 85, 145, 205], xpos=[0]) while menu: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: menu = False if event.key == K_DOWN: statuscursor.move_down() if event.key == K_UP: statuscursor.move_up() if event.key == K_RETURN: if statuscursor.position.y == 25: self.status(self.team[0]) if statuscursor.position.y == 85: self.status(self.team[1]) if statuscursor.position.y == 145: self.status(self.team[2]) if statuscursor.position.y == 205: self.status(self.team[3]) self.buffer.blit(self.menu_image, (0,0)) self.render_menu() statuscursor.update() self.buffer.blit(statuscursor.image, statuscursor.position) pygame.transform.scale(self.buffer, self.screen.get_size(), self.screen) pygame.display.flip() self.clock.tick(60)
def __init__(self, *args, **kwargs): super(BattleUI, self).__init__(*args, **kwargs) self.size = SCREEN_SIZE self.cursor = Cursor() self.board = Board((20, 20, 30), (40, 20, 10), self.size) # TODO: not a fan of the magic numbers self.board.set_display_position(*self.cursor.board_pos)
class BattleUI(ui.TacticsUI): def __init__(self, *args, **kwargs): super(BattleUI, self).__init__(*args, **kwargs) self.size = SCREEN_SIZE self.cursor = Cursor() self.board = Board((20, 20, 30), (40, 20, 10), self.size) # TODO: not a fan of the magic numbers self.board.set_display_position(*self.cursor.board_pos) def redraw(self): pass def reblit(self, screen): self.board.reblit(screen) self.cursor.reblit(screen) def keydown(self, event): if self.cursor.handle_key(event.key, self.board): self.board.set_display_position(*self.cursor.board_pos) def k_UP(self): if self.cursor.k_UP(self.board): self.board.set_display_position(*self.cursor.board_pos) def k_DOWN(self): if self.cursor.k_DOWN(self.board): self.board.set_display_position(*self.cursor.board_pos) def k_LEFT(self): if self.cursor.k_LEFT(self.board): self.board.set_display_position(*self.cursor.board_pos) def k_RIGHT(self): if self.cursor.k_RIGHT(self.board): self.board.set_display_position(*self.cursor.board_pos) def k_CANCEL(self): pass def k_OK(self): pass def k_PAUSE(self): self.main.push_ui("team") def keep_moving(self): if self.cursor.keep_moving(): self.board.set_display_position(*self.cursor.board_pos) @staticmethod def name(): return "battle"
def __init__(self): self.__message_queue = [] self.__cur_stat_surf = None self.__actors = [] self.__items = [] self.__gfx = None self.__quit_loop = False self.__last_id = 0 self.__id_gen = self.__gen_id() self.__actors_on_screen = [] self.__timer = 0 self.__world_time = 0 self.__load_fonts() self.__build_surf_cache() self.__set_game_instance() self.__player_actions = PlayerActions(self) self.__state_worker = StateWorker(self) self.__actor_grid = [] self.__item_grid = [] for y in xrange(200): aline = [] iline = [] for x in xrange(200): aline.append([]) iline.append([]) self.__actor_grid.append(aline) self.__item_grid.append(iline) self.map = None self.dungeon = dungeon.DungeonsOfGogadan() self.quit_mes = QUIT self.stats = [att.Att('Strength', 'Important for Melee-Fighter', 20), att.Att('Endurance', 'Important for Melee-Fighter'), att.Att('Mind', 'Important for Spellcaster'), att.Att('Health', 'How much can you take?', 45)] self.camera = Camera(20, 26) self.state = S_RUN self.__await_target = None Debug.init_debug(self) Debug.debug('init pygame') pygame.init() self.screen = pygame.display.set_mode((1024, 768)) self.__clock = pygame.time.Clock() self.item_to_throw = None self.cursor = Cursor(self) self._items_to_choose = {} self._symbols = [] c = 'abcdefghijklmonpqrstuvwxyz' for s in c: self._symbols.append(s)
def __init__(self, *args, **kwargs): super(OverworldUI, self).__init__(*args, **kwargs) self.size = SCREEN_SIZE self.board = Board((20, 20, 30), (40, 20, 10), self.size) player = Unit("trainee") self.cursor = Cursor(player) self.board.set_unit(0, 0, player) self.board.redraw() self.board.set_display_position(*self.cursor.board_pos) self.keys = set()
class Startup(): def __init__(self): self._window = sf.RenderWindow(sf.VideoMode(settings.windowWidth, settings.windowHeight), "BaconBulb") self._window.vertical_synchronization = True self._window.framerate_limit = 60 self._window.mouse_cursor_visible = False self._cursor = Cursor(self._window) self._game_menu = GameMenu(self._window) def run(self): settings.music.play() while self._window.is_open: self.loop() def loop(self): self._window.clear(sf.Color(50, 50, 50)) self._cursor.setPosition(sf.Mouse.get_position(self._window)) self._cursor.rotate(2) self._game_menu.dispatch() self._window.draw(self._cursor) self._window.display()
def __init__(self, debuggable=False, interval=0.1, unit="s"): self.debuggable = debuggable self.interval = interval self.unit = unit if not is_windows_system(): from cursor import Cursor from terminal import Terminal self.cursor = Cursor(Terminal()) self.sorted_tasks = [] self.tpl_running_task = '[+][{}] {} in {}{}\n' self.tpl_waiting_task = '[+][{}] {}\n' self.tpl_finished_task = '[-][{}] {} in {}{}\n' # self.tpl_faied_task = '[-]{}:{} in {}{}\n' logging.basicConfig(level=logging.DEBUG)
def __init__(self,*args): super(ViewingWindow,self).__init__(*args) self.graph = BridgeConceptGraph() self.nodeSelected = SignalSlotObject() self.nodeUnselected = SignalSlotObject() self.cursor = Cursor() self.cursor.leftClick.connect(self.onLeftClick) self.cursor.leftHover.connect(self.onHover) self.cursor.leftDrag.connect(self.onLeftDrag) self.cursor.leftPress.connect(self.onLeftPress) self.cursor.leftRelease.connect(self.onLeftRelease) self.cursor.rightClick.connect(self.onRightClick) self.cursor.rightDrag.connect(self.onRightDrag) self.cursor.rightPress.connect(self.onRightPress) self.cursor.rightRelease.connect(self.onRightRelease) self.cursor.rightPull.connect(self.onRightPull) self.cursor.rightHover.connect(self.onHover) self.worldCursor = QPointF(0,0) self.leftClickB = False self.leftDragB = False self.HoverB = False self.leftPressB = False self.leftReleaseB = False self.rightClickB = False self.rightDragB = False self.rightPressB = False self.rightReleaseB = False self.rightPullB = False self.selectedNode = None self.heldNode = None self.hoverNode = None self.edgeDragNode = None self.fps = 30 self.translation = QPointF(0.0,0.0) self.scale = 1.0 self.minScale = 0.1 self.maxScale = 10.0 self.initUI()
def create_cursor(self, offset=None): self.cursor = Cursor(self) if offset: self.cursor.seek(offset) return self.cursor
def __init__(self, graph=None, camera=None, orthocamera=None, netcli=False): print "Calling graph context init" # # Cacheable: Keep track of observers # self.__dict__['observers'] = [] if not config.current['global:highlight']: self.highLight = False else: self.highLight = True self.highLightNow = True self.ready = False if not graph: print "Making a graph object" self.graph = Graph(parent=self) else: self.graph = graph if netcli: self.UndoStack = undo.DummyStack(self) self.RedoStack = undo.DummyStack(self) else: self.UndoStack = undo.UndoStack(self) self.RedoStack = undo.RedoStack(self) self.graphgl = graphgl.GraphGL(self.graph) self.decor = interfacegl.InterfaceGL() if not camera: self.camera = Camera() self.camera.lookAt = (0.0, 0.0, 0.0) else: self.camera = camera if not orthocamera: self.orthocamera = OrthoCamera() else: self.orthocamera = orthocamera self.cursor = Cursor() self.path = None # This should default to False and turn on automatically # when you have a 3D input device. # XXX# self.showCursor = False # The drawList should be a dictionary of Drawables, # used by the InputManager to enable transient objects, # menus, etc to be drawn. self.drawList = {} self.orthoMode = None self.showAxes = config.current['default:show-axes'] self.showLocalAxes = config.current['default:show-local-axes'] self.showHUD = config.current['default:show-hud'] self.showGrid = config.current['default:show-grid'] self.showGridLines = config.current['default:show-grid-lines'] self.showPlane = config.current['default:show-plane'] self.planeColor = config.current['default:plane-color'] self.bgColor = config.current['default:background-color'] self.showVertexLabels = config.current['default:show-vertex-labels'] self.showDummyLabels = config.current['default:show-dummy-labels'] self.vertexLabelName = config.current['default:vertex-label-name'] self.vertexLabelColor = config.current['default:vertex-label-color'] self.vertexShadowColor = config.current['default:vertex-shadow-color'] self.vertexLabelStroke = config.current['default:vertex-label-stroke'] self.showGridPlane = "XZ" self.pos = (0.0, 0.0, 0.0) self.sizeX = 5 self.sizeY = 5 self.sizeZ = 5 self.spacing = 2.0 # The HUD status text line. self.HUDstatus = '' #If no highlight object exists, create one. if self.highLight: print "Creating highlight for active context" self.highLight = True from interfacegl import DrawObjectHighLight self.setDraw('wandaHighLight', DrawObjectHighLight( ctx=self, tolerance=5.0, restrict=None, ) )
class ViewingWindow(QWidget): def __init__(self,*args): super(ViewingWindow,self).__init__(*args) self.graph = BridgeConceptGraph() self.nodeSelected = SignalSlotObject() self.nodeUnselected = SignalSlotObject() self.cursor = Cursor() self.cursor.leftClick.connect(self.onLeftClick) self.cursor.leftHover.connect(self.onHover) self.cursor.leftDrag.connect(self.onLeftDrag) self.cursor.leftPress.connect(self.onLeftPress) self.cursor.leftRelease.connect(self.onLeftRelease) self.cursor.rightClick.connect(self.onRightClick) self.cursor.rightDrag.connect(self.onRightDrag) self.cursor.rightPress.connect(self.onRightPress) self.cursor.rightRelease.connect(self.onRightRelease) self.cursor.rightPull.connect(self.onRightPull) self.cursor.rightHover.connect(self.onHover) self.worldCursor = QPointF(0,0) self.leftClickB = False self.leftDragB = False self.HoverB = False self.leftPressB = False self.leftReleaseB = False self.rightClickB = False self.rightDragB = False self.rightPressB = False self.rightReleaseB = False self.rightPullB = False self.selectedNode = None self.heldNode = None self.hoverNode = None self.edgeDragNode = None self.fps = 30 self.translation = QPointF(0.0,0.0) self.scale = 1.0 self.minScale = 0.1 self.maxScale = 10.0 self.initUI() def initUI(self): self.setAutoFillBackground(True) self.setMouseTracking(True) palette = QPalette() palette.setColor(QPalette.Window,QColor(0,100,0)) self.setPalette(palette) def sizeHint(self): return QSize(800,500) def minimumSizeHint(self): return QSize(300,300) def paintEvent(self,event): qp = QPainter() qp.begin(self) qp.scale(self.scale,self.scale) qp.translate(self.translation) qp.setRenderHint(QPainter.Antialiasing) self.drawGraph(qp) self.drawUI(qp) qp.end() def wheelEvent(self,event): self.cursor.update(event,'o') d = float(event.delta()) self.updateWorldCursor() p = self.worldCursor oldScale = self.scale oldTranslation = self.translation self.scale += d/360 self.scale = min(self.maxScale,self.scale) self.scale = max(self.minScale,self.scale) self.translation=((self.translation+p)*(oldScale/self.scale))-p def drawUI(self,qp): pen = QPen() brush = QBrush(QColor(0,100,0,200)) qp.setPen(pen) qp.setBrush(brush) p = self.worldCursor if self.edgeDragNode != None: qp.drawPath( getArrowPath(self.edgeDragNode.position, p, 4, 40, 20, pi/3, 0, 0 ) ) #qp.drawText(0,20,str(self.translation)) #qp.drawText(0,50,str(self.cursor.x)+','+str(self.cursor.y)) #qp.drawText(0,110,str(self.scale)) #qp.drawEllipse(QPointF(0,0),10,10) #qp.drawEllipse(QPointF(0,100),10,10) #qp.drawEllipse(QPointF(100,100),10,10) #qp.drawEllipse(QPointF(100,0),10,10) #print self.scale def drawGraph(self, qp): for index, concept in self.graph.concepts.items(): self.drawConceptToBridgeEdges(qp, concept, self.graph.ForwardEdges[index]) for index, bridge in self.graph.bridges.items(): self.drawBridgeToConceptEdges(qp, bridge, self.graph.ForwardEdges[index]) for index in self.graph.concepts: self.drawConcept(qp,self.graph.concepts[index]) for index in self.graph.bridges: self.drawBridge(qp,self.graph.bridges[index]) def drawBridgeToConceptEdges(self,qp,bridge,edges): pen = QPen() brush = QBrush(QColor(100,0,0,200)) qp.setPen(pen) qp.setBrush(brush) for e in edges: qp.drawPath( getArrowPath(bridge.position, self.graph.concepts[e].position,10,65,30, pi/3,0,self.graph.concepts[e].radius)) def drawConceptToBridgeEdges(self,qp,concept,edges): pen = QPen() brush = QBrush(QColor(0,0,100,200)) qp.setPen(pen) qp.setBrush(brush) for e in edges: qp.drawPath( getArrowPath(concept.position, self.graph.bridges[e].position,6,40,20, pi/3,0,self.graph.bridges[e].radius)) def drawBridge(self,qp,bridge): self.drawNode(qp,bridge) pen = QPen(QColor(0,0,0)) font = QFont() font.setPointSizeF(12.0/(self.scale**(3.0/4))) font.setItalic(True) font.setBold(True) qp.setPen(pen) qp.setFont(font) bTitle = bridge.title pos = bridge.position + QPointF(1,-1)*bridge.radius qp.drawText(pos,bTitle) def drawConcept(self,qp,concept): self.drawNode(qp,concept) pen = QPen(QColor(0,0,0)) bgBrush = QBrush(QColor(255,255,255,20)) font = QFont() font.setPointSizeF(12.0/(self.scale**(3.0/4))) font.setBold(True) qp.setPen(pen) qp.setFont(font) qp.setBackgroundMode(Qt.OpaqueMode) qp.setBackground(bgBrush) cTitle = concept.title pos = concept.position + QPointF(1,-1)*concept.radius qp.drawText(pos,cTitle) def drawNode(self,qp,node): ring = False ringRadius = 5 if node.selected: pen = QPen(node.palette[2]) brush = QBrush(node.palette[2]) elif node.held: pen = QPen(node.palette[0]) brush = QBrush(node.palette[0]) elif node.hovered: pen = QPen(node.palette[1]) brush = QBrush(node.palette[1]) elif node.highlighted: ring = True pen = QPen(node.palette[3]) brush = QBrush(node.palette[3]) else: pen = QPen(node.palette[3]) brush = QBrush(node.palette[3]) qp.setPen(pen) qp.setBrush(brush) qp.drawEllipse(node.position,node.radius,node.radius) if ring: pen = QPen(node.palette[2]) brush = QBrush() qp.setPen(pen) qp.setBrush(brush) qp.drawEllipse(node.position,\ node.radius + ringRadius,\ node.radius + ringRadius) def setGraph(self,graph): self.graph = graph def mousePressEvent(self,event): self.cursor.update(event,'p') def mouseReleaseEvent(self,event): self.cursor.update(event,'r') def mouseMoveEvent(self,event): self.cursor.update(event,'m') def onLeftClick(self): self.leftClickB = True def onLeftDrag(self): self.leftDragB = True def onHover(self): self.HoverB = True def onLeftPress(self): self.leftPressB = True def onLeftRelease(self): self.leftReleaseB = True def onRightClick(self): self.rightClickB = True def onRightDrag(self): self.rightDragB = True def onRightPress(self): self.rightPressB = True def onRightRelease(self): self.rightReleaseB = True def onRightPull(self): self.rightPullB = True def getClosestNode(self,pos): try: G = self.graph distances=[(node,norm(pos - node.position)) for node in G.Nodes()] r = reduce(ltIndex(1),distances) return r except: return (None,None) def updateWorldCursor(self): c = self.cursor s = QPointF(self.scale,self.scale) t = self.translation self.worldCursor = QPointF((c.x/s.x())-t.x(),(c.y/s.y())-t.y()) def readCursorEvents(self): c = self.cursor self.cursor.resetPrevious = True s = QPointF(self.scale,self.scale) t = self.translation self.updateWorldCursor() pos = self.worldCursor prevPos = QPointF((c._px/s.x())-t.x(),(c._py/s.y())-t.y()) (node,dist) = self.getClosestNode(pos) #Due to the ascynchronous design, it's necessary to order these #properly if (self.leftDragB): try: self.heldNode.position = pos except: self.translation += pos - prevPos self.leftDragB = False if (self.HoverB): if node == None: pass elif (dist < node.radius): self.unhover() self.hover(node) else: self.unhover() self.leftHoverB = False if (self.leftPressB): if node == None: pass elif (dist < node.radius): self.unhold() self.unhover() self.hold(node) self.leftPressB = False if (self.leftReleaseB): self.unhold() self.leftReleaseB = False if (self.leftClickB): if node == None: pass elif (dist < node.radius): self.unhover() self.unhold() if not self.selectedNode == node: self.unselect() self.select(node) else: self.unselect() else: self.unselect() self.leftClickB = False if (self.rightClickB): if node == None: self.addConcept(pos) elif (dist < node.radius): self.deleteNode(node) else: self.addConcept(pos) self.rightClickB = False if (self.rightPullB): if node == None: pass elif dist < node.radius: self.edgeDragNode = node elif self.selectedNode != None: self.edgeDragNode = self.selectedNode else: pass self.rightPullB = False if (self.rightDragB): pass if (self.rightPressB): pass if (self.rightReleaseB): if self.edgeDragNode != None and self.edgeDragNode != node: if dist < node.radius: if isinstance(self.edgeDragNode,Bridge): if isinstance(node,Concept): self.graph.ConnectBridgeToConcept( self.edgeDragNode.key, node.key) elif isinstance(self.edgeDragNode,Concept): if isinstance(node,Bridge): self.graph.ConnectConceptToBridge( self.edgeDragNode.key, node.key) elif isinstance(node,Concept): k =self.addBridge((pos + self.edgeDragNode.position)/2) self.graph.ConnectConceptToBridge(self.edgeDragNode.key,k) self.graph.ConnectBridgeToConcept(k,node.key) self.edgeDragNode = None self.rightReleaseB = False def update(self): self.readCursorEvents() #print "Held Node: ",self.heldNode #print "Selected Node: ",self.selectedNode #print "Hovered Node: ",self.hoverNode self.repaint() def animate(self): t1 = clock() self.update() QTimer.singleShot(max(0,1000/self.fps-(clock()-t1)),self.animate) def select(self,node): self.selectedNode = node self.selectedNode.selected = True for pn in self.graph.ReverseEdges[node.key]: try: self.graph.bridges[pn].highlighted = True except: self.graph.concepts[pn].highlighted = True self.nodeSelected.emit() def unselect(self,node=None): if self.selectedNode == node or node == None: try: self.selectedNode.selected = False for pn in self.graph.ReverseEdges[self.selectedNode.key]: try: self.graph.bridges[pn].highlighted = False except: self.graph.concepts[pn].highlighted = False self.selectedNode = None self.nodeUnselected.emit() except: pass def hold(self, node): self.heldNode = node self.heldNode.held = True def unhold(self, node=None): if self.heldNode == node or node == None: try: self.heldNode.held = False self.heldNode = None except: pass def hover(self,node): self.hoverNode = node self.hoverNode.hovered = True def unhover(self, node=None): if self.hoverNode == node or node == None: try: self.hoverNode.hovered = False self.hoverNode = None except: pass def deleteNode(self,node): self.unselect(node) self.unhold(node) self.unhover(node) try: self.graph.RemoveBridge(node.key) except: self.graph.RemoveConcept(node.key) def addConcept(self,pos): C = Concept() C.position = pos k = self.graph.AddConcept(C) C.key = k return k def addBridge(self,pos): B = Bridge() B.position = pos k = self.graph.AddBridge(B) B.key = k return k def writeTo(self, filename): f = open(filename,'w') dump(self.graph,f) f.close() def readFrom(self,filename): f = open(str(filename),'r') self.graph = load(f) f.close()
class GraphContext(pb.Cacheable): """ GraphContext binds together the elements required to present a Graph in an OpenGL environment. It includes: - The graph - The primary camera - The orthogonal camera - Display settings: - ortho vs. standard camera - whether to show local axes - whether to show ground plane - whether to show HUD - whether to show, and color of, ground plane - color of background - whether to show vertex labels (IDs or names) and whether to show labels for bendpoints - colors for vertex labels and their shadows, and the stroke width for drawing labels """ def __setattr__(self, name, value): # Don't update the remote 'ready' state; it's a local flag. if name != 'observers' and name != 'ready': for o in self.observers: o.callRemote('setattr', {name: value}).addErrback(connectionError, 'context setattr') self.__dict__[name] = value def __init__(self, graph=None, camera=None, orthocamera=None, netcli=False): print "Calling graph context init" # # Cacheable: Keep track of observers # self.__dict__['observers'] = [] if not config.current['global:highlight']: self.highLight = False else: self.highLight = True self.highLightNow = True self.ready = False if not graph: print "Making a graph object" self.graph = Graph(parent=self) else: self.graph = graph if netcli: self.UndoStack = undo.DummyStack(self) self.RedoStack = undo.DummyStack(self) else: self.UndoStack = undo.UndoStack(self) self.RedoStack = undo.RedoStack(self) self.graphgl = graphgl.GraphGL(self.graph) self.decor = interfacegl.InterfaceGL() if not camera: self.camera = Camera() self.camera.lookAt = (0.0, 0.0, 0.0) else: self.camera = camera if not orthocamera: self.orthocamera = OrthoCamera() else: self.orthocamera = orthocamera self.cursor = Cursor() self.path = None # This should default to False and turn on automatically # when you have a 3D input device. # XXX# self.showCursor = False # The drawList should be a dictionary of Drawables, # used by the InputManager to enable transient objects, # menus, etc to be drawn. self.drawList = {} self.orthoMode = None self.showAxes = config.current['default:show-axes'] self.showLocalAxes = config.current['default:show-local-axes'] self.showHUD = config.current['default:show-hud'] self.showGrid = config.current['default:show-grid'] self.showGridLines = config.current['default:show-grid-lines'] self.showPlane = config.current['default:show-plane'] self.planeColor = config.current['default:plane-color'] self.bgColor = config.current['default:background-color'] self.showVertexLabels = config.current['default:show-vertex-labels'] self.showDummyLabels = config.current['default:show-dummy-labels'] self.vertexLabelName = config.current['default:vertex-label-name'] self.vertexLabelColor = config.current['default:vertex-label-color'] self.vertexShadowColor = config.current['default:vertex-shadow-color'] self.vertexLabelStroke = config.current['default:vertex-label-stroke'] self.showGridPlane = "XZ" self.pos = (0.0, 0.0, 0.0) self.sizeX = 5 self.sizeY = 5 self.sizeZ = 5 self.spacing = 2.0 # The HUD status text line. self.HUDstatus = '' #If no highlight object exists, create one. if self.highLight: print "Creating highlight for active context" self.highLight = True from interfacegl import DrawObjectHighLight self.setDraw('wandaHighLight', DrawObjectHighLight( ctx=self, tolerance=5.0, restrict=None, ) ) def getStateToCacheAndObserveFor(self, perspective, observer): """ Add an observer to the list, and return our current state with the observer list stripped out. """ print "adding observer to GraphContext:", perspective, observer self.observers.append(observer) d = self.__dict__.copy() # XXX# What other Cacheable-specific data do we have to remove? if 'parent' in d: d['parent'] = None del d['observers'] del d['graphgl'] del d['decor'] del d['UndoStack'] del d['RedoStack'] return d def stoppedObserving(self, perspective, observer): """ Remove an observer from the list. """ self.observers.remove(observer) print "stopped observing:", perspective, observer def init(self): """ Should be called the first time this context is drawn, after OpenGL has been set up. It ensures that the initial viewpoint reflects the initial camera. """ glEnable(GL_COLOR_MATERIAL) glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE) glEnable(GL_LIGHT0) if self.orthoMode: self.orthocamera.use() else: self.camera.use() # glLightfv(GL_LIGHT0, GL_POSITION, (-0.1, 1.0, 0.1, 0.0)) self.graphgl.init() self.decor.init() self.ready = True def loadFromFile(self, filename, format, queryCallback=None, warningCallback=None): """Loads a graph into this context. Sets up defaults for ground plane and camera.""" filepath = path.realpath(filename) (dir, basename) = path.split(filepath) (prefix, ext) = path.splitext(basename) fobj = file(filepath, 'rU') format.load(self.graph, fobj, queryCallback=queryCallback, warningCallback=warningCallback) fobj.close() self.graph.new = False self.graph.change(False) # Set this to force a rendering update of the graph - maybe there's # a better way to do it? It hasn't been changed (for saving purposes) # but the graph object itself has changed (for display purposes). self.graph.dirty = True # Store the path self.path = filename # These should be user preferences.Cursor() self.showAxes = config.current['default:show-axes'] self.showLocalAxes = config.current['default:show-local-axes'] self.showPlane = config.current['default:show-plane'] self.showHUD = config.current['default:show-hud'] self.showGrid = config.current['default:show-grid'] self.showGridLines = config.current['default:show-grid-lines'] self.planeColor = config.current['default:plane-color'] self.bgColor = config.current['default:background-color'] self.showVertexLabels = config.current['default:show-vertex-labels'] self.showDummyLabels = config.current['default:show-dummy-labels'] self.vertexLabelName = config.current['default:vertex-label-name'] self.vertexLabelColor = config.current['default:vertex-label-color'] self.vertexShadowColor = config.current['default:vertex-shadow-color'] self.vertexLabelStroke = config.current['default:vertex-label-stroke'] self.orthoMode = None # Cacheable: Send all these parameters across the wire if self.observers: d = self.__dict__.copy() del d['observers'] del d['graphgl'] del d['decor'] for o in self.observers: o.callRemote('setattr', d).addErrback(connectionError, 'context loadfromfile') # Update the graph edge and vertex lists. for o in self.graph.observers: o.callRemote('setattr', { 'vertices': self.graph.vertices, 'vertices_selected': self.graph.vertices_selected, 'edges': self.graph.edges, 'edges_selected': self.graph.edges_selected, }) o.callRemote('change', True) self.camera.lookAtGraph(self.graph, self.graph.centerOfMass(), offset=self.graph.viewpoint()) def writeToFile(self, format=None, filename=None, options={}): """GraphContext.writeToFile(filename = None) -> void Writes the graph in this context out to a file, autodetecting the filetype from the name of the file. If filename == None, will attempt to use self.path. If self.path == None and filename == None, raises ExportError.""" # Detect what kind of file we're loading and # call a specialized loader if filename == None or format == None: if not self.path == None: filename = self.path filepath = path.realpath(filename) (dir, basename) = path.split(filepath) (prefix, ext) = path.splitext(basename) if not ext == '.mg' and not ext == '.mg2': raise ExportError, "Couldn't save into exported type." format = formatmanager.formats[ext[1:]] else: raise ExportError, "Couldn't save new file without filename." filepath = path.realpath(filename) format.write(self.graph, filepath, options=options) self.path = filename self.graph.change(False) def exportToFile(self, filename, format, options={}): """GraphContext.exportToFile(filename) -> void Writes the graph in this context out to a file, autodetecting the filetype from the name of the file. Will not change the path or reset the changed flag.""" filepath = path.realpath(filename) format.write(self.graph, filepath, options=options) def writeToPOVRay(self, filename, options={}): """Draw the graph to a .pov POVRay file Arguments: filename -- name of the file with path and extension options -- a dictionary of POVRay options """ filepath = path.realpath(filename) if 'skyColor' not in options: options['skyColor'] = self.bgColor if 'planeColor' not in options: options['planeColor'] = self.planeColor if self.orthoMode: formatmanager.formats['pov'].write(self.graph, filepath, self.orthocamera, options=options) else: formatmanager.formats['pov'].write(self.graph, filepath, self.camera, options=options) def revert(self): """GraphContext.revert() -> void Reloads a context from the last saved state. Raises ImportError if there is no last saved state.""" if self.path == None: raise ImportError, "Can't revert an unsaved context." filepath = path.realpath(self.path) (dir, basename) = path.split(filepath) (prefix, ext) = path.splitext(basename) self.graph.clear() self.loadFromFile(self.path, formatmanager.formats[ext[1:]]) def setDraw(self, slot, drawable): self.drawList[slot] = drawable for o in self.observers: o.callRemote('setattr', {'drawList': self.drawList}).addErrback(connectionError, 'context setDraw') def delDraw(self, slot): if slot in self.drawList: del self.drawList[slot] for o in self.observers: o.callRemote('setattr', {'drawList': self.drawList}).addErrback(connectionError, 'context removeDraw') def getDraw(self, slot): return self.drawList[slot] def draw(self, edgeNameBase=None, vertNameBase=None): """Draw the elements of this context on the current GL canvas.""" if not self.ready: self.init() # Set up the camera if self.orthoMode: activecam = self.orthocamera else: activecam = self.camera activecam.use() # Apply the tracker offsets. activecam.useTracker() if self.graph.vertices_selected: orbitCentre = self.graph.vertices_selected[0] else: orbitCentre = self.graph.centerOfMass() # Multiply points if snapping to grid if self.showGrid: ocp = utilities.mult3D(orbitCentre.pos, self.spacing) else: ocp = orbitCentre.pos if config.current['global:camera-orbit'] == "cw": self.camera.absorbit(ocp, Y_AXIS, -1) elif config.current['global:camera-orbit'] == "ccw": self.camera.absorbit(ocp, Y_AXIS, 1) # Only draw decorations if we're in render mode - not in # selection mode. if glGetInteger(GL_RENDER_MODE) == GL_RENDER: # Draw the ground plane if it's enabled, but not when we're # using ortho mode glEnable(GL_CULL_FACE) if self.showPlane and not self.orthoMode: self.decor.drawGroundPlane(height=self.graph.findGroundPlane(), color=self.planeColor, reference=self.camera.pos) # # Draw the graph # glEnable(GL_TEXTURE_2D) self.graphgl.draw(edgeNameBase=edgeNameBase, vertNameBase=vertNameBase) # # Draw A grid if the user wants one # if self.showGridLines: self.decor.drawGrid(parent=self, pos=self.pos, sizeX=self.sizeX, sizeY=self.sizeY, sizeZ=self.sizeZ, spacing=self.spacing) # Only draw decorations if we're in render mode - not in # selection mode. if glGetInteger(GL_RENDER_MODE) == GL_RENDER: glEnable(GL_CULL_FACE) # Draw the coordinate axes if they're enabled if self.showAxes: self.decor.drawAxes() # Draw local axes if required # print "window:",wx.Window.FindFocus(), "\n canvas:", self.parent.canvas showA = False if not self.parent == None: if wx.Window.FindFocus() == self.parent.canvas: showA = True if self.showLocalAxes and showA: localAxes = (X_AXIS, Y_AXIS, Z_AXIS) labels = ('Q', 'A', 'W', 'S', 'E', 'D') if self.orthoMode: if self.orthoMode[0] == X_AXIS: localAxes = (Y_AXIS, Z_AXIS) if self.orthoMode[1] > 0: labels = (None, None, 'W', 'S', 'D', 'A') else: labels = (None, None, 'W', 'S', 'A', 'D') elif self.orthoMode[0] == Y_AXIS: localAxes = (X_AXIS, Z_AXIS) if self.orthoMode[1] > 0: labels = ('A', 'D', None, None, 'S', 'W') else: labels = ('D', 'A', None, None, 'S', 'W') elif self.orthoMode[0] == Z_AXIS: localAxes = (X_AXIS, Y_AXIS) if self.orthoMode[1] > 0: labels = ('A', 'D', 'W', 'S', None, None) else: labels = ('D', 'A', 'W', 'S', None, None) for v in self.graph.vertices_selected: if v.hidden: continue self.decor.draw_localaxes(self, v, axes=localAxes, labels=labels) # Draw vertex labels if selected. if self.showVertexLabels: if self.showDummyLabels: vxlist = self.graph.vertices else: vxlist = [x for x in self.graph.vertices if not isinstance(x, DummyVertex)] if len(vxlist) > 0: if self.vertexLabelName: labelFunc = lambda v: str(v.name) else: labelFunc = lambda v: str(v.id) self.decor.drawVertexLabels(parent=self, vxlist=vxlist, labelFunc=labelFunc, labelStrokeWidth=self.vertexLabelStroke, labelColor=self.vertexLabelColor, shadowColor=self.vertexShadowColor) if self.showHUD: if self.showCursor: self.decor.drawHUD(activecam, self.graph.vertices_selected, pos=self.cursor.realPosition(activecam), status=self.HUDstatus) else: self.decor.drawHUD(activecam, self.graph.vertices_selected, status=self.HUDstatus) if self.showCursor: # First, draw the local grid around the cursor position. # self.decor.drawLocalGrid(pos = self.cursor.realPosition(activecam), size=1, spacing=5.0, snap=5.0) glEnable(GL_CULL_FACE) glDisable(GL_TEXTURE_2D) glDisable(GL_POLYGON_SMOOTH) self.decor.drawCursor(camera=activecam, cursor=self.cursor) for d in self.drawList.values(): d.draw() def goPersp(self): """ Restore and unlock the perspective camera in this context. """ self.orthoMode = None for o in self.observers: o.callRemote('setOrtho', None).addErrback(connectionError, 'abc') def goOrtho(self, axis, look): """ Align and lock in this context for orthographic movement. axis and side specify the alignment of the camera. eg. goOrtho(Y_AXIS, -1) will place the camera on the Y axis looking in the negative direction with movement restricted to the XZ plane. """ self.orthoMode = (axis, look) for o in self.observers: o.callRemote('setOrtho', self.orthoMode).addErrback(connectionError, 'abc') self.orthocamera.setOnAxis(axis, look * -20.0) def vertexWarp(self, vertex, refresh=None): """ Warp to vertex, using the Animator. """ from utilities import add3D, diff3D, mult3D offset = add3D(mult3D(self.camera.vpn, -10.0), (0.0, vertex.radius * 3.0, 0.0)) if self.showGrid: npos = utilities.mult3D(vertex.pos, self.spacing) else: npos = vertex.pos targetpos = add3D(npos, offset) self.parent.animator.perspCameraMove(self.camera, newPos=targetpos, newLook=npos, duration=1.0) def lookAt(self, target, refresh=None): """ Re-point the current camera to look at some object in the graph. Target can be: - a position in 3-space expressed as a 3-tuple of floats - a Vertex object - an Edge object (will look at the midpoint) """ if isinstance(target, Vertex): if self.showGrid: tgt = target tgt.pos = utilities.mult3D(target.pos, self.spacing) else: tgt = target elif isinstance(target, Edge): if self.showGrid: tgt = target tgt.source.pos = utilities.mult3D(target.source.pos, self.spacing) tgt.target.pos = utilities.mult3D(target.target.pos, self.spacing) else: tgt = target elif self.showGrid: tgt = utilities.mult3D(target, self.spacing) else: tgt = target if self.orthoMode: # XXX# Do something pass else: self.parent.animator.perspCameraMove( camera=self.camera, newLook=tgt, duration=1.2, )
class Engine(object): __world_objects = WeakKeyDictionary() def __init__(self): self.__message_queue = [] self.__cur_stat_surf = None self.__actors = [] self.__items = [] self.__gfx = None self.__quit_loop = False self.__last_id = 0 self.__id_gen = self.__gen_id() self.__actors_on_screen = [] self.__timer = 0 self.__world_time = 0 self.__load_fonts() self.__build_surf_cache() self.__set_game_instance() self.__player_actions = PlayerActions(self) self.__state_worker = StateWorker(self) self.__actor_grid = [] self.__item_grid = [] for y in xrange(200): aline = [] iline = [] for x in xrange(200): aline.append([]) iline.append([]) self.__actor_grid.append(aline) self.__item_grid.append(iline) self.map = None self.dungeon = dungeon.DungeonsOfGogadan() self.quit_mes = QUIT self.stats = [att.Att('Strength', 'Important for Melee-Fighter', 20), att.Att('Endurance', 'Important for Melee-Fighter'), att.Att('Mind', 'Important for Spellcaster'), att.Att('Health', 'How much can you take?', 45)] self.camera = Camera(20, 26) self.state = S_RUN self.__await_target = None Debug.init_debug(self) Debug.debug('init pygame') pygame.init() self.screen = pygame.display.set_mode((1024, 768)) self.__clock = pygame.time.Clock() self.item_to_throw = None self.cursor = Cursor(self) self._items_to_choose = {} self._symbols = [] c = 'abcdefghijklmonpqrstuvwxyz' for s in c: self._symbols.append(s) def call_pl_item_throw(self): self.__player_actions.throw_fire() def re_init(self): Debug.debug('re_init') self.__quit_loop = False self.quit_mes = QUIT self.__load_fonts() self.__build_surf_cache() self.__set_game_instance() self.__clock = pygame.time.Clock() self.__id_gen = self.__gen_id() for act in self.__actors: self.__world_objects[act] = True for item in self.__items: self.__world_objects[item] = True self.__world_objects[self.map] = True self.__clear_surfaces() if hasattr(self, 'map'): self.redraw_map() def get_symbol(self): s = self._symbols.pop(0) return s def free_symbol(self, s): if s == None: return self._symbols.append(s) self._symbols.sort() def get_actor_at(self, pos): x, y = pos act = self.__actor_grid[y][x] return act[0] if len(act) > 0 else None #for actor in self.__actors: # if actor.pos() == pos: # return actor #return None def get_all_srd_actors(self, pos, radius=1, null_pos=False): mo = [] for x in xrange(-radius, radius + 1): for y in xrange(-radius, radius + 1): mo.append((x, y)) if not null_pos: mo.remove((0, 0)) poss = [] for m in mo: poss.append((m[0] + pos[0], m[1] + pos[1])) actors = [] for p in poss: acts = self.get_actor_at(p) if not acts == None: actors.append(acts) return actors #for act in self.__actors: # if act.pos() in poss: # actors.append(act) #return actors def get_free_adj(self, pos): new_pos = None mo = [(-1, -1), (-1, 0), (-1, 1), (1, -1), (1, 0), (1, 1), (0, -1), (0, 1)] random.shuffle(mo) while new_pos == None and len(mo) > 0: t = mo.pop() new_pos = pos[0] + t[0], pos[1] + t[1] if not self.map.map_array[new_pos[1]][new_pos[0]][MT_FLAGS] & F_WALKABLE: new_pos = None else: for actor in self.__actors: if actor.pos() == new_pos: new_pos = None break return new_pos def get_sc_up_pos(self): y = 0 x = 0 pos = None for line in self.map.map_array: x = 0 for t in line: if t == MAP_TILE_up: pos = x, y x += 1 y += 1 return pos if pos != None else self.map.get_random_pos() def get_sc_down_pos(self): y = 0 x = 0 pos = None for line in self.map.map_array: x = 0 for t in line: if t == MAP_TILE_down: pos = x, y x += 1 y += 1 return pos if pos != None else self.map.get_random_pos() def get_actor_by_id(self, id): for act in self.__actors: if act.id == id: return act def shout(self, text): self.__message_queue.insert(0, text) print text def change_map(self, down=True): if self.map == None: level = 1 elif down: level = self.map.level + 1 self.__save_map() else: level = self.map.level - 1 self.__save_map() if self.__load_map(level): return if level == 0: self.game_over() self.__actors = [] self.__actors.append(self.player) self.__items = [] self.map = self.dungeon.get_map(level) for act in self.__actors: act.sc = sc(self.map.map_array) if down: pos = self.get_sc_up_pos() else: pos = self.get_sc_down_pos() self.player.set_pos(pos) r = self.camera.adjust(self.player.pos()) while r: r = self.camera.adjust(self.player.pos()) def create_gold(self, amount, pos): gold = dungeon.Populator.create_item('Gold', 'basic_stuff', 0) gold.amount = amount gold.set_pos(pos) self.add_item(gold) def summon_monster(self, caster, name, file, pos): mon = dungeon.Populator.create_creature(name, file) mon.ai = henchmanAI.HenchmanAI(mon) mon.ai.friends.add(caster.id) caster.ai.friends.add(mon.id) mon.set_pos(pos) mon.sc = sc(self.map.map_array) self.add_actor(mon, True) def create_humanoid(self): #man = races[1][3](True, 1) man = races[2][3](True, 1) #man.classkit = classkits[2][1](man) man.classkit = classkits[0][1](man) from ai import simpleai man.ai = henchmanAI.HenchmanAI(man) man.name = 'Nigg Yshur' pos = self.get_free_adj(self.player.pos()) man.set_pos(pos) man.ai.friends.add(self.player.id) self.player.ai.friends.add(man.id) man.sc = sc(self.map.map_array) #self.player = races[race][3](True, gender) #self.player.classkit = classkits[classkit][1](self.player) #self.player.classkit = classkits[classkit][1](self.player) #b = dungeon.Populator.create_item('TomeOfVileUmbrages','tovu',100) #self.player.pick_up(b) def create_character(self): c_res = Res('dc-pl.png', TILESIZE) g = 'female', 'male' gender = 1 race = 0 classkit = 0 OK = False name = '' title = 'He' title2 = 'His' story = ['This is the incredible story of our hero', 'Long time ago, there was a hero named', 'There once was a time, long ago, when'] s = random.choice(story) while not OK: self.screen.fill(BLACK) self.__render_text(self.screen, 'Build your character:', WHITE, ((35, 30)), 'big') self.screen.blit(self.__surf_cache['mes_block2'], (60, 65)) img = pygame.transform.smoothscale(c_res.get(races[race][1 + gender]), (TILESIZE * 2, TILESIZE * 2)) self.screen.blit(img , (75, 100)) self.__render_text(self.screen, name, WHITE, ((73, 170))) y = 100 self.__render_text(self.screen, s, WHITE, ((145, y))) self.__render_text(self.screen, name, GREEN, ((395, y))) y += 20 self.__render_text(self.screen, 'the' , WHITE, ((145, y))) self.__render_text(self.screen, g[gender] + ' ' + races[race][0] + ' ' + classkits[classkit][0] + '.', GREEN, ((167, y))) y += 20 self.__render_text(self.screen, title + ' ' + races[race][3].desc, WHITE, ((145, y))) y += 20 self.__render_text(self.screen, classkits[classkit][1].desc.replace('$$$', title.lower()).replace('%%%', title2.lower()), WHITE, ((145, y))) self.__render_text(self.screen, 'Type in your name', WHITE, ((600, 100))) self.__render_text(self.screen, 'press F1 / F2 to change race', WHITE, ((600, 120))) self.__render_text(self.screen, 'press F3 / F4 to change class', WHITE, ((600, 140))) self.__render_text(self.screen, 'press F5 to change gender', WHITE, ((600, 160))) self.__render_text(self.screen, 'press Enter to start', WHITE, ((600, 180))) pygame.display.flip() for e in pygame.event.get(): if e.type == pygame.QUIT: sys.exit() if e.type == pygame.KEYDOWN: if e.key == pygame.K_F5: if gender == 1: gender -= 1 title = 'She' title2 = 'Her' else: gender += 1 title = 'He' title2 = 'His' if e.key == pygame.K_F3: classkit += 1 if classkit >= len(classkits): classkit = 0 elif e.key == pygame.K_F4: classkit -= 1 if classkit < 0: classkit = len(classkits) - 1 elif e.key == pygame.K_F1: race += 1 if race >= len(races): race = 0 elif e.key == pygame.K_F2: race -= 1 if race < 0: race = len(races) - 1 elif e.key == pygame.K_RETURN: self.player = races[race][3](True, gender) self.player.classkit = classkits[classkit][1](self.player) b = dungeon.Populator.create_item('TomeOfVileUmbrages', 'tovu', 100) self.player.pick_up(b) self.player.clear_surfaces() self.player.timer = 0 OK = True elif e.key == pygame.K_BACKSPACE: if len(name) > 0: name = name[:-1] else: kn = pygame.key.name(e.key) if kn in 'abcdefghijklmnopqrstuvwxyz' and len(name) < 10: if len(name) > 0: name += pygame.key.name(e.key) else: name += pygame.key.name(e.key).upper() def start(self, ts): if ts: self.create_character() self.change_map() self.create_humanoid() Debug.debug('starting mainloop') return self._main_loop() def is_inside_map(self, pos): return not (pos[0] < 0 or pos[1] < 0 or pos[0] >= self.map.width or pos[1] >= self.map.height) def update_item_pos(self, item, new_pos): x, y = item.pos() nx, ny = new_pos if item in self.__item_grid[y][x]: self.__item_grid[y][x].remove(item) self.__item_grid[ny][nx].append(item) def update_actor_pos(self, act, new_pos): x, y = act.pos() nx, ny = new_pos if act in self.__actor_grid[y][x]: self.__actor_grid[y][x].remove(act) self.__actor_grid[ny][nx].append(act) def is_move_valid(self, actor, new_pos): if not self.is_inside_map(new_pos): return False nx, ny = new_pos act = self.__actor_grid[ny][nx] if len(act) > 0: return act[0] valid = self.map.can_enter(new_pos, actor.move_mode) if valid and actor == self.player: self.map.cur_surf = None items = self.get_items_at(new_pos) if len(items) == 1: self.shout('You see a %s' % (items[0].get_name())) if len(items) > 1: self.shout('You see several items here') return valid def get_range_target(self, cpos, tpos): return self.get_actor_at(tpos) # if cpos != tpos: # poss = line(cpos[0], cpos[1], tpos[0], tpos[1]) # poss.pop(0) # for pos in poss: # actor = self.get_actor_at(pos) # if actor != None: # return actor # else: # return self.caster # return None def throw_item(self, attacker, item, target_pos): t_pos = target_pos s_pos = attacker.pos() victim = self.get_range_target(attacker.pos(), target_pos) if victim != None: t_pos = victim.pos() dir = attacker.locateDirection(t_pos) gfx = throw.ThrowFX(dir, s_pos, t_pos, item) self.drawGFX(gfx) item.set_pos(t_pos) def range_attack(self, attacker, target_pos): t_pos = target_pos s_pos = attacker.pos() victim = self.get_range_target(attacker.pos(), target_pos) if victim != None: t_pos = victim.pos() dir = attacker.locateDirection(t_pos) gfx = projectile.ProjectileFX(dir, s_pos, t_pos) self.drawGFX(gfx) #while self.__gfx != None: # self._world_draw() if victim != None: self.attack(attacker, victim, True) def __c_end_friendship(self, attacker, victim): victim.ai.friends.discard(attacker.id) victim.ai.hostile.add(attacker.id) attacker.ai.friends.discard(victim.id) attacker.ai.hostile.add(victim.id) todel = [] for id in victim.ai.friends: act = self.get_actor_by_id(id) if act == None: todel.append(id) else: act.ai.friends.discard(attacker.id) act.ai.hostile.add(attacker.id) for id in todel: victim.ai.friends.discard(id) todel = [] for id in attacker.ai.friends: act = self.get_actor_by_id(id) if act == None: todel.append(id) else: act.ai.friends.discard(victim.id) act.ai.hostile.add(victim.id) for id in todel: attacker.ai.friends.discard(id) def __c_apply_effects(self, attacker, victim): for fx in attacker.get_av_fx(): if d(100) <= fx[1]: Debug.debug('Applied effect %s to %s by %s' % (fx[0], victim, attacker)) f = fx[0](victim, attacker) f.tick() for fx in victim.get_dv_fx(): skip = False for nt in fx[0].notrigger: if attacker.slot.weapon.flags & nt: skip = True if not skip and d(100) <= fx[1]: Debug.debug('Applied effect %s to %s by %s' % (fx[0], attacker, victim)) f = fx[0](attacker, victim) f.tick() def attack(self, attacker, victim, ranged=False): self.__c_end_friendship(attacker, victim) vi_adress = (victim == self.player and ['you'] or ['the ' + victim.name])[0] at_miss_adress = (attacker == self.player and ['You miss'] or [attacker.name + ' misses'])[0] at_hit_adress = (attacker == self.player and ['You hit'] or ['The ' + attacker.name + ' hits'])[0] at_kill_adress = (attacker == self.player and ['You killed'] or ['The ' + attacker.name + ' killed'])[0] wpn = attacker.weapon if wpn == None: wpn = attacker.unarmed_weapon highest_skill = None, 0 for s in wpn.skills: v = getattr(attacker.skills, s) if v > highest_skill[1]: highest_skill = s, v attack_roll = d(100) if attack_roll > highest_skill: self.shout('%s %s.' % (at_miss_adress, vi_adress)) Debug.debug('Miss!') return if victim.get_RA() > 0 and not victim.unconscious: victim.RA -= 1 dodge_skill = victim.skills.Dodge dodge_roll = d(100) if dodge_roll <= dodge_skill: self.shout('%s dodged the attack' % (vi_adress)) return self.__c_apply_effects(attacker, victim) hit_zone = victim.HP.get_random_zone() z = getattr(victim.HP, hit_zone)[2] if wpn.type != I_VOID: damage = wpn.damage[1]() + attacker.get_DM()[0]() else: damage = d(3) + attacker.get_DM()[0]() dam=self.do_damage(victim, damage, hit_zone, source=attacker) self.shout('%s %s at the %s for %i damage' % (at_hit_adress, vi_adress, z,dam)) def do_damage(self, act, dam, zone, type=D_GENERIC, source=None): return act.do_damage(dam, zone, type) def wait_for_target(self, point_of_entry): self.__await_target = point_of_entry self.__player_actions.cursor() def do_identify(self): self.__player_actions.identify() def target_choosen(self, pos): self.__await_target(pos) self.__await_target = None #self.player.fire(pos) def get_items_at(self, pos): x, y = pos #print self.__item_grid[y][x] return [item for item in self.__item_grid[y][x] if not item.picked_up] #return [item for item in self.__items if item.pos() == pos] def game_over(self): print 'You failed' self.__quit_loop = True self.__actors = [] def redraw_map(self): self.map.cur_surf = None def redraw_stats(self): self.__cur_stat_surf = None def add_to_world_objects(self, obj): self.__world_objects[obj] = True def add_actor(self, actor, add=True): if add: self.__actors.append(actor) if self.map != None: actor.sc = sc(self.map.map_array) self.__world_objects[actor] = True def add_item(self, item, add=True): if add: self.__items.append(item) self.__world_objects[item] = True def del_actor(self, actor): if actor in self.__actors: self.__actors.remove(actor) if actor in self.__actors_on_screen: self.__actors_on_screen.remove(actor) x, y = actor.pos() if actor in self.__actor_grid[y][x]: self.__actor_grid[y][x].remove(actor) def del_item(self, item): if item in self.__items: self.__items.remove(item) x, y = item.pos() if item in self.__item_grid[y][x]: self.__item_grid[y][x].remove(item) #if item.player_symbol != None: # self.free_symbol(item.player_symbol) def get_id(self): return self.__id_gen.next() def drawGFX(self, gfx): self.__gfx = gfx self.state = S_GFX # good or bad?? while self.__gfx != None: self._world_draw() def _main_loop(self): while not self.__quit_loop: self.__clock.tick(40) self._world_move() self._world_draw() self._world_input() # print self.clock.get_fps() self.std_font = None self.__clock = None self.__cur_stat_surf = None self.__last_id = self.__id_gen.next() self.__id_gen = None self.__clear_surfaces() return self.quit_mes def _world_input(self): for e in pygame.event.get(): self.__quit_loop = e.type == pygame.QUIT if e.type == pygame.KEYDOWN: if e.key == GAME_SAVE_QUIT: self.__quit_loop = True self.quit_mes = SAVE # --- cheat keys >>> if e.key == pygame.K_F1: for line in self.map.map_array: l = '' for s in line: l = l + str(s[0]) print l if e.key == pygame.K_F2: self.player.cur_health = 200 self.player.cur_endurance = 5000 self.player.cur_mind = 5000 self.player.cur_strength = 5000 if e.key == pygame.K_F3: for item in self.__items: print item.name, item.pos() if e.key == pygame.K_F4: for act in self.__actors: print act.name, act.timer if e.key == pygame.K_F5: for S in gc.get_referrers(Surface): if isinstance(S, Surface): print S print gc.get_referrers(Surface) if e.key == pygame.K_F6: self.create_humanoid() # <<< cheat keys --- if not self.state == S_GFX: self.__cur_stat_surf = None self.moved = True if self.state == S_RUN and not self.player.unconscious: if e.key in PLAYER_ACTIONS: self.__player_actions.__getattribute__(PLAYER_ACTIONS[e.key])() elif self.state in STATE_WORKER: self.__state_worker.__getattribute__(STATE_WORKER[self.state])(e.key) if self.state == S_PLAYER_CURSOR: pygame.event.pump() keys = pygame.key.get_pressed() for key in MOVES: if keys[key]: pygame.time.wait(150) if key == MOVE_WAIT: pos = self.__actors_on_screen[0].pos() if pos == self.cursor.pos(): self.__actors_on_screen.append(self.__actors_on_screen.pop(0)) pos = self.__actors_on_screen[0].pos() self.cursor.set_pos(pos) self.__actors_on_screen.append(self.__actors_on_screen.pop(0)) else: self.cursor.move(key) if self.state == S_RUN and not self.player.unconscious: pygame.event.pump() keys = pygame.key.get_pressed() [self.player.move(key) for key in MOVES if keys[key] and self.player.timer <= 0] def _world_move(self): if not self.__quit_loop: if self.state == S_RUN: self.__actors.sort(sort_by_time) #actors with lowest timer first diff = self.__actors[0].timer self.__timer += diff self.__world_time += diff if self.__timer > 500: #act-independent issues # one combat-round [act.tick() for act in self.__actors] self.__timer -= 500 for actor in self.__actors: if actor.timer > 0: actor.timer -= diff else: actor.act() elif self.state == S_GFX: if self.__gfx == None: self.state = S_RUN def _world_draw(self): if self.__gfx == None or self.__gfx.redraw: if self.camera.adjust(self.player.pos()): self.map.cur_surf = None self.screen.fill((0, 0, 0)) if not self.player.dazzled: self.screen.blit(self.__get_map_surface(), (-self.camera.x * TILESIZE, -self.camera.y * TILESIZE)) if not self.player.dazzled: for item in self.__items: if not item.picked_up and (self.player.sc.lit(item.x, item.y) or self.player.x == item.x and self.player.y == item.y): try: self.screen.blit(self.__get_item_surface(item), (item.x * TILESIZE - self.camera.x * TILESIZE, item.y * TILESIZE - self.camera.y * TILESIZE)) except: print sys.exc_info() print item.name, item.pos(), 'is invalid!!!!' for act in self.__actors: if act == self.player or self.player.sc.lit(act.x, act.y) and not self.player.dazzled: try: self.screen.blit(self.__get_actor_surface(act), (act.x * TILESIZE - self.camera.x * TILESIZE, act.y * TILESIZE - self.camera.y * TILESIZE)) if not act in self.__actors_on_screen: self.__actors_on_screen.append(act) except: print sys.exc_info() print act.name, act.pos(), 'is invalid!!!!' else: if act in self.__actors_on_screen: self.__actors_on_screen.remove(act) if self.state == S_PLAYER_CURSOR: self.screen.blit(self.cursor.get_surf(), (self.cursor.x * TILESIZE - self.camera.x * TILESIZE, self.cursor.y * TILESIZE - self.camera.y * TILESIZE)) self.screen.blit(self.__get_message_surface(), (0, 768 - 128)) self.screen.blit(self.__get_statblock_surface(), (1024 - 192, 0)) if self.__gfx != None: pos = self.__gfx.pos() if pos == None: self.__gfx = None self.__cur_stat_surf = None else: x, y = pos #tiles = __get_affected_tiles(x,y,self.__gfx.get_surf()) x = x / TILESIZE + self.camera.x y = y / TILESIZE + self.camera.y #print x,y,self.player.pos(),self.player.sc.lit(x, y) if self.player.sc.lit(x, y): self.screen.blit(self.__gfx.get_surf(), pos) self.__gfx.tick() pygame.display.flip() def __get_map_surface(self): if self.map.cur_surf == None: self.player.sc.do_fov(self.player.x, self.player.y, 15) surf_map = pygame.Surface((self.map.width * TILESIZE, self.map.height * TILESIZE)) cx, cy, cw, ch = self.camera.get_view_port() for x in xrange(max(cx, 0), min(self.map.width, cw + 1)): for y in xrange(max(cy, 0), min(self.map.height, ch + 1)): pos = (x, y) == self.player.pos() lit = self.player.sc.lit(x, y) memo = self.map.map_array[y][x][MT_FLAGS] & F_MEMO if pos or lit or memo: blit_position = ((x) * TILESIZE, (y) * TILESIZE) surf_map.blit(self.map.get_tile_at(x, y), blit_position) if not pos and not lit and memo: surf_map.blit(self.__surf_cache['FOW'], blit_position) if not self.map.map_array[y][x][MT_FLAGS] & F_MEMO: tile = self.map.map_array[y][x] new_tile = tile[0], tile[1], tile[2] ^ F_MEMO self.map.map_array[y][x] = new_tile self.map.cur_surf = surf_map return self.map.cur_surf def __get_actor_surface(self, act): if act.cur_surf == None: surf_act = pygame.Surface((TILESIZE, TILESIZE), pygame.SRCALPHA, 32) surf_act.blit(act.get_tile(), (0, 0)) act.cur_surf = surf_act return act.cur_surf def __get_item_surface(self, item): if item.cur_surf == None: surf_item = pygame.Surface((TILESIZE, TILESIZE), pygame.SRCALPHA, 32) surf_item.blit(item.get_dd_img(), (0, 0)) item.cur_surf = surf_item return item.cur_surf def __get_message_surface(self): surf = pygame.Surface((1024 - 192, 128)) surf.blit(self.__surf_cache['mes_block'], (0, 0)) y = 100 for mes in self.__message_queue: self.__render_text(surf, mes, WHITE, (20, y)) y -= 20 if y < 10: break return surf def __get_statblock_surface(self): if self.__cur_stat_surf == None: surf = pygame.Surface((192, 768)) surf.fill(BLACK) #surf.blit(self.__surf_cache['stat_block'], (0, 0)) if self.state in (S_RUN, S_GFX): self.__draw_stat_block(surf) if self.state in CHOOSE_STATES: self.__draw_item_choose(surf, CHOOSE_STATES[self.state]) self.__cur_stat_surf = surf return self.__cur_stat_surf def __set_game_instance(self): dungeon.Map.game = self Actor.game = self Item.game = self AI.game = self Camera.game = self dungeon.Populator.game = self magic.Spell.game = self GFX.game = self att.Att.game = self dungeon.SADungeon.game = self def __draw_item_choose(self, surf, message): self.__render_text(surf, message, WHITE, (16, 20)) y = 38 abc = self._items_to_choose.keys() #abc.sort(sort_by_type) s48 = pygame.Surface.copy(self.__surf_cache['stat_32']) for key in abc: item = self._items_to_choose[key] color = WHITE if hasattr(item, 'special'): if item.special: color = GREEN if hasattr(item, 'color'): color = item.color if hasattr(item, 'get_name'): name = item.get_name() else: name = item.name surf.blit(s48, (16, y)) if hasattr(item, 'cur_surf'): surf.blit(self.__get_item_surface(item), (16, y)) self.__render_text(surf, '%s' % (key), WHITE, (16, y)) #self.__render_text(surf, '%s -' % (key), WHITE, (16, y)) self.__render_text(surf, name, color, (64, y)); y += 18 info = item.info() for line in info: self.__render_text(surf, line, color, (64, y)); y += 18 if len(info) == 0: y += 18 y += 18 def __draw_stat_block(self, surf): bt = self.player.get_body_tile() bt = pygame.transform.smoothscale(bt, (96, 96)) bt.set_alpha(122) y = 50 surf.blit(bt, (32, y)) x = 77 y = 55 color = WHITE if self.player.HP.Head[0] == self.player.HP.Head[1]: color = GREEN if self.player.HP.Head[0] == 0: color = YELLOW if self.player.HP.Head[0] < 0: color = RED self.__render_text(surf, str(self.player.HP.Head[0]), color, (x, y)) y = 75 color = WHITE if self.player.HP.Chest[0] == self.player.HP.Chest[1]: color = GREEN if self.player.HP.Chest[0] == 0: color = YELLOW if self.player.HP.Chest[0] < 0: color = RED self.__render_text(surf, str(self.player.HP.Chest[0]), color, (x, y)) y = 95 color = WHITE if self.player.HP.Abdomen[0] == self.player.HP.Abdomen[1]: color = GREEN if self.player.HP.Abdomen[0] == 0: color = YELLOW if self.player.HP.Abdomen[0] < 0: color = RED self.__render_text(surf, str(self.player.HP.Abdomen[0]), color, (x, y)) x = 40 y = 85 color = WHITE if self.player.HP.L_Arm[0] == self.player.HP.L_Arm[1]: color = GREEN if self.player.HP.L_Arm[0] == 0: color = YELLOW if self.player.HP.L_Arm[0] < 0: color = RED self.__render_text(surf, str(self.player.HP.L_Arm[0]), color, (x, y)) x = 110 color = WHITE if self.player.HP.R_Arm[0] == self.player.HP.R_Arm[1]: color = GREEN if self.player.HP.R_Arm[0] == 0: color = YELLOW if self.player.HP.R_Arm[0] < 0: color = RED self.__render_text(surf, str(self.player.HP.R_Arm[0]), color, (x, y)) x = 55 y = 130 color = WHITE if self.player.HP.L_Leg[0] == self.player.HP.L_Leg[1]: color = GREEN if self.player.HP.L_Leg[0] == 0: color = YELLOW if self.player.HP.L_Leg[0] < 0: color = RED self.__render_text(surf, str(self.player.HP.L_Leg[0]), color, (x, y)) x = 95 color = WHITE if self.player.HP.R_Leg[0] == self.player.HP.R_Leg[1]: color = GREEN if self.player.HP.R_Leg[0] == 0: color = YELLOW if self.player.HP.R_Leg[0] < 0: color = RED self.__render_text(surf, str(self.player.HP.R_Leg[0]), color, (x, y)) stats = [('STR ', self.player.STR, self.player.get_STR()), ('CON ', self.player.CON, self.player.get_CON()), ('DEX ', self.player.DEX, self.player.get_DEX()), ('SIZ ', self.player.SIZ, self.player.get_SIZ()), ('INT ', self.player.INT, self.player.get_INT()), ('POW ', self.player.POW, self.player.get_POW()), ('CHA ', self.player.CHA, self.player.get_CHA()), ('DM ', self.player.DM[1], self.player.get_DM()[1])] y = 245 for line in stats: b = 0 if len(str(line[1])) > 3: b = 18 self.__render_text(surf, str(line[0]).rjust(2, ' '), WHITE, (16, y)); self.__render_text(surf, str(line[1]).rjust(2, ' '), GREEN, (55, y)); self.__render_text(surf, '/', WHITE, (70 + b, y)); self.__render_text(surf, str(line[2]).rjust(2, ' '), WHITE, (80 + b, y)); y += 18 #pygame.draw.circle(Surface, color, pos, radius, width=0): return Rect #r = pygame.Surface((100, 2)) #r.fill(RED) #surf.blit(r, (16, y + 20)) #size = float(line[2]) / float(line[1]) * 100 #if size > 0: # g = pygame.Surface((size, 2)) # if size > 100: # g.fill(BLUE) # else: # g.fill(GREEN) #surf.blit(g, (16, y + 20)) self.__render_text(surf, 'Gold:', WHITE, (16, 510)) self.__render_text(surf, str(self.player.gold), WHITE, (90, 510)) self.__render_text(surf, 'XP:', WHITE, (16, 528)) self.__render_text(surf, str(self.player.xp), WHITE, (90, 528)) i = 0 y = 600 count = len(self.player.items) s32 = pygame.Surface.copy(self.__surf_cache['stat_32']) sgreen = pygame.Surface.copy(self.__surf_cache['sgreen']) for h in xrange(3): for x in xrange(5): pos = (x * TILESIZE + x * 3 + 5, h * TILESIZE + y + h * 3) surf.blit(s32, pos) if i < count: item = self.player.items[i] if item.equipped: surf.blit(sgreen, pos) surf.blit(self.__get_item_surface(item), pos) self.__render_text(surf, self.player.items[i].get_ps(), WHITE, (pos)) i += 1 #print (x*TILESIZE,h*TILESIZE+y) self.__render_text(surf, self.dungeon.name, WHITE, (16, 710)) self.__render_text(surf, 'Level: %i' % (self.map.level), WHITE, (16, 728)) def __render_text(self, surf, text, color, pos, font='std'): t = self.__font_cache[font].render('%s' % (text), True, color) ts = self.__font_cache[font].render('%s' % (text), True, BLACK) surf.blit(ts, (pos[0] + 1, pos[1] + 1)) surf.blit(t, pos) def __load_fonts(self): #self.std_font = pygame.font.Font(os.path.join('font', 'jesaya.ttf'), 14) self.__font_cache = {'std':pygame.font.Font(os.path.join('font', 'alex.ttf'), 17), 'big':pygame.font.Font(os.path.join('font', 'alex.ttf'), 25)} def __save_map(self): self.__clear_surfaces() self.__actors.remove(self.player) data = self.map, self.__actors, self.__items , self.player.pos() if os.access('MAP%i.gz' % (self.map.level), os.F_OK): os.remove('MAP%i.gz' % (self.map.level)) FILE = gzip.open('MAP%i.gz' % (self.map.level), 'w') pickle.dump(data, FILE, 2) FILE.close() def __load_map(self, level): if os.access('MAP%i.gz' % (level), os.F_OK): FILE = gzip.open('MAP%i.gz' % (level), 'r') self.map, self.__actors, self.__items, pos = pickle.load(FILE) self.__set_game_instance() FILE.close() self.player.set_pos(pos) r = self.camera.adjust(self.player.pos()) while r: r = self.camera.adjust(self.player.pos()) self.__actors.append(self.player) for act in self.__actors: self.__world_objects[act] = True act.sc = sc(self.map.map_array) self.player.sc.do_fov(self.player.x, self.player.y, self.player.cur_mind / 20 + 5) for item in self.__items: self.__world_objects[item] = True self.__world_objects[self.map] = True self.__clear_surfaces() self._world_draw() return True return False self.__quit_loop = True self.quit_mes = SAVE def __build_surf_cache(self): fow_surf = pygame.Surface((TILESIZE, TILESIZE)) fow_surf.fill(BLACK) fow_surf.set_alpha(100) sgreen = pygame.Surface((TILESIZE, TILESIZE)) sgreen.fill(GREEN) sgreen.set_alpha(100) self.__surf_cache = {'sgreen':sgreen, 'FOW': fow_surf, 'stat_block': load_image('stat.png'), 'stat_48': load_image('48.png'), 'stat_32': pygame.transform.smoothscale(load_image('48.png'), (32, 32)), 'mes_block':load_image('mes_block.png'), 'mes_block2':load_image('mes_block2.png')} def __clear_surfaces(self): for obj in self.__world_objects.keys(): obj.clear_surfaces() self.cursor.cursor_surf = None def __gen_id(self): for x in xrange(self.__last_id, 9999999): yield x
class Menu(object): """docstring for Menu""" def __init__(self, screen): self.clock = pygame.time.Clock() self.screen = screen self.buffer = pygame.Surface(self.screen.get_size()) self.font = pygame.font.Font(FONT, FONT_SIZE) self.menu_items = ['Items','Equip','Magic','Status','Save','Close','Quit'] self.menu_image = pygame.image.load(IMAGES_DIR+'menu.png').convert_alpha() self.cursor = Cursor(ypos=[5,30,55,80,105,130,155]) def open_menu(self): menu = True pygame.key.set_repeat() while menu: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: menu = False if event.key == K_DOWN: self.cursor.move_down() if event.key == K_UP: self.cursor.move_up() if event.key == K_RETURN: if self.cursor.position.y == 30: self.open_equipment() if self.cursor.position.y == 55: self.open_magic() if self.cursor.position.y == 80: self.open_status() if self.cursor.position.y == 105: self.save() if self.cursor.position.y == 130: menu = False if self.cursor.position.y == 155: pygame.quit() self.buffer.blit(self.menu_image, (0,0)) self.render_menu() self.render_cursor() pygame.transform.scale(self.buffer, self.screen.get_size(), self.screen) pygame.display.flip() self.clock.tick(60) pygame.key.set_repeat(1,5) def render_menu(self): pos = 5 for item in self.menu_items: self.buffer.blit(self.font.render(item, 0, pygame.Color("white")), (self.buffer.get_width()-110,pos)) pos += 25 def render_cursor(self, animate=True): if animate: self.cursor.update() self.buffer.blit(self.cursor.image, self.cursor.position) def save(self): # Save function goes here ! print "Game Save" def open_magic(self): # MAGIC ! TODO popup = True while popup: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_RETURN: popup = False self.buffer.blit(self.menu_image, (0,0)) self.render_menu() self.render_cursor(animate=False) self.buffer.blit(self.font.render("You don't have any magic... Yet...", 0,pygame.Color("white")), (10, 50)) pygame.transform.scale(self.buffer, self.screen.get_size(), self.screen) pygame.display.flip() self.clock.tick(60) def open_equipment(self): # EQUIPMENT ! TODO popup = True while popup: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_RETURN: popup = False self.buffer.blit(self.menu_image, (0,0)) self.render_menu() self.render_cursor(animate=False) self.buffer.blit(self.font.render("You don't have any equipment...", 0,pygame.Color("white")), (10, 50)) self.buffer.blit(self.font.render("(Yes I'm a lazy developper...)", 0,pygame.Color("white")), (10, 65)) pygame.transform.scale(self.buffer, self.screen.get_size(), self.screen) pygame.display.flip() self.clock.tick(60) def open_status(self): menu = True statuscursor = Cursor(ypos=[25, 85, 145, 205], xpos=[0]) while menu: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: menu = False if event.key == K_DOWN: statuscursor.move_down() if event.key == K_UP: statuscursor.move_up() if event.key == K_RETURN: if statuscursor.position.y == 25: self.status(self.team[0]) if statuscursor.position.y == 85: self.status(self.team[1]) if statuscursor.position.y == 145: self.status(self.team[2]) if statuscursor.position.y == 205: self.status(self.team[3]) self.buffer.blit(self.menu_image, (0,0)) self.render_menu() statuscursor.update() self.buffer.blit(statuscursor.image, statuscursor.position) pygame.transform.scale(self.buffer, self.screen.get_size(), self.screen) pygame.display.flip() self.clock.tick(60) def status(self, char): menu = True while menu: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: menu = False self.buffer.blit(self.menu_image, (0,0)) self.render_char(char, 1) self.buffer.blit(self.font.render("Skills", 0,(255,255,255)), (60, 45)) self.buffer.blit(self.font.render("Stats", 0,(255,255,255)), (60, 60)) self.buffer.blit(self.font.render("Strength : %d" % char.str, 0,(255,255,255)), (60, 75)) self.buffer.blit(self.font.render("Defense : %d" % char.defense, 0,(255,255,255)), (300, 75)) self.buffer.blit(self.font.render("Intelligence : %d" % char.int, 0,(255,255,255)), (60, 90)) self.buffer.blit(self.font.render("Magic Defense : %d" % char.mdefense, 0,(255,255,255)), (300, 90)) self.buffer.blit(self.font.render("Dexterity : %d" % char.dex, 0,(255,255,255)), (60, 105)) pygame.transform.scale(self.buffer, self.screen.get_size(), self.screen) pygame.display.flip() self.clock.tick(60)
def __init__(self): ############### # load config # ############### with open('config.yaml') as f: CONFIG = yaml.load(f) with open('mvc.yaml') as f: MVC = yaml.load(f) self.subj_id = CONFIG['subject-id'] self.subj_dir = 'datasets/' + self.subj_id self.loc = CONFIG['location'] ################# # set constants # ################# if self.loc == 'lab': self.FRAME_RATE = 120 elif self.loc == 'scanner': self.FRAME_RATE = 60 self.SCREEN_WIDTH, self.SCREEN_HEIGHT = 1024, 768 self.BG_COLOR_REG = 70,70,70 self.BG_COLOR_REG_2 = 110,110,110 self.BG_COLOR_REG_3 = 40,40,40 self.SUCCESS_COLOR = 70,170,70 self.FAIL_COLOR = 170,70,70 self.INDICATOR_COLOR = 40,60,40 self.INDICATOR_COLOR_2 = 30,100,30 self.GOOD_MSG_COLOR = 160,255,160 self.BAD_MSG_COLOR = 255,160,160 self.A_MSG_COLOR = 160,160,255 self.B_MSG_COLOR = 230,230,160 self.REG_FIXATION_COLOR = 200,200,200 self.GOOD_FIXATION_COLOR = self.SUCCESS_COLOR self.BAD_FIXATION_COLOR = 240,140,140 self.BAD_SCORE_COLOR = 200,100,100 self.GOOD_SCORE_COLOR = 100,200,100 self.HIGHLIGHT_SCORE_COLOR = 20,255,20 self.NORM_SCORE_COLOR = 180,180,100 self.SENSOR_INPUT_OFFSET = np.array([0.5*self.SCREEN_WIDTH, 0.75*self.SCREEN_HEIGHT]) self.BORDER_COLOR_DICT = {'incomplete':(50,0,0), 'ready':(0,0,50), 'complete':(0,50,0), 'disconnected':(50,0,0), 'idle':(50,50,50), 'rai':(0,50,0), 'rfi':(0,50,0), 'loc':(0,50,0), 'nfb':(0,50,0)} self.BG_COLOR_DICT = {'incomplete':(100,0,0), 'ready':(0,0,100), 'complete':(0,100,0), 'disconnected':(100,0,0), 'idle':(100,100,100), 'rai':(0,100,0), 'rfi':(0,100,0), 'loc':(0,100,0), 'nfb':(0,100,0)} # dict entry for current timer set to use self.PRE_REST_TIME = {'trial':0} self.INTRO_TIME = {'trial':0} self.FEEDBACK_TIME = {'trial':0} self.ACTIVE_TIME = {'trial':0} self.TRIALS = {'trial':0} self.TRIAL_TIME = {'trial':0} self.INTRO_TRIGGER_TIME = {'trial':0} self.ACTIVE_TRIGGER_TIME = {'trial':0} self.FEEDBACK_TRIGGER_TIME = {'trial':0} # self-paced times self.PRE_REST_TIME['s_p'] = 3 self.INTRO_TIME['s_p'] = 1 self.FEEDBACK_TIME['s_p'] = 2 self.ACTIVE_TIME['s_p'] = -1 self.TRIALS['s_p'] = 5 self.TRIAL_TIME['s_p'] = (self.PRE_REST_TIME['s_p'] + self.INTRO_TIME['s_p'] + self.FEEDBACK_TIME['s_p']) self.INTRO_TRIGGER_TIME['s_p'] = self.PRE_REST_TIME['s_p'] self.ACTIVE_TRIGGER_TIME['s_p'] = self.PRE_REST_TIME['s_p'] + self.INTRO_TIME['s_p'] self.FEEDBACK_TRIGGER_TIME['s_p'] = -1 self.TRIAL_TYPES = 9 self.trial_type_count = 0 # localizer times # 40 seconds per trial # 480s per run self.PRE_REST_TIME['loc'] = 17 self.INTRO_TIME['loc'] = 1 self.ACTIVE_TIME['loc'] = 20 self.FEEDBACK_TIME['loc'] = 2 self.TRIALS['loc'] = 12 # neurofeedback times # 60 seconds per trial # 480s per run self.PRE_REST_TIME['nfb'] = 27 self.INTRO_TIME['nfb'] = 1 self.ACTIVE_TIME['nfb'] = 30 self.FEEDBACK_TIME['nfb'] = 2 self.TRIALS['nfb'] = 8 self.NFB_INFO_TIME = 0.5 self.NFB_INFO_HEIGHT = 28 self.MVC_TIME = 19 self.INTRO_TRIGGER_TIME['loc'] = self.PRE_REST_TIME['loc'] self.ACTIVE_TRIGGER_TIME['loc'] = self.PRE_REST_TIME['loc'] + self.INTRO_TIME['loc'] self.FEEDBACK_TRIGGER_TIME['loc'] = self.ACTIVE_TRIGGER_TIME['loc'] + self.ACTIVE_TIME['loc'] self.INTRO_TRIGGER_TIME['nfb'] = self.PRE_REST_TIME['nfb'] self.ACTIVE_TRIGGER_TIME['nfb'] = self.PRE_REST_TIME['nfb'] + self.INTRO_TIME['nfb'] self.FEEDBACK_TRIGGER_TIME['nfb'] = self.ACTIVE_TRIGGER_TIME['nfb'] + self.ACTIVE_TIME['nfb'] self.CONTROL_TRIGGER_TIME = 1000*int(0.5*self.INTRO_TRIGGER_TIME['nfb']) self.BASELINE_CALC_SHIFT = self.PRE_REST_TIME['nfb']-10 self.TRIAL_TIME['loc'] = (self.PRE_REST_TIME['loc'] + self.INTRO_TIME['loc'] + self.ACTIVE_TIME['loc'] + self.FEEDBACK_TIME['loc']) self.TRIAL_TIME['nfb'] = (self.PRE_REST_TIME['nfb'] + self.INTRO_TIME['nfb'] + self.ACTIVE_TIME['nfb'] + self.FEEDBACK_TIME['nfb']) ##################### # control variables # ##################### self.TR = 1. self.ADD_CONTROL_TRS = 5 self.TF_CONTROL = self.ACTIVE_TIME['nfb']+self.ADD_CONTROL_TRS self.N_ACTIVE_TIME = self.ACTIVE_TIME['nfb']/self.TR+1 self.N_CONTROL_STEPS = self.TF_CONTROL/self.TR+1 self.CONTROL_MVC_MIN = 0.1 self.CONTROL_MVC_MAX = 0.4 self.u_vec = np.zeros((1,self.N_CONTROL_STEPS)) self.y_vec = np.zeros(self.N_CONTROL_STEPS) gc.set_system(self) ########################## # force sensor variables # ########################## self.MVC_IN_PIXEL = 900 self.MVC_MIN = 0#0.05 self.ANGLE_ADD_DEG = 20 self.ANGLE_ADD = np.deg2rad(self.ANGLE_ADD_DEG) self.ANGLE_MULT = 1+2*self.ANGLE_ADD/np.pi self.set_mvc(MVC['mvc']) self.DAQ_LPF_CUTOFF = 8 self.DAQ_LPF_ORDER = 3 self.CALIBRATE_BOOL = False # False or True if self.CALIBRATE_BOOL: fu.write_cal_header(self) if SENSOR_ACTIVE: if self.CALIBRATE_BOOL: self.daq = Pydaq('Dev3/ai0:2', self.FRAME_RATE, lp_filt_freq=14, lp_filt_order=3, force_params='force_params_cal.txt') else: self.daq = Pydaq('Dev3/ai0:1', self.FRAME_RATE, lp_filt_freq=self.DAQ_LPF_CUTOFF, lp_filt_order=self.DAQ_LPF_ORDER, force_params='force_params_lab.txt') self.scanner_daq = Pydaq('Dev1/ai2:3', self.FRAME_RATE, lp_filt_freq=self.DAQ_LPF_CUTOFF, lp_filt_order=self.DAQ_LPF_ORDER, force_params='force_params_scanner.txt') ######################## # networking variables # ######################## IP = CONFIG['server-ip'] PORT = CONFIG['server-port'] self.SERVER_TARGET = 'http://{ip}:{port}/'.format(ip=IP, port=PORT) self.requests_running_bool = mp.Value('i', 1) self.last_volume_received = mp.Value('i', 0) self.pool = mp.Pool() self.insta_mode = 'disconnected' # idle, rai, rfi, loc, nfb self.roi_name = 'm1_left_a' self.next_run_msg = '' self.insta_complete = OrderedDict() self.insta_complete['roi'] = 'incomplete' self.insta_complete['rai'] = 'incomplete' self.insta_complete['rfi'] = 'incomplete' self.insta_complete['warp2rfi'] = 'incomplete' self.insta_complete['glm'] = 'incomplete' self.insta_complete['loc'] = 'incomplete' self.raw_betas = {'active':0., 'force':0., 'complexity':0., 'constant':0.} self.psc_betas = {'active':0.5, 'force':1.5, 'complexity':1.0} self.MAX_CONTROL = 3 self.MIN_CONTROL = 0.5 self.PSC_TARGET_LIST = [1.5,1.5,1.5,1.5] self.RUN_TYPE_LIST = CONFIG['run-type-list'] self.NFB_TRS = int(self.TRIAL_TIME['nfb'] *self.TRIALS['nfb']/self.TR) self.bold_rois_array = [] self.bold_rois_array.append(mp.Array('d',self.NFB_TRS)) self.REQUEST_WAIT_TIME = 0.1 self.requests_process = mp.Process(target = gn.requests_loop, args = (self.SERVER_TARGET, self.REQUEST_WAIT_TIME, self.requests_running_bool, self.last_volume_received, self.bold_rois_array,)) #################################################### # start pygame and initialize default game objects # #################################################### pygame.init() pygame.mouse.set_visible(not pygame.mouse.set_visible) self.clock = pygame.time.Clock() if CONFIG['fullscreen']: self.screen = pygame.display.set_mode( (self.SCREEN_WIDTH, self.SCREEN_HEIGHT), pygame.FULLSCREEN) else: self.screen = pygame.display.set_mode( (self.SCREEN_WIDTH, self.SCREEN_HEIGHT)) ################################## # initialize custom game objects # ################################## self.CURSOR_RAD = 75 self.FIXATION_WIDTH = 1.5*self.CURSOR_RAD self.FIXATION_HEIGHT = 8 self.cursor = Cursor(self.screen, self.CURSOR_RAD) self.timers = {} self.init_timers() self.TARGET_SUCCESS_TIME = .15 self.TARGET_MIN_TIME = .5 self.TARGET_RAD_MIN = -25 self.TARGET_RAD_MAX = 45 ##################### # target lists here # ##################### # function to generate x length, all same mvc, # all same phase # and do {20s length} x {.1, .2, .4} x {0, 180} self.MVC_LIST = [] self.PHASE_LIST = [] self.MVC_LIST.append(np.array([.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1])) self.MVC_LIST.append(np.array([.2,.2,.2,.2,.2,.2,.2,.2,.2,.2,.2,.2,.2,.2,.2,.2,.2,.2,.2,.2])) self.MVC_LIST.append(np.array([.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4])) self.PHASE_LIST.append(np.array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])) self.PHASE_LIST.append(np.array([180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180])) self.TRAINING_TARGET_LOC_LIST = [] self.loc_target_order = [0,3,1,4,2,5,1,4,0,5,3,2] for mvc in self.MVC_LIST: for phase in self.PHASE_LIST: self.TRAINING_TARGET_LOC_LIST.append(self.gen_target_list(mvc,phase)) self.next_mvc_list = [] self.next_phase_list = [] self.next_target_loc_list = [] # auto-generate 1, 1.5, and 2 psc from dummy data for psc_target in (1.,1.5,2.): new_targets = self.gen_control_targets(psc_target) self.TRAINING_TARGET_LOC_LIST.append(new_targets) self.SAMPLE_MVC_LIST = np.array([.4,.1,.2,.1,.2,.4]) self.SAMPLE_PHASE_LIST = np.array([0,0,0,180,180,180]) self.SAMPLE_TARGET_LOC_LIST = self.gen_target_list(self.SAMPLE_MVC_LIST, self.SAMPLE_PHASE_LIST) self.set_targets(self.SAMPLE_TARGET_LOC_LIST) ###################### # set game variables # ###################### self.screen_mid = np.array([0.5*self.screen.get_width(), 0.5*self.screen.get_height()]) self.bg_color = self.BG_COLOR_REG_3 self.fixation_color = self.REG_FIXATION_COLOR self.input_mode = 'mouse' self.input_pos = np.array([0.0,0.0]) self.input_force = np.array([0.0,0.0]) self.cal_force = 0. self.debug_bool = False self.nfb_info_bool = False self.run_mode = 'idle' # idle, mvc, trials self.run_type = 's_p' self.self_paced_bool = True self.controller_active_bool = False self.controller_calc_bool = False self.nfb_run_count = 0 self.calc_score_bool = False self.trial_time_array = np.array(()) self.set_timer_mode('s_p') self.current_score = 0 self.score_color = self.GOOD_SCORE_COLOR self.score_fixation_status = 'norm' self.max_rec_mvc_both = 0 self.max_rec_mvc_x = 0 self.max_rec_mvc_y = 0 self.MVC_DISPLAY_CEIL = 100.
class PngScraperFrame(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) self.createMenu() #self.pngs = ['c:/temp/mibook.png'] self.pngs = GetPngList(PNGDIR) self.cursor = Cursor(ListView(self.pngs)) box = wx.BoxSizer(wx.VERTICAL) # next button row = wx.BoxSizer(wx.HORIZONTAL) def CursorButton(label): b = wx.Button(self, label= label) b.Bind(wx.EVT_BUTTON, self.OnCursorButton) return b row.Add(CursorButton("<<")) row.Add(CursorButton("<")) self.which = wx.TextCtrl(self, -1, '') self.updateWhich() row.Add(self.which) row.Add(CursorButton(">")) row.Add(CursorButton(">>")) # coords box self.coords = wx.TextCtrl(self, -1, '(0,0)') row.Add(self.coords, 0, wx.ALIGN_RIGHT) row.Add((20,20),1) # color box self.color = wx.TextCtrl(self, -1, '0x000000') row.Add(self.color, 0, wx.ALIGN_RIGHT) row.Add((20,20),1) box.Add(row, 0, wx.ALIGN_CENTER_HORIZONTAL) # the image pane = wx.ScrolledWindow(self, -1, size=(300,400)) box.Add(pane, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALL|wx.ADJUST_MINSIZE) self.image = wx.StaticBitmap(pane, bitmap=wx.EmptyBitmap(800, 600)) self.image.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) self.image.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown) self.updateImage() # the shell self.locals = {'self':self, 'wx':wx, 'hook': lambda:None, 'gc':self.getGC() } self.shell = py.shell.Shell(self, locals=self.locals) self.shell.SetMinSize((500,400)) box.Add(self.shell, 4, wx.EXPAND) self.shell.SetFocus() self.SetSizerAndFit(box) wx.EVT_CLOSE(self, self.OnCloseWindow) def createMenu(self): # Setting up the menu. filemenu= wx.Menu() filemenu.Append(ID_OPEN_FILE, "&Open File", "OpenFile") filemenu.Append(ID_OPEN_DIR, "Open &Directory", "OpenDir") filemenu.AppendSeparator() filemenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program") # Creating the menubar. menuBar = wx.MenuBar() menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content. wx.EVT_MENU(self, wx.ID_EXIT, self.OnExit) wx.EVT_MENU(self, ID_OPEN_FILE, self.OnOpenFile) wx.EVT_MENU(self, ID_OPEN_DIR, self.OnOpenDir) def OnCursorButton(self, evt): buttonMap = { "<<":"moveToStart", "<" :"movePrevious", ">" :"moveNext", ">>":"moveToEnd", } try: getattr(self.cursor, buttonMap[evt.GetEventObject().Label])() self.updateWhich() self.updateImage() self.shell.run('hook()') except StopIteration: pass def OnOpenFile(self, event): dlg = wx.FileDialog( self, message="Choose a file", defaultDir=os.getcwd(), defaultFile="", wildcard='*.png', style=wx.OPEN | wx.CHANGE_DIR) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() self.pngs.insert(self.cursor.position,path) self.updateWhich() self.updateImage() def OnOpenDir(self, event): dlg = wx.DirDialog(self, "Choose a directory:", defaultPath=os.getcwd(), style=wx.DD_DEFAULT_STYLE|wx.DD_NEW_DIR_BUTTON) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() while self.pngs: self.pngs.pop() self.pngs.extend(GetPngList(path)) self.cursor.moveToStart() self.updateWhich() self.updateImage() self.shell.run('hook()') def OnExit(self, evt): self.Close() def updateWhich(self): self.which.Value = "%s/%s" % (self.cursor.position, len(self.pngs)) def updateImage(self): # set the visible bitmap img = wx.Image(self.pngs[self.cursor.position], wx.BITMAP_TYPE_PNG) self.image.SetBitmap(wx.BitmapFromImage(img)) self.Fit() # and make the pil image self.im = im = Image.new('RGB', (self.image.Size)) self.im.fromstring(wx.ImageFromBitmap(self.image.GetBitmap()).GetData()) def OnRightDown(self, e): self.image.Refresh() def OnLeftDown(self, e): point = (e.X, e.Y) self.coords.Value = "(%s,%s)" % point self.color.Value = "0x%s" % "".join(hex(v)[2:].upper() for v in self.im.getpixel(point)) # draw crosshairs: dc = wx.ClientDC(self.image) dc.SetPen(wx.Pen("RED")) dc.DrawLine(e.X-2, e.Y, e.X, e.Y) dc.DrawLine(e.X, e.Y-2, e.X, e.Y) dc.DrawLine(e.X+2, e.Y, e.X, e.Y) dc.DrawLine(e.X, e.Y+2, e.X, e.Y) def getGC(self): gc = wx.GCDC(wx.ClientDC(self.image)) ink = wx.Color(0x99, 0xcc, 0xff, 0x88) gc.SetPen(wx.Pen(ink)) gc.SetBrush(wx.Brush(ink)) return gc # @TODO: re-enable drawWords. it was cool. :) # def drawWords(self): # chars = self.chars() # inks = wx.Color(0x99, 0xcc, 0xff, 0x88) , wx.Color(0x99, 0xff, 0xcc, 0x88) # # gc = self.getGC() # # i = 0 # for c in chars: # if c[4] not in ('', ' '): # # ink = inks[i % 2] # i += 1 # # gc.SetPen(wx.Pen(ink)) # gc.SetBrush(wx.Brush(ink)) # # gc.DrawRectangle(*c[:4]) # def drawFirstUnkowns(self, cutoff=200, mode='L'): # "I *THINK* this was to show a new char to learn in context." # chars = self.chars(mode, cutoff) # # seen = {} # # gc = self.getGC() # ink = wx.Color(0xff, 0x00, 0x00, 0x88) # gc.SetPen(wx.Pen(ink)) # gc.SetBrush(wx.Brush(ink)) # # i = 0 # for c in chars: # if type(c[4]) in (int,long): # if c[4] not in seen: # gc.DrawRectangle(*c[:4]) # seen[c[4]]=True # def chars(self, mode='L', cutoff=200): # return list(scrape.letters(self.im.convert(mode), cutoff)) def drawBaseLines(self, baseline_color='#99CCFF', linegap_color='#eeeeee'): img_out = self.im dc = self.getGC() y = 0 w, h = img_out.size for (top, base, bottom) in scrape.guess_lines(img_out): # draw the baseline dc.SetPen(wx.Pen(baseline_color)) if not base: base = bottom -2 dc.SetPen(wx.RED_PEN) dc.DrawLines([(0,base),(w,base)]) # shade out the other stuff dc.SetPen(wx.Pen(linegap_color)) dc.SetBrush(wx.Brush(linegap_color)) dc.DrawRectangle(0,y,w,top-y) y = bottom # shade bottom area dc.DrawRectangle(0,y,w,h-y) def OnCloseWindow(self, event): self.Destroy()
class Game(object): def __init__(self): ############### # load config # ############### with open('config.yaml') as f: CONFIG = yaml.load(f) with open('mvc.yaml') as f: MVC = yaml.load(f) self.subj_id = CONFIG['subject-id'] self.subj_dir = 'datasets/' + self.subj_id self.loc = CONFIG['location'] ################# # set constants # ################# if self.loc == 'lab': self.FRAME_RATE = 120 elif self.loc == 'scanner': self.FRAME_RATE = 60 self.SCREEN_WIDTH, self.SCREEN_HEIGHT = 1024, 768 self.BG_COLOR_REG = 70,70,70 self.BG_COLOR_REG_2 = 110,110,110 self.BG_COLOR_REG_3 = 40,40,40 self.SUCCESS_COLOR = 70,170,70 self.FAIL_COLOR = 170,70,70 self.INDICATOR_COLOR = 40,60,40 self.INDICATOR_COLOR_2 = 30,100,30 self.GOOD_MSG_COLOR = 160,255,160 self.BAD_MSG_COLOR = 255,160,160 self.A_MSG_COLOR = 160,160,255 self.B_MSG_COLOR = 230,230,160 self.REG_FIXATION_COLOR = 200,200,200 self.GOOD_FIXATION_COLOR = self.SUCCESS_COLOR self.BAD_FIXATION_COLOR = 240,140,140 self.BAD_SCORE_COLOR = 200,100,100 self.GOOD_SCORE_COLOR = 100,200,100 self.HIGHLIGHT_SCORE_COLOR = 20,255,20 self.NORM_SCORE_COLOR = 180,180,100 self.SENSOR_INPUT_OFFSET = np.array([0.5*self.SCREEN_WIDTH, 0.75*self.SCREEN_HEIGHT]) self.BORDER_COLOR_DICT = {'incomplete':(50,0,0), 'ready':(0,0,50), 'complete':(0,50,0), 'disconnected':(50,0,0), 'idle':(50,50,50), 'rai':(0,50,0), 'rfi':(0,50,0), 'loc':(0,50,0), 'nfb':(0,50,0)} self.BG_COLOR_DICT = {'incomplete':(100,0,0), 'ready':(0,0,100), 'complete':(0,100,0), 'disconnected':(100,0,0), 'idle':(100,100,100), 'rai':(0,100,0), 'rfi':(0,100,0), 'loc':(0,100,0), 'nfb':(0,100,0)} # dict entry for current timer set to use self.PRE_REST_TIME = {'trial':0} self.INTRO_TIME = {'trial':0} self.FEEDBACK_TIME = {'trial':0} self.ACTIVE_TIME = {'trial':0} self.TRIALS = {'trial':0} self.TRIAL_TIME = {'trial':0} self.INTRO_TRIGGER_TIME = {'trial':0} self.ACTIVE_TRIGGER_TIME = {'trial':0} self.FEEDBACK_TRIGGER_TIME = {'trial':0} # self-paced times self.PRE_REST_TIME['s_p'] = 3 self.INTRO_TIME['s_p'] = 1 self.FEEDBACK_TIME['s_p'] = 2 self.ACTIVE_TIME['s_p'] = -1 self.TRIALS['s_p'] = 5 self.TRIAL_TIME['s_p'] = (self.PRE_REST_TIME['s_p'] + self.INTRO_TIME['s_p'] + self.FEEDBACK_TIME['s_p']) self.INTRO_TRIGGER_TIME['s_p'] = self.PRE_REST_TIME['s_p'] self.ACTIVE_TRIGGER_TIME['s_p'] = self.PRE_REST_TIME['s_p'] + self.INTRO_TIME['s_p'] self.FEEDBACK_TRIGGER_TIME['s_p'] = -1 self.TRIAL_TYPES = 9 self.trial_type_count = 0 # localizer times # 40 seconds per trial # 480s per run self.PRE_REST_TIME['loc'] = 17 self.INTRO_TIME['loc'] = 1 self.ACTIVE_TIME['loc'] = 20 self.FEEDBACK_TIME['loc'] = 2 self.TRIALS['loc'] = 12 # neurofeedback times # 60 seconds per trial # 480s per run self.PRE_REST_TIME['nfb'] = 27 self.INTRO_TIME['nfb'] = 1 self.ACTIVE_TIME['nfb'] = 30 self.FEEDBACK_TIME['nfb'] = 2 self.TRIALS['nfb'] = 8 self.NFB_INFO_TIME = 0.5 self.NFB_INFO_HEIGHT = 28 self.MVC_TIME = 19 self.INTRO_TRIGGER_TIME['loc'] = self.PRE_REST_TIME['loc'] self.ACTIVE_TRIGGER_TIME['loc'] = self.PRE_REST_TIME['loc'] + self.INTRO_TIME['loc'] self.FEEDBACK_TRIGGER_TIME['loc'] = self.ACTIVE_TRIGGER_TIME['loc'] + self.ACTIVE_TIME['loc'] self.INTRO_TRIGGER_TIME['nfb'] = self.PRE_REST_TIME['nfb'] self.ACTIVE_TRIGGER_TIME['nfb'] = self.PRE_REST_TIME['nfb'] + self.INTRO_TIME['nfb'] self.FEEDBACK_TRIGGER_TIME['nfb'] = self.ACTIVE_TRIGGER_TIME['nfb'] + self.ACTIVE_TIME['nfb'] self.CONTROL_TRIGGER_TIME = 1000*int(0.5*self.INTRO_TRIGGER_TIME['nfb']) self.BASELINE_CALC_SHIFT = self.PRE_REST_TIME['nfb']-10 self.TRIAL_TIME['loc'] = (self.PRE_REST_TIME['loc'] + self.INTRO_TIME['loc'] + self.ACTIVE_TIME['loc'] + self.FEEDBACK_TIME['loc']) self.TRIAL_TIME['nfb'] = (self.PRE_REST_TIME['nfb'] + self.INTRO_TIME['nfb'] + self.ACTIVE_TIME['nfb'] + self.FEEDBACK_TIME['nfb']) ##################### # control variables # ##################### self.TR = 1. self.ADD_CONTROL_TRS = 5 self.TF_CONTROL = self.ACTIVE_TIME['nfb']+self.ADD_CONTROL_TRS self.N_ACTIVE_TIME = self.ACTIVE_TIME['nfb']/self.TR+1 self.N_CONTROL_STEPS = self.TF_CONTROL/self.TR+1 self.CONTROL_MVC_MIN = 0.1 self.CONTROL_MVC_MAX = 0.4 self.u_vec = np.zeros((1,self.N_CONTROL_STEPS)) self.y_vec = np.zeros(self.N_CONTROL_STEPS) gc.set_system(self) ########################## # force sensor variables # ########################## self.MVC_IN_PIXEL = 900 self.MVC_MIN = 0#0.05 self.ANGLE_ADD_DEG = 20 self.ANGLE_ADD = np.deg2rad(self.ANGLE_ADD_DEG) self.ANGLE_MULT = 1+2*self.ANGLE_ADD/np.pi self.set_mvc(MVC['mvc']) self.DAQ_LPF_CUTOFF = 8 self.DAQ_LPF_ORDER = 3 self.CALIBRATE_BOOL = False # False or True if self.CALIBRATE_BOOL: fu.write_cal_header(self) if SENSOR_ACTIVE: if self.CALIBRATE_BOOL: self.daq = Pydaq('Dev3/ai0:2', self.FRAME_RATE, lp_filt_freq=14, lp_filt_order=3, force_params='force_params_cal.txt') else: self.daq = Pydaq('Dev3/ai0:1', self.FRAME_RATE, lp_filt_freq=self.DAQ_LPF_CUTOFF, lp_filt_order=self.DAQ_LPF_ORDER, force_params='force_params_lab.txt') self.scanner_daq = Pydaq('Dev1/ai2:3', self.FRAME_RATE, lp_filt_freq=self.DAQ_LPF_CUTOFF, lp_filt_order=self.DAQ_LPF_ORDER, force_params='force_params_scanner.txt') ######################## # networking variables # ######################## IP = CONFIG['server-ip'] PORT = CONFIG['server-port'] self.SERVER_TARGET = 'http://{ip}:{port}/'.format(ip=IP, port=PORT) self.requests_running_bool = mp.Value('i', 1) self.last_volume_received = mp.Value('i', 0) self.pool = mp.Pool() self.insta_mode = 'disconnected' # idle, rai, rfi, loc, nfb self.roi_name = 'm1_left_a' self.next_run_msg = '' self.insta_complete = OrderedDict() self.insta_complete['roi'] = 'incomplete' self.insta_complete['rai'] = 'incomplete' self.insta_complete['rfi'] = 'incomplete' self.insta_complete['warp2rfi'] = 'incomplete' self.insta_complete['glm'] = 'incomplete' self.insta_complete['loc'] = 'incomplete' self.raw_betas = {'active':0., 'force':0., 'complexity':0., 'constant':0.} self.psc_betas = {'active':0.5, 'force':1.5, 'complexity':1.0} self.MAX_CONTROL = 3 self.MIN_CONTROL = 0.5 self.PSC_TARGET_LIST = [1.5,1.5,1.5,1.5] self.RUN_TYPE_LIST = CONFIG['run-type-list'] self.NFB_TRS = int(self.TRIAL_TIME['nfb'] *self.TRIALS['nfb']/self.TR) self.bold_rois_array = [] self.bold_rois_array.append(mp.Array('d',self.NFB_TRS)) self.REQUEST_WAIT_TIME = 0.1 self.requests_process = mp.Process(target = gn.requests_loop, args = (self.SERVER_TARGET, self.REQUEST_WAIT_TIME, self.requests_running_bool, self.last_volume_received, self.bold_rois_array,)) #################################################### # start pygame and initialize default game objects # #################################################### pygame.init() pygame.mouse.set_visible(not pygame.mouse.set_visible) self.clock = pygame.time.Clock() if CONFIG['fullscreen']: self.screen = pygame.display.set_mode( (self.SCREEN_WIDTH, self.SCREEN_HEIGHT), pygame.FULLSCREEN) else: self.screen = pygame.display.set_mode( (self.SCREEN_WIDTH, self.SCREEN_HEIGHT)) ################################## # initialize custom game objects # ################################## self.CURSOR_RAD = 75 self.FIXATION_WIDTH = 1.5*self.CURSOR_RAD self.FIXATION_HEIGHT = 8 self.cursor = Cursor(self.screen, self.CURSOR_RAD) self.timers = {} self.init_timers() self.TARGET_SUCCESS_TIME = .15 self.TARGET_MIN_TIME = .5 self.TARGET_RAD_MIN = -25 self.TARGET_RAD_MAX = 45 ##################### # target lists here # ##################### # function to generate x length, all same mvc, # all same phase # and do {20s length} x {.1, .2, .4} x {0, 180} self.MVC_LIST = [] self.PHASE_LIST = [] self.MVC_LIST.append(np.array([.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1])) self.MVC_LIST.append(np.array([.2,.2,.2,.2,.2,.2,.2,.2,.2,.2,.2,.2,.2,.2,.2,.2,.2,.2,.2,.2])) self.MVC_LIST.append(np.array([.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4])) self.PHASE_LIST.append(np.array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])) self.PHASE_LIST.append(np.array([180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180])) self.TRAINING_TARGET_LOC_LIST = [] self.loc_target_order = [0,3,1,4,2,5,1,4,0,5,3,2] for mvc in self.MVC_LIST: for phase in self.PHASE_LIST: self.TRAINING_TARGET_LOC_LIST.append(self.gen_target_list(mvc,phase)) self.next_mvc_list = [] self.next_phase_list = [] self.next_target_loc_list = [] # auto-generate 1, 1.5, and 2 psc from dummy data for psc_target in (1.,1.5,2.): new_targets = self.gen_control_targets(psc_target) self.TRAINING_TARGET_LOC_LIST.append(new_targets) self.SAMPLE_MVC_LIST = np.array([.4,.1,.2,.1,.2,.4]) self.SAMPLE_PHASE_LIST = np.array([0,0,0,180,180,180]) self.SAMPLE_TARGET_LOC_LIST = self.gen_target_list(self.SAMPLE_MVC_LIST, self.SAMPLE_PHASE_LIST) self.set_targets(self.SAMPLE_TARGET_LOC_LIST) ###################### # set game variables # ###################### self.screen_mid = np.array([0.5*self.screen.get_width(), 0.5*self.screen.get_height()]) self.bg_color = self.BG_COLOR_REG_3 self.fixation_color = self.REG_FIXATION_COLOR self.input_mode = 'mouse' self.input_pos = np.array([0.0,0.0]) self.input_force = np.array([0.0,0.0]) self.cal_force = 0. self.debug_bool = False self.nfb_info_bool = False self.run_mode = 'idle' # idle, mvc, trials self.run_type = 's_p' self.self_paced_bool = True self.controller_active_bool = False self.controller_calc_bool = False self.nfb_run_count = 0 self.calc_score_bool = False self.trial_time_array = np.array(()) self.set_timer_mode('s_p') self.current_score = 0 self.score_color = self.GOOD_SCORE_COLOR self.score_fixation_status = 'norm' self.max_rec_mvc_both = 0 self.max_rec_mvc_x = 0 self.max_rec_mvc_y = 0 self.MVC_DISPLAY_CEIL = 100. def gen_target_list(self, mvc_list, phase_list): mvc_list = np.ravel(mvc_list) phase_list = np.ravel(phase_list) target_list = np.zeros((2,2*len(mvc_list))) for idx in range(len(mvc_list)): if phase_list[idx] == 0: target_list[0][2*idx] = 0 target_list[1][2*idx] = -self.MVC_IN_PIXEL*mvc_list[idx] target_list[0][2*idx+1] = 0 target_list[1][2*idx+1] = -self.MVC_IN_PIXEL*self.MVC_MIN elif phase_list[idx] == 180: target_list[0][2*idx] = self.MVC_IN_PIXEL*mvc_list[idx] target_list[1][2*idx] = -self.MVC_IN_PIXEL*self.MVC_MIN target_list[0][2*idx+1] = -self.MVC_IN_PIXEL*mvc_list[idx] target_list[1][2*idx+1] = -self.MVC_IN_PIXEL*self.MVC_MIN return np.transpose(target_list) def set_mvc(self, mvc): self.newtons_2_pixel_both = self.MVC_IN_PIXEL/(.5*mvc['both']) self.newtons_2_pixel_x = self.MVC_IN_PIXEL/(mvc['x']) self.newtons_2_pixel_y = self.MVC_IN_PIXEL/(mvc['y']) def set_targets(self, target_list): self.targets = [] # set targets for target_loc in target_list: target_rad = (self.TARGET_RAD_MAX - (self.TARGET_RAD_MAX - self.TARGET_RAD_MIN) * np.sqrt(target_loc[0]**2 + target_loc[1]**2) /float(self.MVC_IN_PIXEL)) self.targets.append(Target(self.screen, target_loc, self.SENSOR_INPUT_OFFSET, target_rad, self.CURSOR_RAD, self.TARGET_SUCCESS_TIME, self.TARGET_MIN_TIME)) # link targets self.current_target = self.targets[0] self.targets[0].prev_target = None self.targets[-1].next_target = None for idx in range(len(self.targets)-1): self.targets[idx].next_target = self.targets[idx+1] self.targets[idx+1].prev_target = self.targets[idx] def get_pos(self): if self.input_mode=='mouse' or not(SENSOR_ACTIVE): return pygame.mouse.get_pos() else: if self.loc == 'lab': f_in_x, f_in_y = self.daq.get_force() elif self.loc == 'scanner': f_in_x, f_in_y = self.scanner_daq.get_force() self.input_force = f_in_x, f_in_y f_mag = max(f_in_x, f_in_y) f_ang = np.arctan2(f_in_x, f_in_y) f_out_x = f_mag*np.cos(2*self.ANGLE_MULT*f_ang-self.ANGLE_ADD) f_out_y = f_mag*np.sin(2*self.ANGLE_MULT*f_ang-self.ANGLE_ADD) ang_blend = (f_ang-.25*np.pi)/(.25*np.pi) ang_blend_both = (max(0,(1-abs(ang_blend))) *self.newtons_2_pixel_both) if ang_blend < 0: ang_blend_side = abs(ang_blend)*self.newtons_2_pixel_y else: ang_blend_side = abs(ang_blend)*self.newtons_2_pixel_x newtons_2_pixel = ang_blend_both + ang_blend_side pos_x = (self.SENSOR_INPUT_OFFSET[0] +newtons_2_pixel*f_out_x) pos_y = (self.SENSOR_INPUT_OFFSET[1] -newtons_2_pixel*f_out_y) return (pos_x, pos_y) def init_timers(self): self.timers['loc'] = Timer(self.TRIAL_TIME['loc'], self.TRIALS['loc']) self.timers['nfb'] = Timer(self.TRIAL_TIME['nfb'], self.TRIALS['nfb']) self.timers['s_p'] = Timer(self.TRIAL_TIME['s_p'], self.TRIALS['s_p']) self.timers['trial'] = self.timers['loc'] self.timers['move'] = Timer(sys.maxint) self.timers['mvc'] = Timer(self.MVC_TIME) self.timers['nfb_info'] = Timer(self.NFB_INFO_TIME) def set_timer_mode(self, mode): self.timers['trial'] = self.timers[mode] self.PRE_REST_TIME['trial'] = self.PRE_REST_TIME[mode]*1000 self.INTRO_TIME['trial'] = self.INTRO_TIME[mode]*1000 self.FEEDBACK_TIME['trial'] = self.FEEDBACK_TIME[mode]*1000 self.ACTIVE_TIME['trial'] = self.ACTIVE_TIME[mode]*1000 self.TRIALS['trial'] = self.TRIALS[mode]*1000 self.TRIAL_TIME['trial'] = self.TRIAL_TIME[mode]*1000 self.INTRO_TRIGGER_TIME['trial'] = self.INTRO_TRIGGER_TIME[mode]*1000 self.ACTIVE_TRIGGER_TIME['trial'] = self.ACTIVE_TRIGGER_TIME[mode]*1000 self.FEEDBACK_TRIGGER_TIME['trial'] = self.FEEDBACK_TRIGGER_TIME[mode]*1000 def reset_all_timers(self): for k,t in self.timers.iteritems(): t.reset() def check_input(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.quit() elif event.key == pygame.K_0: if self.loc == 'lab': self.daq.set_volts_zero() elif self.loc == 'scanner': self.scanner_daq.set_volts_zero() elif event.key == pygame.K_m: if self.input_mode == 'mouse': self.input_mode = 'sensor' elif self.input_mode == 'sensor': self.input_mode = 'mouse' elif event.key == pygame.K_d: self.debug_bool = not self.debug_bool elif event.key == pygame.K_s: self.nfb_info_bool = not self.nfb_info_bool elif event.key == pygame.K_SPACE: self.run_type = 's_p' gr.reset_for_next_run(self) self.run_mode = 'trials' elif event.key == pygame.K_7: self.run_mode = 'mvc' elif event.key == pygame.K_8: gn.set_mode('loc', self.SERVER_TARGET) self.run_type = 'loc' self.next_run_msg = 'Ready for Localizer' elif event.key == pygame.K_9: gn.set_mode('nfb', self.SERVER_TARGET) self.run_type = 'nfb' self.next_run_msg = ('Ready for Run ' + str(game.nfb_run_count + 1) + ' of 4') elif event.key == pygame.K_5: if ((self.run_type == 'loc' or self.run_type == 'nfb') and self.run_mode == 'idle'): self.run_mode = 'trials' self.next_run_msg = '' gr.reset_for_next_run(self) # control of insta_server elif event.key == pygame.K_g: gn.set_mode('idle', self.SERVER_TARGET) elif event.key == pygame.K_h: gn.set_mode('rai', self.SERVER_TARGET) elif event.key == pygame.K_j: gn.set_mode('rfi', self.SERVER_TARGET) elif event.key == pygame.K_k: gn.set_mode('loc', self.SERVER_TARGET) elif event.key == pygame.K_l: gn.set_mode('nfb', self.SERVER_TARGET) # testing controls # elif event.key == pygame.K_z: # # figure out when/where to calculate this (add trigger) # # need baseline calculation # # and y_vec calculation # psc_target = 2. # # self.pool.apply_async(func = gc.calc_control, # # args = (self, # # psc_target, # # self.u_vec, # # self.y_vec), # # callback = self.update_control_targets) # u_vec = gc.calc_control(self, # psc_target, # self.u_vec, # self.y_vec) # self.update_control_targets(u_vec) def run(self): fu.write_trial_s_p_header(self) fu.write_control_file(self) fu.write_all_headers_timed(self) self.requests_process.start() while True: time_passed = self.clock.tick_busy_loop(self.FRAME_RATE) self.check_input() self.input_pos = self.get_pos() self.cursor.update(self.input_pos) if self.current_target != None: self.cursor.update_warn(time_passed, not(self.current_target.success)) else: self.cursor.update_warn(time_passed, False) self.draw_background() if self.run_mode == 'trials': gr.frame_based_updates(game, time_passed) if self.debug_bool: self.draw_debug(time_passed) if self.nfb_info_bool: self.draw_nfb_info(time_passed) if self.run_mode == 'mvc': gr.run_mvc(self, time_passed) else: self.cursor.draw() pygame.display.flip() def draw_targets(self): current_bool = self.current_target != None if current_bool: next_bool = self.current_target.next_target != None else: next_bool = False if next_bool: next_next_bool = self.current_target.next_target.next_target != None else: next_next_bool = False if next_next_bool: self.current_target.next_target.next_target.draw(draw_type='next_next') if next_bool: self.current_target.next_target.draw(draw_type='next') if current_bool: self.current_target.draw(draw_type='current') def draw_debug(self, time_passed): fr = 1000/float(time_passed) fr_msg = 'frame rate: ' + str(fr) x_v_msg = 'x force: ' + str(self.input_force[0]) y_v_msg = 'y force: ' + str(self.input_force[1]) betas_active_msg = 'active beta: ' + str(self.psc_betas['active']) betas_force_msg = 'force beta: ' + str(self.psc_betas['force']) betas_complexity_msg = 'complexity beta: ' + str(self.psc_betas['complexity']) lvr_msg = 'last vol: ' + str(self.last_volume_received.value) gg.draw_msg(self.screen, fr_msg, loc='left', pos=(10,33), size=28) gg.draw_msg(self.screen, x_v_msg, loc='left', pos=(10,66), size=28) gg.draw_msg(self.screen, y_v_msg, loc='left', pos=(10,99), size=28) gg.draw_msg(self.screen, betas_active_msg, loc='left', pos=(10,132), size=28) gg.draw_msg(self.screen, betas_force_msg, loc='left', pos=(10,165), size=28) gg.draw_msg(self.screen, betas_complexity_msg, loc='left', pos=(10,198), size=28) gg.draw_msg(self.screen, lvr_msg, loc='left', pos=(10,231), size=28) if self.CALIBRATE_BOOL: self.cal_force = self.daq.force_transform_cal( self.daq.get_volts_cal()) z_v_msg = 'z lbs: ' + str(self.cal_force) gg.draw_msg(self.screen, z_v_msg, loc='left', pos=(10,231), size=28) fu.cal_record(self, self.f_cal) def draw_nfb_info(self, time_passed): self.timers['nfb_info'].update(time_passed) if self.timers['nfb_info'].time_limit_hit: self.pool.apply_async(func = gn.get_complete, args = (self.SERVER_TARGET, self.insta_complete), callback = self.update_complete) self.pool.apply_async(func = gn.get_mode, args = (self.SERVER_TARGET,), callback = self.update_mode) self.pool.apply_async(func = gn.get_betas, args = (self.SERVER_TARGET, self.roi_name, self.raw_betas), callback = self.update_betas) self.timers['nfb_info'].time_limit_hit = False self.timers['nfb_info'].count = 0 # show insta_mode and insta_complete list_count = 0 for k,v in self.insta_complete.iteritems(): gg.draw_info_rect(self.screen, k + ': ' + v, (255,255,255),self.BORDER_COLOR_DICT[v], self.BG_COLOR_DICT[v],350, self.NFB_INFO_HEIGHT,200, 50 + list_count*(8+self.NFB_INFO_HEIGHT)) list_count += 1 gg.draw_info_rect(self.screen, 'mode: ' + self.insta_mode, (255,255,255),self.BORDER_COLOR_DICT[self.insta_mode], self.BG_COLOR_DICT[self.insta_mode],350, self.NFB_INFO_HEIGHT,200, 65 + list_count*(8+self.NFB_INFO_HEIGHT), border_size=12) def update_complete(self, insta_complete): self.insta_complete = insta_complete def update_betas(self, raw_betas): self.raw_betas = raw_betas if self.raw_betas['constant'] != 0: for k,v in self.psc_betas.iteritems(): self.psc_betas[k] = 100*self.raw_betas[k]/self.raw_betas['constant'] gc.set_control_limits(self, self.psc_betas) def update_control_targets(self, u_vec): self.u_vec = self.u_vec + u_vec u_vec_reduced = np.ravel(self.u_vec) u_vec_reduced = u_vec_reduced[0:self.N_ACTIVE_TIME] self.next_mvc_list, self.next_phase_list = gc.betas_to_mvc_phase(self, self.psc_betas, u_vec_reduced) self.next_target_loc_list = self.gen_target_list(self.next_mvc_list, self.next_phase_list) self.set_targets(self.next_target_loc_list) def calc_y_psc(self): trial_num = self.timers['trial'].count-1 begin_rest_idx = trial_num*self.TRIAL_TIME['nfb'] + self.BASELINE_CALC_SHIFT end_rest_idx = begin_rest_idx + self.PRE_REST_TIME['nfb'] - self.BASELINE_CALC_SHIFT + self.INTRO_TIME['nfb'] begin_move_idx = end_rest_idx end_move_idx = begin_move_idx + self.ACTIVE_TIME['nfb'] + 1 rest_mean = 10e-9+np.mean(self.bold_rois_array[0][begin_rest_idx:end_rest_idx]) y_vec_psc = (100*(self.bold_rois_array[0][begin_move_idx:end_move_idx]-rest_mean) /rest_mean) self.y_vec[0:self.N_ACTIVE_TIME] = y_vec_psc[0:self.N_ACTIVE_TIME] self.y_vec[self.N_ACTIVE_TIME:] = np.mean(y_vec_psc[self.N_ACTIVE_TIME - self.ADD_CONTROL_TRS :self.N_ACTIVE_TIME]) def gen_control_targets(self, psc_target): u_vec = gc.calc_control(self, psc_target) u_vec_reduced = u_vec[0:self.N_ACTIVE_TIME] mvc_list, phase_list = gc.betas_to_mvc_phase(self, self.psc_betas, u_vec_reduced) return self.gen_target_list(mvc_list, phase_list) def update_mode(self, mode): self.insta_mode = mode def increment_target(self): self.current_target = self.current_target.next_target def draw_background(self): self.screen.fill(self.bg_color) if self.run_mode == 'idle' and self.loc == 'lab': instr_msg = ('Press Space for Run ' + str(self.trial_type_count+1) + ' of ' + str(self.TRIAL_TYPES)) gg.draw_msg(self.screen, instr_msg, loc='center', pos=(.5*self.SCREEN_WIDTH, .5*self.SCREEN_HEIGHT), size=48) if self.next_run_msg != '': gg.draw_msg(self.screen, self.next_run_msg, loc='center', pos=(.5*self.SCREEN_WIDTH, .4*self.SCREEN_HEIGHT), size=48) def quit(self): self.requests_running_bool.value = 0 self.requests_process.join() sys.exit()
class Logger(object): # TODO: check screen height before log messages debuggable = False debug_messages_queue = Queue.Queue() temp_backup_queue = Queue.Queue() info_message_array = [] TPL_DEBUG_MESSAGE = '[DEBUG] {}' def __init__(self, debuggable=False, interval=0.1, unit="s"): self.debuggable = debuggable self.interval = interval self.unit = unit if not is_windows_system(): from cursor import Cursor from terminal import Terminal self.cursor = Cursor(Terminal()) self.sorted_tasks = [] self.tpl_running_task = '[+][{}] {} in {}{}\n' self.tpl_waiting_task = '[+][{}] {}\n' self.tpl_finished_task = '[-][{}] {} in {}{}\n' # self.tpl_faied_task = '[-]{}:{} in {}{}\n' logging.basicConfig(level=logging.DEBUG) def set_sorted_tasks(self, sorted_tasks): self.sorted_tasks = sorted_tasks def draw(self): # if len(self.sorted_tasks) > 0: self.cursor.restore() self._draw() self.cursor.flush() def clear_space(self): self.cursor.restore() self.cursor.clear_lines(self._calculate_lines_num()) self.cursor.save() def update(self): self.clear_space() self.draw() def reset(self): if not self.debuggable: self.clear_space() self.sorted_tasks = [] Logger.info_message_array = [] @staticmethod def info(message): Logger.info_message_array.append(message) @staticmethod def debug(message): Logger.debug_messages_queue.put(message) Logger.temp_backup_queue.put(message) @staticmethod def warn(message): pass @staticmethod def error(message): pass @staticmethod def print_debug_message(message): if isinstance(message, dict) or isinstance(message, list): print_json(message) else: print(Logger.TPL_DEBUG_MESSAGE.format(message)) @staticmethod def flush_debug_messages(): while not Logger.debug_messages_queue.empty(): message = Logger.debug_messages_queue.get() Logger.print_debug_message(message) @staticmethod def write_error_log(exception=None, extra=None): import json try: log_path = get_error_log_path() with open(log_path, 'w') as fp: while not Logger.temp_backup_queue.empty(): message = Logger.temp_backup_queue.get(timeout=0.5) if isinstance(message, dict) or isinstance(message, list): fp.write(json.dumps(message, indent=4, separators=(',', ': '))) else: fp.write(message) fp.write('\n') # write extra info if exception: fp.write(exception) return log_path except Exception as e: print(traceback.format_exc()) print(e.message) return None def _calculate_lines_num(self): lines_count = 0 for task in self.sorted_tasks: if task.can_show_log: lines_count += 1 return lines_count + len(Logger.info_message_array) + 1 def _draw(self): # map(lambda task: self.cursor.write(self._get_formatted_message(task)), self.sorted_tasks) map(lambda message: self.cursor.write(message + '\n'), Logger.info_message_array) map(lambda task: self.cursor.write(self._get_formatted_message(task)), filter(lambda task: task.can_show_log(), self.sorted_tasks)) def _get_formatted_message(self, task): return { FAILURE: self.tpl_finished_task.format(task.name, 'failed.', task.cost_time, self.unit), READY: self.tpl_running_task.format(task.name, 'not start.', 'N/A', self.unit), WAITING: self.tpl_waiting_task.format(task.name, 'waiting...'), WORKING: self.tpl_running_task.format(task.name, task.running_message, round(time.time() - task.run_start_time, 1), self.unit), SUCCESS: self.tpl_finished_task.format(task.name, task.finished_message, task.cost_time, self.unit) }.get(task.status, 'NULL')
def execute(self): self.salir = False while not self.salir: self.clock.tick(self.velocidad) # eventos de teclado for event in pygame.event.get(): if event.type == pygame.QUIT: self.salir = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self.pausa = True # submenu if self.pausa: while self.pausa: self.clock.tick(self.velocidad) for event in pygame.event.get(): if event.type == pygame.QUIT: self.pausa = False self.salir = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self.pausa = False if event.key == pygame.K_2: if self.velocidad_algoritmo < 30: self.velocidad_algoritmo += 1 if event.key == pygame.K_1: if self.velocidad_algoritmo > 0: self.velocidad_algoritmo -= 1 if event.key == pygame.K_d: if self.cursor.modo_borrar: self.cursor.modo_borrar = False self.texto = self.fuente.render("Pausado", True, (255, 0, 255)) else: self.cursor.modo_borrar = True self.texto = self.fuente.render("Pausado Modo borrar paredes", True, (255, 0, 255)) if event.key == pygame.K_r: self.tablero.matrix = self.tablero.rellenaRandom() self.pathfinder.reset() self.tablero.reset_ab() if pygame.key.get_pressed()[pygame.K_l] and pygame.key.get_pressed()[pygame.K_n]: self.tablero = Tablero(80, 80) self.pathfinder = PathFinder(self.tablero) self.cursor = Cursor(self.tablero, self.pathfinder) #updates self.cursor.update() self.cursor.changeState() self.texto_algo = self.fuente.render("Velocidad: " + str(self.velocidad_algoritmo), True, (255, 0, 255)) # draws self.screen.fill((0, 0, 0)) self.draw_matriz() self.screen.blit(self.texto, (8, self.screen.get_height() - 28)) self.screen.blit(self.texto_algo, (self.screen.get_width() - 200, self.screen.get_height() - 28)) pygame.draw.rect(self.screen, (250, 0, 0), self.cursor.rect) pygame.display.update() #pathfinder #self.pathfinder.run2() for i in range(self.velocidad_algoritmo): self.pathfinder.run() # el que funciona # updates self.cursor.update() # draws self.screen.fill((0, 0, 0)) self.draw_matriz() pygame.display.update()
class Program(object): def __init__(self): self.tablero = Tablero(80, 80) self.screen = pygame.display.set_mode((len(self.tablero.matrix[0]) * 10, len(self.tablero.matrix) * 10 + 32), pygame.DOUBLEBUF) pygame.display.set_caption("Pathfinder") self.clock = pygame.time.Clock() self.pausa = True self.velocidad = 100 self.velocidad_algoritmo = 8 # a star self.pathfinder = PathFinder(self.tablero) # cursor self.cursor = Cursor(self.tablero, self.pathfinder) #fuente pygame.font.init() self.fuente = pygame.font.SysFont("default", 24) self.texto = self.fuente.render("Pausado", True, (255, 0, 255)) self.texto_algo = self.fuente.render("Velocidad: " + str(self.velocidad_algoritmo), True, (255, 0, 255)) def draw_matriz(self): for linea in self.tablero.matrix: for casilla in linea: if casilla.estado == "D": pygame.draw.rect(self.screen, (100, 40, 0), casilla.rect) elif casilla.estado == "A": pygame.draw.rect(self.screen, (255, 255, 0), casilla.rect) elif casilla.estado == "B": pygame.draw.rect(self.screen, (0, 255, 100), casilla.rect) else: pygame.draw.rect(self.screen, (20, 170, 170), casilla.rect) for posibles in self.pathfinder.open_list: pygame.draw.rect(self.screen, (0, 0, 0), posibles.rect) if self.pathfinder.encontrado: for casillas in self.pathfinder.ruta: pygame.draw.rect(self.screen, (0, 255, 0), casillas.rect) else: for analizados in self.pathfinder.closed_list: pygame.draw.rect(self.screen, (255, 255, 240), analizados.rect) def execute(self): self.salir = False while not self.salir: self.clock.tick(self.velocidad) # eventos de teclado for event in pygame.event.get(): if event.type == pygame.QUIT: self.salir = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self.pausa = True # submenu if self.pausa: while self.pausa: self.clock.tick(self.velocidad) for event in pygame.event.get(): if event.type == pygame.QUIT: self.pausa = False self.salir = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self.pausa = False if event.key == pygame.K_2: if self.velocidad_algoritmo < 30: self.velocidad_algoritmo += 1 if event.key == pygame.K_1: if self.velocidad_algoritmo > 0: self.velocidad_algoritmo -= 1 if event.key == pygame.K_d: if self.cursor.modo_borrar: self.cursor.modo_borrar = False self.texto = self.fuente.render("Pausado", True, (255, 0, 255)) else: self.cursor.modo_borrar = True self.texto = self.fuente.render("Pausado Modo borrar paredes", True, (255, 0, 255)) if event.key == pygame.K_r: self.tablero.matrix = self.tablero.rellenaRandom() self.pathfinder.reset() self.tablero.reset_ab() if pygame.key.get_pressed()[pygame.K_l] and pygame.key.get_pressed()[pygame.K_n]: self.tablero = Tablero(80, 80) self.pathfinder = PathFinder(self.tablero) self.cursor = Cursor(self.tablero, self.pathfinder) #updates self.cursor.update() self.cursor.changeState() self.texto_algo = self.fuente.render("Velocidad: " + str(self.velocidad_algoritmo), True, (255, 0, 255)) # draws self.screen.fill((0, 0, 0)) self.draw_matriz() self.screen.blit(self.texto, (8, self.screen.get_height() - 28)) self.screen.blit(self.texto_algo, (self.screen.get_width() - 200, self.screen.get_height() - 28)) pygame.draw.rect(self.screen, (250, 0, 0), self.cursor.rect) pygame.display.update() #pathfinder #self.pathfinder.run2() for i in range(self.velocidad_algoritmo): self.pathfinder.run() # el que funciona # updates self.cursor.update() # draws self.screen.fill((0, 0, 0)) self.draw_matriz() pygame.display.update()
def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) self.createMenu() #self.pngs = ['c:/temp/mibook.png'] self.pngs = GetPngList(PNGDIR) self.cursor = Cursor(ListView(self.pngs)) box = wx.BoxSizer(wx.VERTICAL) # next button row = wx.BoxSizer(wx.HORIZONTAL) def CursorButton(label): b = wx.Button(self, label= label) b.Bind(wx.EVT_BUTTON, self.OnCursorButton) return b row.Add(CursorButton("<<")) row.Add(CursorButton("<")) self.which = wx.TextCtrl(self, -1, '') self.updateWhich() row.Add(self.which) row.Add(CursorButton(">")) row.Add(CursorButton(">>")) # coords box self.coords = wx.TextCtrl(self, -1, '(0,0)') row.Add(self.coords, 0, wx.ALIGN_RIGHT) row.Add((20,20),1) # color box self.color = wx.TextCtrl(self, -1, '0x000000') row.Add(self.color, 0, wx.ALIGN_RIGHT) row.Add((20,20),1) box.Add(row, 0, wx.ALIGN_CENTER_HORIZONTAL) # the image pane = wx.ScrolledWindow(self, -1, size=(300,400)) box.Add(pane, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALL|wx.ADJUST_MINSIZE) self.image = wx.StaticBitmap(pane, bitmap=wx.EmptyBitmap(800, 600)) self.image.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) self.image.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown) self.updateImage() # the shell self.locals = {'self':self, 'wx':wx, 'hook': lambda:None, 'gc':self.getGC() } self.shell = py.shell.Shell(self, locals=self.locals) self.shell.SetMinSize((500,400)) box.Add(self.shell, 4, wx.EXPAND) self.shell.SetFocus() self.SetSizerAndFit(box) wx.EVT_CLOSE(self, self.OnCloseWindow)
from cursor import Cursor #Main pygame.init() screenwidth = 640 screenheight = 480 screen = pygame.display.set_mode((screenwidth, screenheight)) pygame.display.set_caption('Game') #game clock FPS = 20 clock = pygame.time.Clock() trooper = Unit(screen, 'trooper', 'spritesheets/trooper.bmp') background = Background(screen) cursor = Cursor(screen) cursor_x, cursor_y = (0,0) while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: sys.exit() elif event.key == pygame.K_z: trooper.action() elif event.key == pygame.K_UP: cursor.update('up') elif event.key == pygame.K_DOWN: