def mugello(): """Handle the front-page.""" return flask.render_template('master.xhtml', pagina=Connect.body("", "mugello"), luogo="mugello", menu=Connect.menu(""), submenu=Connect.submnu(""))
def get(self): self.render('master.xhtml', pagina=Connect.body("", "sanpiero"), luogo="sanpiero", menu=Connect.menu(""), submenu=Connect.submnu(""))
def login(): # Output message if something goes wrong... msg = '' # Check if "username" and "password" POST requests exist (user submitted form) if request.method == 'POST' and 'username' in request.form and 'password' in request.form: # Create variables for easy access username = request.form['username'] password = request.form['password'] # Check if account exists using MySQL cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute( 'SELECT * FROM accounts WHERE username = %s AND password = %s', ( username, password, )) # Fetch one record and return result account = cursor.fetchone() # If account exists in accounts table in out database if account: # Create session data, we can access this data in other routes session['loggedin'] = True session['id'] = account['id'] session['username'] = account['username'] # Redirect to home page return flask.render_template('master.xhtml', username=session['username'], pagina=Connect.body("", "chisiamo"), luogo="index", menu=Connect.menu(""), submenu=Connect.submnu("")) else: # Account doesnt exist or username/password incorrect msg = 'Incorrect username/password!' # Show the login form with message (if any) return render_template('index.html', msg=msg)
def chisiamo(): return flask.render_template('master.xhtml', pagina=Connect.body("", "chisiamo"), luogo="index", menu=Connect.menu(""), submenu=Connect.submnu(""))
def test_connect(): print("Standard Connection") try: # Connect to the DCRIS database with an option file conn = Connect("dcris.txt") # Get the connection cursor object cursor = conn.cursor # Define a SQL query sql = "SELECT * FROM keyword" # Execute the query from the connection cursor cursor.execute(sql) # Print the column names from the query result print("Columns:") print(cursor.column_names) # Get and print the contents of the query results (raw results) rows = cursor.fetchall() print("Row count: {}".format(cursor.rowcount)) print("Data:") for row in rows: print(row) # Close the Connect object conn.close() except Exception as e: print(str(e))
def upload(): return flask.render_template('upload_form.html', pagina=Connect.body("", "upload"), luogo="upload", menu=Connect.menu(""), submenu=Connect.submnu(""))
def master(): """ simple entry for test """ return flask.render_template('master.html', tempdir="/srv/http/proloco_flask/static/img/", menu=Connect.menu(""), submenu=Connect.submnu(""), submenu2=Connect.submnu2(""))
def arrivare(): return flask.render_template('comearrivare.xhtml', pagina=Connect.body("", "upload"), luogo="upload", menu=Connect.menu(""), submenu=Connect.submnu(""))
def get(self): self.render('news.xhtml', pagina=Connect.body("", "index"), luogo="index", menu=Connect.menu(""), submenu=Connect.submnu(""), news=Connect.news(""))
def __init__(self, screen, screenw, screenh, spriteList, soundManager): self.sprites = spriteList self.screen = screen self.screenw = screenw self.screenh = screenh self.soundManager = soundManager self.state = "Main" self.mainButtons = [] self.mainButtons.append(Button(self.screen, self.sprites.getSprite("login"), self.sprites.getSprite("loginHighlighted"), 368, 350, 281, 68, "Login", 'Start Button.ogg', soundManager)) self.mainButtons.append(Button(self.screen, self.sprites.getSprite("start"), self.sprites.getSprite("startHighlighted"), 368, 442, 281, 68, "Game", 'Start Button.ogg', soundManager)) self.mainButtons.append(Button(self.screen, self.sprites.getSprite("exit"), self.sprites.getSprite("exitHighlighted"), 368, 534, 281, 68, "Exit", 'Exit.ogg', soundManager)) self.fontsize = 30 self.font = pygame.font.Font(os.path.join('Fonts', 'nasalization-rg.ttf'), self.fontsize) self.loginButtons = [] self.ip = textInput(self.screen, "Server IP", (self.screenw/2 - 200, 30), (self.font.get_height() * 8), 50, 15) self.username = textInput(self.screen, "Username", (self.screenw/2 - 200, 130), (self.font.get_height() * 8), 50, 8) self.password = textInput(self.screen, "Password", (self.screenw/2 - 200, 230), (self.font.get_height() * 8), 50, 8, True) self.loginButtons.append(Button(self.screen, self.sprites.getSprite("login"), self.sprites.getSprite("loginHighlighted"), 368, 442, 281, 68, "Lobby", 'Start Button.ogg', soundManager)) self.loginButtons.append(Button(self.screen, self.sprites.getSprite("exit"), self.sprites.getSprite("exitHighlighted"), 368, 534, 281, 68, "Main", 'Exit.ogg', soundManager)) self.mouseDelay = 50 self.mouseNext = pygame.time.get_ticks() self.loginPressed = False #for server self.socket = Connect() self.socket.serverName = None self.socket.clientSocket.settimeout(0.0) self.loginStatus = ""
def upload_form(): """ show upload form with multiple scenarios """ return flask.render_template('upload_form.html', pagina=Connect.body("", "upload"), luogo="upload", menu=Connect.menu(""), submenu=Connect.submnu(""))
def menu(): return flask.render_template('menu.xhtml', username=session['username'], pagina=Connect.body("", "menu"), luogo="index", menu=Connect.menu(""), submenu=Connect.submnu(""))
def get(self): luogo = self.get_argument('luogo') self.render('nivo.xhtml', pagina=Connect.body("", "index"), luogo="index", menu=Connect.menu(""), submenu=Connect.submnu(""), slider=Connect.slider("", luogo))
def get(self): titolo = self.get_argument('titolo') id = self.get_argument('id') self.render('news_one.xhtml', news=Connect.news_one("", titolo, id), pagina=Connect.body("", "sanpiero"), titolo=titolo, id=id)
def news_one(): titolo = request.args['titolo'] id = request.args['id'] """Handle the front-page.""" return flask.render_template('news_one.xhtml', news=Connect.news_one("", titolo, id), pagina=Connect.body("", "sanpiero"), titolo=titolo, id=id)
def entry_point(): """ simple entry for test """ return flask.render_template('master.xhtml', luogo="index", pagina=Connect.body("", "index"), tempdir="/srv/http/proloco_flask/static/img/", menu=Connect.menu(""), submenu=Connect.submnu(""), submenu2=Connect.submnu2(""))
def __init__(self, screen, screenw, screenh, spriteList, soundManager): self.sprites = spriteList self.screen = screen self.screenw = screenw self.screenh = screenh self.soundManager = soundManager self.player = Player(1, "ship1", "missile1", (500, 700), 32, 32) #self.player = Player(player, "ship" + str(player), "missile"+ str(player + 1), (200 * player,700), 32, 32) self.paused = False self.start = True self.level = 1 self.background = "GameBackground" self.background2 = "GameBackground" self.enemyGrid = [] self.enemyRowCount = 5 self.enemyColumnCount = 10 self.enemyCount = 50 #self.player.score = 0 self.setGrid() self.missiles = [] self.missileDelay = 100 self.enemyDelay = 100 self.enemyFireChance = 100 self.nextMissile = pygame.time.get_ticks() + self.missileDelay self.nextEnemyMove = pygame.time.get_ticks() + self.enemyDelay self.bgHeight = 1536 self.currentBG1Height = 0 self.currentBG2Height = -self.bgHeight self.state = "Game" self.keyDelay = 500 self.nextKeyInput = pygame.time.get_ticks() self.fontsize = 30 self.font = pygame.font.Font(os.path.join('Fonts', 'nasalization-rg.ttf'), self.fontsize) self.pauseButtons = [] self.pauseButtons.append(Button(screen, self.sprites.getSprite("exit"), self.sprites.getSprite("exitHighlighted"), 368, 330, 281, 68, "Menu", 'Exit.ogg', soundManager)) self.mouseDelay = 100 self.mouseNext = pygame.time.get_ticks() #for server self.socket = Connect() self.socket.serverName = '169.234.82.138' random.seed(datetime.now()) self.startTime = None
def get(self): self.render('manifesta.xhtml', titolo="Manifestazioni", per='5%', go="more", pagina=Connect.body("", "sanpiero"), manifestazione="manifestazioni", news=Connect.manifesta(""), menu=Connect.menu(""), submenu=Connect.submnu(""))
def manifestazioni(): return flask.render_template('manifesta.xhtml', username=session['username'], titolo="Manifestazioni", per='5%', go="more", pagina=Connect.body("", "sanpiero"), manifestazione="manifestazioni", news=Connect.manifesta(""), menu=Connect.menu(""), submenu=Connect.submnu(""))
def match(self): self.connect = Connect() self.connect.connect(local.id, local.curDeckID) data = self.connect.recv() if data == None: return logger.error('匹配超时') self.cardlist = [] #待选 self.selected = [] #选中 self.commitArgs = [] #暂存变量 self.status = 'beforeBattle' self.renderOpening(data) # 绘制开场信息并等待换牌
def logout(): # Remove session data, this will log the user out session.pop('loggedin', None) session.pop('id', None) session.pop('username', None) # Redirect to login page return flask.render_template('master.xhtml', luogo="index", pagina=Connect.body("", "index"), tempdir="/srv/http/proloco_flask/static/img/", menu=Connect.menu(""), submenu=Connect.submnu(""), submenu2=Connect.submnu2(""))
def getMoviesWithoutDirector(): connect = Connect() cursor = connect.initConnect() query = ("SELECT id_movie, imdb_id " " FROM movies " " WHERE id_movie NOT IN (SELECT id_movie FROM movies_directors) AND id_movie > 11844") cursor.execute(query) result = {} for (id_movie, imdb_id) in cursor: result[id_movie] = imdb_id connect.closeConnect() return result
def main(): (PROJECT, LOCATION, VERBOSE, USER, PASSWORD, EXTENSIONS) = process_arguments() TC = Connect(USER, PASSWORD) Logged_In = TC.Login() if Logged_In: logger.info("Logged in as {}".format(USER)) else: print "Login failed" sys.exit(1) TC.set_projects_area(LOCATION) projects = (TC.get_projects()) ProjectId = None for project_index in projects: if projects[project_index]["name"].lower() == PROJECT.lower(): logger.debug("Found Project") # pprint ( projects[project_index]) ProjectId = project_index RootId = projects[project_index]["rootId"] if ProjectId != None: download_dir_and_children(TC, ProjectId, RootId, ".", EXTENSIONS, VERBOSE) else: logger.critical("Did not find Project") print "Did not find Project" logger.info("Logging out") TC.logout()
def manifestazioni_one(): titolo = request.args['titolo'] id = request.args['id'] """Handle the front-page.""" return flask.render_template('manifesta.xhtml', username=session['username'], per='30%', go="back", news=Connect.manifesta_one("", titolo, id), pagina=Connect.body("", "sanpiero"), titolo=titolo, id=id, menu=Connect.menu(""), submenu=Connect.submnu(""))
def ins_manifesta(): # Output message if something goes wrong... msg = '' # Check if "username", "password" and "email" POST requests exist (user submitted form) if request.method == 'POST' and 'username' in request.form and 'password' in request.form and 'email' in request.form: # Create variables for easy access username = request.form['username'] password = request.form['password'] email = request.form['email'] cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM accounts WHERE username = %s', (username, )) account = cursor.fetchone() # If account exists show error and validation checks if account: msg = 'Account already exists!' elif not re.match(r'[^@]+@[^@]+\.[^@]+', email): msg = 'Invalid email address!' elif not re.match(r'[A-Za-z0-9]+', username): msg = 'Username must contain only characters and numbers!' elif not username or not password or not email: msg = 'Please fill out the form!' else: multiple_upload() # Account doesnt exists and the form data is valid, now insert new account into accounts table cursor.execute('INSERT INTO accounts VALUES (NULL, %s, %s, %s)', ( username, password, email, )) mysql.connection.commit() msg = 'You have successfully registered!' elif request.method == 'POST': # Form is empty... (no POST data) msg = 'Please fill out the form!' # Show registration form with message (if any) if 'loggedin' in session: return render_template('ins_manifestazioni.html', msg=msg, tempdir="/srv/http/proloco_flask/static/img/", menu=Connect.menu(""), submenu=Connect.submnu(""), submenu2=Connect.submnu2("")) else: msg = 'devi registrarti per inserire contenuti' return render_template('index.html', msg=msg)
def __init__(self, id=None, mode='PoW', block_size=200, difficulty=3, port=0000, ip="000", local_ip="000"): self.id = id self.mode = mode self.block_size = block_size self.blocks = [] self.difficulty = difficulty self.curr_block = Block(block_size=block_size) self.credits = {0: sys.float_info.max} if port != 0000: self.connect = Connect( port, { ConnectData.TYPE_TRANSACTION: self.add_transaction, ConnectData.TYPE_BLOCK: self.add_block, ConnectData.TYPE_MESSAGE: self.print_msg }) if ip != "000": self.connect = ConnectRemote( ip, local_ip, { ConnectData.TYPE_TRANSACTION: self.add_transaction, ConnectData.TYPE_BLOCK: self.add_block, ConnectData.TYPE_MESSAGE: self.print_msg }) self.transactions_queue = [] self.blocks_queue = [] self.lock = threading.Lock() self.__setup_logger() self.main_thread = threading.Thread(target=self.__run).start()
def find(name): connect = Connect() cursor = connect.initConnect() query = ("SELECT id_director, name " "FROM directors " "WHERE name = %s " "ORDER BY id_director ASC") data = (name,) cursor.execute(query, data) result = False for (id_director, name) in cursor: result = id_director break connect.closeConnect() return result
def main(): print("Welcome to the simple Blockchain project!") transactions, clients = produce_transactions("txdataset_v2.txt", 40) remote_network = False main_connect = Connect(65430) #To send over Local Network if remote_network: main_connect = ConnectRemote("192.168.1.7", False) # To send over Remote Network # miner0 = Miner(id=0, block_size=100, difficulty=20, port=65434, main_connect=main_connect) # miner1 = Miner(id=1, block_size=100, difficulty=20, port=65435, main_connect=main_connect) # miner2 = Miner(id=2, block_size=100, difficulty=20, port=65436, main_connect=main_connect) # miner1 = Miner(id=0, block_size=100, difficulty=20, port=65434) for transaction in transactions: main_connect.send_to_all_miners(ConnectData.TYPE_TRANSACTION, transaction)
def test_heightInsert(self): t = TriSolve() p1 = PVector(12, 10) p2 = PVector(10, 20) p3 = PVector(20, 29) v1 = Vertex(p1) v2 = Vertex(p2) v3 = Vertex(p3) c1 = Connect(v1, v2) c2 = Connect(v1, v3) c3 = Connect(v2, v3) l = [] l = t.heightInsert(l, c3) self.assertEqual(l, [c3]) l = t.heightInsert(l, c1) self.assertEqual(l, [c1, c3]) l = t.heightInsert(l, c2) self.assertEqual(l, [c1, c2, c3])
def save(data): connect = Connect() cursor = connect.initConnect() query = ("INSERT INTO movies " "(title" ", original_title" ", year" ", release_date" ", duration" ", imdb_rating" ", imdb_id" ", imdb_poster)" "VALUES (%s, %s, %s, %s, %s, %s, %s, %s)") data = (data['title'] , data['original_title'] , data['year'] , data['release_date'] , data['duration'] , data['rating'] , data['imdb_id'] , data['poster'] ) cursor.execute(query, data) connect.commit() id_movie = cursor.lastrowid connect.closeConnect() return id_movie
def __init__(self, btn, c_list): self.builder = gtk.Builder() self.builder.add_from_file("./ui/w2s.glade") self.login = self.builder.get_object("login") usr = self.builder.get_object("usr") pwd = self.builder.get_object("pwd") msg_box = gtk.MessageDialog(parent=None, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_OK) msg_box.set_markup("Invalid Mobile Number or Password") Login.btn = btn Login.c_list = c_list # FIXME: Autologin #try: # pass_file=open(".pass","r") # usr.set_text(pass_file.read().rsplit()[0]) # pass_file.close() #except IOError: # print('file cant open') # #finally: # pass_file.close() res = self.login.run() if (res == 1): Login.con = Connect() state = Login.con.login(usr.get_text(), pwd.get_text()) if (state == login_failed): msg_box.run() msg_box.hide() elif (state == login_success): contact = Contacts(Login.con.getContacts(), Login.c_list) contact.build_list() Login.btn.set_sensitive(True) #fetch contatcs data elif (res == 2): pass self.login.hide()
def addGenre(id_movie, id_genre): connect = Connect() cursor = connect.initConnect() query = ("INSERT INTO movies_genres " "(id_movie, id_genre)" "VALUES (%s, %s)") data = (id_movie, id_genre) cursor.execute(query, data) connect.commit() connect.closeConnect()
def main(): (PROJECT, LOCATION, FOLDER, FILES, GLOB, AGE, DELETE, CACHE, RECURSE, VERBOSE, USER, PASSWORD) = process_arguments() TC = Connect(USER, PASSWORD, VERBOSE) Logged_In = TC.Login() if Logged_In: logger.info("Logged in as {}".format(USER)) else: logger.info("Login in as {} failed".format(USER)) sys.exit("Login failed") TC.set_projects_area(LOCATION) projectId = (TC.get_project_by_name(PROJECT)) if projectId == None: logger.critical("Did not find Project") sys.exit("Did not find Project") else: logger.info("projectID: " + projectId) folderId = TC.get_folderId_by_path(projectId, PROJECT, FOLDER) if folderId == None: logger.critical("Did not find folder") sys.exit("Did not find folder") else: logger.info("folderID: " + folderId) # subfolders=TC.get_folders(projectId,folderId) upload_files_and_folders(TC, projectId, PROJECT, folderId, FOLDER, FILES, GLOB, AGE, DELETE, CACHE, RECURSE, VERBOSE) logger.info("Logging out") TC.logout()
def addDirector(id_movie, id_director): connect = Connect() cursor = connect.initConnect() query = ("INSERT INTO movies_directors " "(id_movie, id_director)" "VALUES (%s, %s)") data = (id_movie, id_director) cursor.execute(query, data) connect.commit() connect.closeConnect()
def save(id_imdb): connect = Connect() cursor = connect.initConnect() query = ("INSERT INTO imdb " "(id_imdb)" "VALUES (%s)") data = (id_imdb,) try: cursor.execute(query, data) except MySQLdb.Error: raise connect.commit() connect.closeConnect()
def __init__(self): """Ctor""" self.symbols = {} self.ticks = {} self.event = Event() self.con = Connect("172.20.0.11", port = 7496, verbose = True) handlers = { self.errorHandler: message.Error, self.tickPriceHandler: message.TickPrice, self.tickSizeHandler: message.TickSize, self.tickGenericHandler: message.TickGeneric, self.tickStringHandler: message.TickString, self.portfolioHandler: message.UpdatePortfolio, self.accountValueHandler: message.UpdateAccountValue } for func, msg in handlers.iteritems(): self.con.register(func, msg)
def test_Connect__eq__(self): p = PVector(12, 10) p1 = PVector(20, 20) p2 = PVector(20, 20) v1 = Vertex(p) v2 = Vertex(p1) c1 = Connect(v1, v2) c2 = Connect(v2, v1) c3 = Connect(v1, v2) self.assertEqual(c1, c2) self.assertEqual(c1, c3) self.assertEqual(c1 == Connect(v1, v2), True) #same coordinates, but not referring to the same Vertex object self.assertEqual(c1 == Connect(v1, Vertex(p1)), False) self.assertEqual( Connect(v1, Vertex(p1)) == Connect(v1, Vertex(p1)), False)
def save(name): connect = Connect() cursor = connect.initConnect() query = ("INSERT INTO directors " "(name)" "VALUES (%s)") data = (name,) cursor.execute(query, data) connect.commit() id_director = cursor.lastrowid connect.closeConnect() return id_director
def connectLogin(self): self.connect = Connect() self.connect.setConfig(self.conf) wx.BeginBusyCursor() if self.connect.testConnect(): wx.EndBusyCursor() self.message.SetForegroundColour('ROYALBLUE1') self.message.SetLabel("network connected please login") self.tryLogin() else: wx.EndBusyCursor() self.message.SetForegroundColour(wxNamedColour('ORANGE1')) self.message.SetLabel("network failed. please try proxy") self.proxy = ProxyDialog(self) keeptrying = True while keeptrying: if self.proxy.showProxy(self): self.connect.setProxy(self.proxy.getProxyServer() + ':' + self.proxy.getProxyPort()) wx.BeginBusyCursor() window.message.SetForegroundColour('ROYALBLUE1') window.message.SetLabel("checking network connection...") if self.connect.testConnect(): wx.EndBusyCursor() self.message.SetForegroundColour('ROYALBLUE1') self.message.SetLabel("network connected. please login") if self.tryLogin(): keeptrying = False else: wx.EndBusyCursor() self.message.SetForegroundColour(wxNamedColour('ORANGE1')) if len(self.proxy.getProxyServer()) > 0: #FIXME add proper check self.message.SetLabel("proxy failed. please try again") else: self.message.SetLabel("network failed. please try proxy") else: self.Destroy() sys.exit(0)
def getLastImdbID(): connect = Connect() cursor = connect.initConnect() query = ("SELECT MAX(id_imdb) AS last_imdb_id " "FROM imdb ") cursor.execute(query) result = False for (last_imdb_id) in cursor: if(last_imdb_id[0] == None): last_imdb_id = 0 else: last_imdb_id = int(last_imdb_id[0]) break nid = last_imdb_id + 1 try: Imdb.save(nid) connect.closeConnect() except MySQLdb.Error: connect.closeConnect() nid = Imdb.getLastImdbID() return nid
class AppIB(): """IB API Implementation""" def __init__(self): """Ctor""" self.symbols = {} self.ticks = {} self.event = Event() self.con = Connect("172.20.0.11", port = 7496, verbose = True) handlers = { self.errorHandler: message.Error, self.tickPriceHandler: message.TickPrice, self.tickSizeHandler: message.TickSize, self.tickGenericHandler: message.TickGeneric, self.tickStringHandler: message.TickString, self.portfolioHandler: message.UpdatePortfolio, self.accountValueHandler: message.UpdateAccountValue } for func, msg in handlers.iteritems(): self.con.register(func, msg) def start(self): """Start the app.""" self.symbols["QQQ"] = self.createContract("QQQ") self.symbols["MNST"] = self.createContract("MNST") self.symbols["MSFT"] = self.createContract("MSFT") self.con.reqMktData(self.symbols) # con.addOrder("MNST", minQty = 100, orderType="MKT", outsideRTH = True) # con.placeOrder() def run(self): """Run the main loop""" while True: self.event.wait(30) self.event.clear() if 0: continue for key, id in self.symbols.items(): try: print key, ":", self.ticks[id.m_conId] except KeyError: print key, ": No data" print def createContract(self, symbol, secType="STK", exchange="SMART", currency="USD"): """Create and store a contact from the given symbol""" c = Contract() c.m_symbol = symbol c.m_secType = secType c.m_exchange = exchange c.m_currency = currency return c def getSymbolFromId(self, id): """Return the string symbol for the given id. @param id Integer Id of the wanted symbol. @return String Symbol """ try: return [v.m_symbol for v in self.symbols.values() if v.m_conId == id][0] except IndexError: return False def tickGenericHandler(self, msg): print "GENERIC--- [{2}] {0}: {1}.".format( TickType.getField(msg.tickType), msg.value, self.getSymbolFromId(msg.tickerId)) def tickStringHandler(self, msg): print "STRING--- [{2}] {0}: {1}.".format( TickType.getField(msg.tickType), msg.value, self.getSymbolFromId(msg.tickerId)) def tickPriceHandler(self, msg): """Handle TickPrice messages from IB. Remove the globals and implement a Producer/Consumer @param msg ib.opt.message.TickPrice Message sent by IB """ self.ticks[msg.tickerId] = msg symb = self.getSymbolFromId(msg.tickerId) if symb: db.tickers.update({"symbol": symb}, {"$set": {TickType.getField(msg.field): msg.price}}, upsert = True) self.event.set() def portfolioHandler(self, msg): """Handle UpdatePortfolio messages from IB. @param msg ib.opt.message.UpdatePortfolio """ print "----", type(msg), msg def accountValueHandler(self, msg): """Handle UpdateAccountValue messages from IB. Store accout data in db @param msg ib.opt.message.UpdateAccountValue Message sent by IB """ db.account.update({"account": msg.accountName, msg.key: {"$exists": True}}, {"$set": {msg.key: msg.value, "currency": msg.currency}}, upsert = True) print "account: {0}: {1} [{2}] ({3})".format( msg.key, msg.value, msg.currency, msg.accountName) def tickSizeHandler(self, msg): """Handle TickSize messages from IB. Store tick data in db @param msg ib.opt.message.TickSize Message sent by IB """ symb = self.getSymbolFromId(msg.tickerId) if symb: #print "[{1}] {0}: {2}".format(symb, fieldType[msg.field], msg.size) db.tickers.update({"symbol": symb}, {"$set": {TickType.getField(msg.field): msg.size}}, upsert = True) def errorHandler(self, msg): """Error handler. @param msg ib.opt.message.Error Message sent by IB """ print "ERROR:", msg
class Main_Menu(): def __init__(self, screen, screenw, screenh, spriteList, soundManager): self.sprites = spriteList self.screen = screen self.screenw = screenw self.screenh = screenh self.soundManager = soundManager self.state = "Main" self.mainButtons = [] self.mainButtons.append(Button(self.screen, self.sprites.getSprite("login"), self.sprites.getSprite("loginHighlighted"), 368, 350, 281, 68, "Login", 'Start Button.ogg', soundManager)) self.mainButtons.append(Button(self.screen, self.sprites.getSprite("start"), self.sprites.getSprite("startHighlighted"), 368, 442, 281, 68, "Game", 'Start Button.ogg', soundManager)) self.mainButtons.append(Button(self.screen, self.sprites.getSprite("exit"), self.sprites.getSprite("exitHighlighted"), 368, 534, 281, 68, "Exit", 'Exit.ogg', soundManager)) self.fontsize = 30 self.font = pygame.font.Font(os.path.join('Fonts', 'nasalization-rg.ttf'), self.fontsize) self.loginButtons = [] self.ip = textInput(self.screen, "Server IP", (self.screenw/2 - 200, 30), (self.font.get_height() * 8), 50, 15) self.username = textInput(self.screen, "Username", (self.screenw/2 - 200, 130), (self.font.get_height() * 8), 50, 8) self.password = textInput(self.screen, "Password", (self.screenw/2 - 200, 230), (self.font.get_height() * 8), 50, 8, True) self.loginButtons.append(Button(self.screen, self.sprites.getSprite("login"), self.sprites.getSprite("loginHighlighted"), 368, 442, 281, 68, "Lobby", 'Start Button.ogg', soundManager)) self.loginButtons.append(Button(self.screen, self.sprites.getSprite("exit"), self.sprites.getSprite("exitHighlighted"), 368, 534, 281, 68, "Main", 'Exit.ogg', soundManager)) self.mouseDelay = 50 self.mouseNext = pygame.time.get_ticks() self.loginPressed = False #for server self.socket = Connect() self.socket.serverName = None self.socket.clientSocket.settimeout(0.0) self.loginStatus = "" def draw(self): if self.state == "Main": self.screen.blit(self.sprites.getSprite("titlescreen"), (0, 0)) for button in self.mainButtons: button.draw() elif self.state == "Login": self.screen.blit(self.sprites.getSprite("titlescreenbg"), (0, 0)) self.ip.draw() self.username.draw() self.password.draw() if self.loginStatus == "Invalid Password": self.screen.blit(self.font.render("Wrong Password. Try again.", True, pygame.Color(255,255,255)),(300,self.screenh/2 - 100)) elif self.loginStatus == "No Server": self.screen.blit(self.font.render("Waiting for server. Double check info.", True, pygame.Color(255,255,255)),(300,self.screenh/2 - 100)) elif self.loginStatus == "Missing Field(s)": self.screen.blit(self.font.render("Missing Field(s).", True, pygame.Color(255,255,255)),(self.screenw/2 - (len("Invalid Format.") * 30)/4,self.screenh/2 - 100)) for button in self.loginButtons: button.draw() def mouseUpdate(self): if pygame.time.get_ticks() >= self.mouseNext: if pygame.mouse.get_pressed()[0]: if self.state == "Main": for button in self.mainButtons: if button.checkClicked(pygame.mouse.get_pos()): self.state = button.click() elif self.state == "Login": for button in self.loginButtons: if button.checkClicked(pygame.mouse.get_pos()): self.state = button.click() if self.state == "Lobby": self.loginPressed = True if self.ip.input != "" and self.username.input != "" and self.password.input != "": message = self.username.input + ":" + self.password.input self.socket.serverName = self.ip.input try: self.socket.send("LOG:" + message) modifiedMessage, serverAddress = self.socket.clientSocket.recvfrom(2048) self.loginStatus = "" if modifiedMessage.decode() == "Invalid Password": self.loginStatus = "Invalid Password" self.state = "Login" except: self.loginStatus = "No Server" self.state = "Login" else: self.state = "Login" self.loginStatus = "Missing Field(s)" else: self.loginStatus = "" self.loginPressed = False self.ip.checkClicked(pygame.mouse.get_pos()) self.username.checkClicked(pygame.mouse.get_pos()) self.password.checkClicked(pygame.mouse.get_pos()) self.mouseNext = pygame.time.get_ticks() + self.mouseDelay def update(self): self.mouseUpdate() if self.state == "Main": for button in self.mainButtons: button.checkHover(pygame.mouse.get_pos()) return "Menu" elif self.state == "Login": if self.loginPressed: try: message = self.username.input + ":" + self.password.input self.socket.send("LOG:" + message) modifiedMessage, serverAddress = self.socket.clientSocket.recvfrom(2048) self.loginStatus = "" if modifiedMessage.decode() == "Invalid Password": self.loginStatus = "Invalid Password" self.state = "Login" elif modifiedMessage.decode() == "Success": self.state = "Lobby" except: self.loginStatus = "No Server" self.state = "Login" for button in self.loginButtons: button.checkHover(pygame.mouse.get_pos()) self.ip.update() self.username.update() self.password.update() return "Menu" else: return self.state
class game: def __init__(self, screen, screenw, screenh, spriteList, soundManager): self.sprites = spriteList self.screen = screen self.screenw = screenw self.screenh = screenh self.soundManager = soundManager self.player = Player(1, "ship1", "missile1", (500, 700), 32, 32) #self.player = Player(player, "ship" + str(player), "missile"+ str(player + 1), (200 * player,700), 32, 32) self.paused = False self.start = True self.level = 1 self.background = "GameBackground" self.background2 = "GameBackground" self.enemyGrid = [] self.enemyRowCount = 5 self.enemyColumnCount = 10 self.enemyCount = 50 #self.player.score = 0 self.setGrid() self.missiles = [] self.missileDelay = 100 self.enemyDelay = 100 self.enemyFireChance = 100 self.nextMissile = pygame.time.get_ticks() + self.missileDelay self.nextEnemyMove = pygame.time.get_ticks() + self.enemyDelay self.bgHeight = 1536 self.currentBG1Height = 0 self.currentBG2Height = -self.bgHeight self.state = "Game" self.keyDelay = 500 self.nextKeyInput = pygame.time.get_ticks() self.fontsize = 30 self.font = pygame.font.Font(os.path.join('Fonts', 'nasalization-rg.ttf'), self.fontsize) self.pauseButtons = [] self.pauseButtons.append(Button(screen, self.sprites.getSprite("exit"), self.sprites.getSprite("exitHighlighted"), 368, 330, 281, 68, "Menu", 'Exit.ogg', soundManager)) self.mouseDelay = 100 self.mouseNext = pygame.time.get_ticks() #for server self.socket = Connect() self.socket.serverName = '169.234.82.138' random.seed(datetime.now()) self.startTime = None def reset(self): self.player = Player(1, "ship1", "missile2", (500, 700), 32, 32) self.enemyGrid = [] self.missiles = [] self.enemyCount = 50 self.setGrid() self.level = 1 self.player.score = 0 self.state = "Game" self.paused = False self.start = True self.startTime = pygame.time.get_ticks() #Creates the grid for the enemies in the game def setGrid(self, speed = 16, health = 1): for row in range(self.enemyRowCount): self.enemyGrid.append([]) for column in range(self.enemyColumnCount): rnum = random.randint(1, 100) enemySprite = "Alien1SpriteSheet" if rnum <= 45: enemySprite = "Alien2SpriteSheet" elif rnum >= 90 and rnum < 98: enemySprite = "Alien3SpriteSheet" elif rnum >= 98: enemySprite = "Alien4SpriteSheet" self.enemyGrid[row].append(Enemy((32 + (column * 96), (row * 64) - self.enemyRowCount * 64), 32, 32, Animate(self.sprites.getSprite(enemySprite), 2, 2, 32, 32, 10), health, speed, row, column, enemySprite)) def draw(self): self.screen.blit(self.sprites.getSprite(self.background), (0, self.currentBG1Height)) self.screen.blit(self.sprites.getSprite(self.background2), (0, self.currentBG2Height)) self.screen.blit(self.sprites.getSprite(self.player.image), self.player.getPos()) for missile in self.missiles: self.screen.blit(self.sprites.getSprite(missile.image), missile.getPos()) for row in range(self.enemyRowCount): for column in range(self.enemyColumnCount): self.enemyGrid[row][column].anim.draw(self.screen, self.enemyGrid[row][column].getPos()) self.screen.blit(self.font.render("Lives: " + str(self.player.lives), True, pygame.Color(255,255,255)), (0, 670)) self.screen.blit(self.font.render("Ammo: " + str(self.player.missileCap - self.player.missileCount), True, pygame.Color(255,255,255)), (0, 670 + self.fontsize)) self.screen.blit(self.font.render("Score: " + str(self.player.score), True, pygame.Color(255,255,255)),(0,670 + (self.fontsize * 2))) self.screen.blit(self.font.render("Level: " + str(self.level), True, pygame.Color(255,255,255)), (0, 670 - self.fontsize)) if self.paused: for button in self.pauseButtons: button.draw() #Handles everything that needs to go on in the game def update(self): if self.start: if pygame.time.get_ticks() >= self.startTime + 100: self.soundManager.playSound("Enemy_entrance.ogg") pygame.time.delay(2000) self.soundManager.playNewMusic("ScumInvadersTheme(Final).ogg", .2) self.start = False self.keyUpdate() if not self.paused: self.backgroundUpdate() self.state = self.enemyUpdate() if self.checkState(): return self.state self.checkMissiles() self.state = self.checkPlayerLives() if self.checkState(): return self.state self.checkEnemyCount() else: return self.mouseUpdate() return self.state def togglePause(self): self.paused = not self.paused def checkState(self): return self.state != "Game" def checkPlayerLives(self): if (self.player.lives <= 0): return "Menu" return "Game" def checkEnemyCount(self): if self.enemyCount == 0: self.enemyCount = 50 self.nextLevel() '''Odd levels -> change speed; even levels -> change health''' def nextLevel(self): self.enemyGrid = [] self.level += 1 if self.level == 5: self.soundManager.playSound("LevelUp.ogg") self.player.image = "ship1upgrade2" elif self.level == 10: self.soundManager.playSound("LevelUp.ogg") self.player.image = "ship1upgrade3" if self.level % 2 == 0: if self.enemyFireChance > 20: self.enemyFireChance -= 2; self.setGrid(16 + self.level/2, self.level/2) else: self.setGrid(16 + (self.level -1)/2, self.level//2 + 1) #for row in range(self.enemyRowCount): # for column in range(self.enemyColumnCount): # if self.level % 2 == 0: # self.enemyGrid[row][column].speed += self.level * 5 # else: # rnum = random.randint(self.level - 1, self.level) # self.enemyGrid[row][column].health = rnum if self.level %2 == 1: self.player.missileCap += 1 #Handles all of the keypresses (Movement, Shooting and pause) def keyUpdate(self): keys = pygame.key.get_pressed() if pygame.time.get_ticks() > self.nextKeyInput: if keys[pygame.K_ESCAPE]: self.togglePause() self.nextKeyInput = pygame.time.get_ticks() + self.keyDelay if not self.paused: if keys[pygame.K_a]: if not ((self.player.posx - self.player.speed) <= 0): self.player.moveLeft() self.socket.send("MOV:" + str(self.player.posx) + ":" + str(self.player.posy)) if keys[pygame.K_d]: if not ((self.player.posx + self.player.speed + self.player.imagew) >= self.screenw): self.player.moveRight() self.socket.send("MOV:" + str(self.player.posx) + ":" + str(self.player.posy)) if pygame.time.get_ticks() > self.nextMissile: self.nextMissile = pygame.time.get_ticks() + self.missileDelay if keys[pygame.K_SPACE]: if self.player.missileCount < self.player.missileCap: self.missiles.append(self.player.fire()) self.soundManager.playSound("Player_Shoot.ogg") #Only used in the pause menu, captures the clicks from the mouse on the pause screen def mouseUpdate(self): for button in self.pauseButtons: button.checkHover(pygame.mouse.get_pos()) if pygame.time.get_ticks() >= self.mouseNext: if pygame.mouse.get_pressed()[0]: for button in self.pauseButtons: if button.checkClicked(pygame.mouse.get_pos()): return button.click() self.mouseNext = pygame.time.get_ticks() + self.mouseDelay return "Game" def checkHit(self, numMissiles): for row in range(self.enemyRowCount): for column in range(self.enemyColumnCount): if self.enemyGrid[row][column].health != 0: if self.enemyGrid[row][column].collider.colliderect(self.missiles[numMissiles].collider): attacker = self.missiles.pop(numMissiles).owner self.enemyGrid[row][column].health -= 1 self.player.missileCount -= 1 if self.enemyGrid[row][column].health == 0 and not self.enemyGrid[row][column].dead: self.enemyGrid[row][column].dead = True self.enemyGrid[row][column].anim = Animate(self.sprites.getSprite(self.enemyGrid[row][column].type[:6] + "DeathSpriteSheet"), 3, 3, 32, 32, 2, False) self.enemyCount -= 1 if self.enemyGrid[row][column].type == "Alien4SpriteSheet": self.player.score += (100 * self.level) * 10 elif self.enemyGrid[row][column].type != "Alien3SpriteSheet": self.player.score += (100 * self.level) * 2 else: self.player.score += 100 * self.level return #Handles the effects of the missiles from both players(1) and enemies(0) def checkMissiles(self): numMissiles = 0 while numMissiles < len(self.missiles): self.missiles[numMissiles].update() attacker = self.missiles[numMissiles].owner #1 is the player's missile shots if attacker == 1: if ((self.missiles[numMissiles].posy + self.missiles[numMissiles].imageh) < 0): self.missiles.pop(numMissiles) self.player.missileCount -= 1 else: self.checkHit(numMissiles) #-1 is the enemy's missile shots elif attacker == -1: if (self.missiles[numMissiles].collider.colliderect(self.player.collider)): self.player.lives -= 1 enemyGridPos = self.missiles.pop(numMissiles).getEnemyPos() self.enemyGrid[enemyGridPos[0]][enemyGridPos[1]].missileCount -= 1 elif ((self.missiles[numMissiles].posy) > self.screenh): enemyGridPos = self.missiles.pop(numMissiles).getEnemyPos() self.enemyGrid[enemyGridPos[0]][enemyGridPos[1]].missileCount -= 1 numMissiles += 1 def enemyUpdate(self): if pygame.time.get_ticks() > self.nextEnemyMove: self.nextEnemyMove = pygame.time.get_ticks() + self.enemyDelay for row in range(self.enemyRowCount): for column in range(self.enemyColumnCount): if self.enemyGrid[row][column].health != 0 and (self.enemyGrid[row][column].posy + 32 >= 768 or (self.enemyGrid[row][column].posy + 32 > self.player.posy and self.player.posx < self.enemyGrid[row][column].posx < self.player.posx + 64)) : self.togglePause() return "Menu" self.enemyGrid[row][column].anim.update() rNum2 = random.randint(1,self.enemyFireChance) if rNum2 == 1: if (self.enemyGrid[row][column].health != 0 and self.enemyGrid[row][column].missileCount < self.enemyGrid[row][column].missileCap): self.missiles.append(self.enemyGrid[row][column].fire()) if self.enemyGrid[row][column].lastMove == None: if row % 2 == 0: self.enemyGrid[row][column].lastMove = "Left" else: self.enemyGrid[row][column].lastMove = "Right" self.enemyGrid[row][column].moveDown() self.enemyGrid[row][column].moveDown() self.enemyGrid[row][column].moveDown() #print("This happened.") elif self.enemyGrid[row][column].lastMove == "Left": if self.enemyGrid[row][column].posx <= 0: self.enemyGrid[row][column].lastMove = "Right" self.enemyGrid[row][column].moveDown() # self.enemyGrid[row][column].moveRight() else: self.enemyGrid[row][column].moveLeft() elif self.enemyGrid[row][column].lastMove == "Right": if self.enemyGrid[row][column].posx + self.enemyGrid[row][column].imagew >= 1024: self.enemyGrid[row][column].lastMove = "Left" self.enemyGrid[row][column].moveDown() # self.enemyGrid[row][column].moveLeft() else: self.enemyGrid[row][column].moveRight() #rNum = random.randint(1, 5) #for row in range(self.enemyRowCount): # for column in range(self.enemyColumnCount): ##checks if enemies have reached the bottom of the screen #if self.enemyGrid[row][column].posy + 32 >= 768 or (self.enemyGrid[row][column].posy + 32 > self.player.posy and self.player.posx < self.enemyGrid[row][column].posx < self.player.posx + 64) : # return "Menu" # if self.enemyGrid[row][column].health != 0: # if rNum >= 3: # self.enemyGrid[row][column].lastMove = "Down" # self.enemyGrid[row][column].moveDown() # elif rNum == 1: # if (self.enemyGrid[row][column].posx - 16 >= 0) and self.enemyGrid[row][column].lastMove != "Left": # self.enemyGrid[row][column].lastMove = "Left" # self.enemyGrid[row][column].moveLeft() # elif rNum == 2: # if ((self.enemyGrid[row][column].posx + 16 + self.enemyGrid[row][column].imagew) <= self.screenw) and self.enemyGrid[row][column].lastMove != "Right": # self.enemyGrid[row][column].lastMove = "Right" # self.enemyGrid[row][column].moveRight() return "Game" #scrolls through the background def backgroundUpdate(self): self.currentBG1Height += 1 self.currentBG2Height += 1 if (self.currentBG1Height >= self.bgHeight): self.currentBG1Height = -self.bgHeight rnum = random.randint(1,3) if rnum == 1: self.background = "GameBackground" elif rnum == 2: self.background = "GameBackground2" else: self.background = "GameBackground3" elif (self.currentBG2Height >= self.bgHeight): self.currentBG2Height = -self.bgHeight rnum = random.randint(1,3) if rnum == 1: self.background2 = "GameBackground" elif rnum == 2: self.background2 = "GameBackground2" else: self.background2 = "GameBackground3"
class Mytago ( wxFrame ): def __init__ ( self ): wxFrame.__init__ ( self, None, -1, 'MYTAGO Uploader', size = ( 600, 445 ), style = wx.DEFAULT_FRAME_STYLE ^ ( wx.MAXIMIZE_BOX | wx.RESIZE_BORDER ) ) self.SetBackgroundColour("WHITE") self.TESTING = False self.username = '' self.password = '' wx.lib.colourdb.updateColourDB() _icon = wx.IconFromBitmap(getAppIcon()) self.SetIcon(_icon) self.panel = wxPanel ( self, -1, size=(580, 50) ) self.panel.SetBackgroundColour('WHITE') self.addbutton = wxButton ( self.panel, -1, "+" ) self.Bind(wx.EVT_BUTTON, self.OnAddButton, self.addbutton) self.addbutton.SetForegroundColour('CHARTREUSE2') self.addbutton.SetFont(wx.Font(20, wx.SWISS, wx.NORMAL, wx.BOLD, False)) self.addbutton.SetMaxSize((30,30)) self.addbutton.SetMinSize((30,30)) self.addbutton.SetToolTipString("Add Images") self.delbutton = wxButton ( self.panel, -1, "-" ) self.Bind(wx.EVT_BUTTON, self.OnDelButton, self.delbutton) self.delbutton.Enable(False) self.delbutton.SetForegroundColour('ORANGE1') self.delbutton.SetFont(wx.Font(20, wx.SWISS, wx.NORMAL, wx.BOLD, False)) self.delbutton.SetMaxSize((30,30)) self.delbutton.SetMinSize((30,30)) self.delbutton.SetToolTipString("Remove Selected Images") self.progpanel = wxPanel(self, -1, size=(565, 10) ) self.progpanel.SetBackgroundColour('GREY70') self.progress = wx.Gauge(self.progpanel, -1, 50, size =(565, 10)) self.progress.Show(False) self.upbutton = wxButton ( self.panel, -1, "Upload" ) self.Bind(wx.EVT_BUTTON, self.OnUpButton, self.upbutton) self.upbutton.Enable(False) self.upbutton.SetForegroundColour('GREY30') self.upbutton.SetFont(wx.Font(15, wx.SWISS, wx.NORMAL, wx.BOLD, False)) self.upbutton.SetMaxSize((120,30)) self.upbutton.SetMinSize((120,30)) self.upbutton.SetToolTipString("Upload Images") self.helpbutton = wxButton ( self.panel, -1, "i" ) self.Bind(wx.EVT_BUTTON, self.OnHelpButton, self.helpbutton) self.helpbutton.SetForegroundColour('DEEPSKYBLUE') self.helpbutton.SetFont(wx.Font(15, wx.SWISS, wx.NORMAL, wx.BOLD, False)) self.helpbutton.SetMaxSize((30,30)) self.helpbutton.SetMinSize((30,30)) self.helpbutton.SetToolTipString("Help") self.imgpanel = scrolled.ScrolledPanel(self, -1, size=(560, 290), style = wx.TAB_TRAVERSAL|wx.NO_BORDER, name="imgpanel" ) self.imgpanel.SetBackgroundColour("WHITE") logo = getAppLogo() if not self.TESTING: self.logoimg = wx.StaticBitmap(self.panel, -1, logo) self.scrollsizer = wx.FlexGridSizer(rows=1, cols=3, vgap=10, hgap=10) self.imgpanel.SetSizer( self.scrollsizer ) self.imgpanel.SetAutoLayout(1) self.imgpanel.SetupScrolling() self.footer = wxPanel ( self, -1, size=(580, 20) ) self.footer.SetBackgroundColour("WHITE") self.message = wx.StaticText(self.footer, -1, "", size = (450, 10)) font = wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD) self.message.SetFont(font) self.hyper1 = hl.HyperLinkCtrl(self.footer, wx.ID_ANY, "www.mytago.com", URL="http://www.mytago.com") self.hyper1.SetBold(True) self.hyper1.SetColours("STEELBLUE1", "STEELBLUE1", "STEELBLUE1") self.hyper1.SetUnderlines(False, False, False) self.hyper1.SetToolTip(wx.ToolTip("Mytago")) self.hyper1.UpdateLink() self.sizertop = wxBoxSizer ( wxALIGN_CENTER_HORIZONTAL ) self.sizerbot = wxBoxSizer ( wxALIGN_CENTER_HORIZONTAL ) self.sizermain = wxBoxSizer ( wx.VERTICAL ) self.sizertop.Add ( (10, 40), 0, wx.EXPAND ) if self.TESTING: self.sizertop.Add ( (230, 40), 0, wx.ALIGN_TOP | wx.EXPAND ) else: self.sizertop.Add ( self.logoimg, 0, wx.ALIGN_TOP | wx.EXPAND ) self.sizertop.Add ( (100, 40), 0, wx.EXPAND ) self.sizertop.Add ( self.addbutton, 0 ) self.sizertop.Add ( (5, 40), 0, wx.EXPAND ) self.sizertop.Add ( self.delbutton, 0 ) self.sizertop.Add ( (15, 40), 0, wx.EXPAND ) self.sizertop.Add ( self.upbutton, 0) self.sizertop.Add ( (10, 40), 0, wx.EXPAND ) self.sizertop.Add ( self.helpbutton, 0) self.sizerbot.Add ( (15, 10), 0, wx.EXPAND ) self.sizerbot.Add ( self.message, 0, wx.ALIGN_LEFT | wx.EXPAND ) self.sizerbot.Add ( (10, 10), 0, wx.EXPAND ) self.sizerbot.Add ( self.hyper1, 0, wx.ALIGN_RIGHT | wx.EXPAND ) self.sizerbot.Add ( (15, 10), 0, wx.EXPAND ) self.sizermain.Add ((600, 10) ) self.sizermain.Add ( self.panel, 0, wx.EXPAND | wx.FIXED_MINSIZE ) self.sizermain.Add ((600, 10) ) self.sizermain.Add ( self.progpanel, 0, wx.ALIGN_CENTER | wx.FIXED_MINSIZE ) self.sizermain.Add ((600, 10) ) self.sizermain.Add ( self.imgpanel, 0, wx.ALIGN_CENTER | wx.FIXED_MINSIZE ) self.sizermain.Add ((600, 5) ) self.sizermain.Add ( wx.StaticLine(self, -1, size=(565,-1)), 0, wx.TOP | wx.ALIGN_CENTER | wx.FIXED_MINSIZE ) self.sizermain.Add ((600, 5) ) self.sizermain.Add ( self.footer, 0, wx.EXPAND | wx.FIXED_MINSIZE ) self.sizermain.Add ((600, 5) ) self.panel.SetSizer ( self.sizertop ) self.footer.SetSizer ( self.sizerbot ) self.SetSizer(self.sizermain) self.Show ( True ) self.maskimg = getMask() self.lastsel = None self.lastdesel = None self.shifted = False self.delimglist = [] self.pathlist = [] self.upimglist = [] self.upcount = 0 self.lastupcount = -1 self.uploading = False self.cancelnow = False # Catch all shift key presses self.panel.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown, self.panel) self.panel.Bind(wx.EVT_KEY_UP, self.OnKeyUp, self.panel) self.imgpanel.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown, self.imgpanel) self.imgpanel.Bind(wx.EVT_KEY_UP, self.OnKeyUp, self.imgpanel) self.footer.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown, self.footer) self.footer.Bind(wx.EVT_KEY_UP, self.OnKeyUp, self.footer) def initConfig(self): self.conf = Config() if self.TESTING: self.conf.setAPI('http://localhost/api') self.message.SetForegroundColour('ROYALBLUE1') self.message.SetLabel("checking network connection...") def connectLogin(self): self.connect = Connect() self.connect.setConfig(self.conf) wx.BeginBusyCursor() if self.connect.testConnect(): wx.EndBusyCursor() self.message.SetForegroundColour('ROYALBLUE1') self.message.SetLabel("network connected please login") self.tryLogin() else: wx.EndBusyCursor() self.message.SetForegroundColour(wxNamedColour('ORANGE1')) self.message.SetLabel("network failed. please try proxy") self.proxy = ProxyDialog(self) keeptrying = True while keeptrying: if self.proxy.showProxy(self): self.connect.setProxy(self.proxy.getProxyServer() + ':' + self.proxy.getProxyPort()) wx.BeginBusyCursor() window.message.SetForegroundColour('ROYALBLUE1') window.message.SetLabel("checking network connection...") if self.connect.testConnect(): wx.EndBusyCursor() self.message.SetForegroundColour('ROYALBLUE1') self.message.SetLabel("network connected. please login") if self.tryLogin(): keeptrying = False else: wx.EndBusyCursor() self.message.SetForegroundColour(wxNamedColour('ORANGE1')) if len(self.proxy.getProxyServer()) > 0: #FIXME add proper check self.message.SetLabel("proxy failed. please try again") else: self.message.SetLabel("network failed. please try proxy") else: self.Destroy() sys.exit(0) def tryLogin(self): wx.SafeYield() login = LoginDialog(self) if login.showLogin(self): self.username = login.getUser() self.password = login.getPassword() self.updateMessage() return True else: self.Destroy() sys.exit(0) def makeUploader(self): self.uploader = Uploader() self.uploader.setConfig(self.conf) self.uploader.setConnector(self.connect) self.uploader.setAccess(self.username, self.password) self.uploader.setWindow(self) def showUploadFailedMessage(self): self.message.SetForegroundColour('ORANGE1') if self.connect.getError() == '105' : self.showMessage( 'upload limit reached, ' + `len(self.upimglist)` + ' image(s) left to upload') elif self.connect.getError() == '106' : self.showMessage( 'server is busy, ' + `len(self.upimglist)` + ' image(s) left to upload') elif len(self.upimglist) == 1: self.showMessage( 'upload failed, ' + `len(self.upimglist)` + ' image left to upload') elif len(self.upimglist) > 1: self.showMessage( 'upload failed, ' + `len(self.upimglist)` + ' images left to upload') else: self.message.SetForegroundColour('GREY30') def showMessage(self, msg): self.message.SetForegroundColour('STEELBLUE1') if len(self.username) < 33: # prevent long username to overflow footer space self.message.SetLabel( self.username + ' | ' + msg ) else: self.message.SetLabel( msg ) def updateMessage(self): if len(self.upimglist) == 1: self.showMessage( `len(self.upimglist)` + ' image ready for upload') elif len(self.upimglist) > 1: self.showMessage( `len(self.upimglist)` + ' images ready for upload') else: self.showMessage( 'please add images to upload') def addImages(self, dlg): try: paths = dlg.GetPaths() self.conf.setLastPath(dlg.GetDirectory()) wx.BeginBusyCursor() wx.Yield() self.panel.Update() #self.progress.Show(True) #self.progress.SetRange( len(paths) ) i = 0 if len(paths) > 0: tilesize = self.conf.tileSize() for path in paths: i += 1 self.progress.SetValue(i) if path in self.pathlist: if self.conf.debug: print "Skip: %s" % path else: if self.conf.debug: print "Adding: %s" % path self.showMessage('adding image ' + str(i) + ' of ' + `len(paths)`) self.pathlist.append(path) img = wx.Image(path, wx.BITMAP_TYPE_ANY) imgtile = self.conf.imgSize(img.GetWidth(), img.GetHeight()) nw = imgtile[0] nh = imgtile[1] if nh and nw: img.Rescale(nw,nh) sizedimg = img.ConvertToBitmap() self.imgbutton = buttons.GenBitmapToggleButton( self.imgpanel, -1, None, size=tilesize ) self.imgbutton.SetToolTipString(path); self.imgbutton.SetBitmapLabel(sizedimg); self.maskimg.Rescale(nw,nh) maskbmp = self.maskimg.ConvertToBitmap() mask = wx.Mask(maskbmp, wx.BLACK) sizedimgtoggle = img.ConvertToBitmap() sizedimgtoggle.SetMask(mask); self.imgbutton.SetBitmapSelected(sizedimgtoggle) self.imgbutton.SetBackgroundColour("WHITE") #self.scrollsizer.Add( self.imgbutton ) #self.upimglist.append(self.imgbutton) self.scrollsizer.Prepend(self.imgbutton) self.upimglist.insert(0, self.imgbutton) self.Bind(wx.EVT_BUTTON, self.OnImgButton, self.imgbutton) self.imgbutton.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown, self.imgbutton) self.imgbutton.Bind(wx.EVT_KEY_UP, self.OnKeyUp, self.imgbutton) #redraw wx.Yield() #self.scrollsizer.Layout() #self.imgpanel.Layout() self.imgpanel.SetupScrolling() #self.imgpanel.Refresh() self.imgpanel.Update() self.upbutton.Enable(True) #if its disabled by delbutton #self.progress.SetRange(0) #self.progress.Show(False) self.scrollsizer.Layout() self.imgpanel.Layout() self.imgpanel.SetupScrolling() self.imgpanel.Refresh() self.imgpanel.Update() self.panel.Update() wx.EndBusyCursor() except: self.upbutton.Enable(True) #self.imgpanel.Show(True) self.progress.SetRange(0) self.progress.Show(False) self.imgpanel.SetupScrolling() self.imgpanel.Update() self.panel.Update() wx.EndBusyCursor() # All event handler functions def OnResult(self, event): # Gets events triggered from Uploader->Worker Thread if event.data is None: self.upimglist = self.upimglist[self.upcount:] #slice out uploaded self.uploader.closeThread() if self.cancelnow: self.postUpload(False) else: self.postUpload(True) elif event.data == 0: self.uploader.closeThread() self.postUpload(False) else: count = int(event.data) - 1 if(count == self.lastupcount): button = self.upimglist[count] self.showMessage('uploading image ' + str(count+1) + ' of ' + `len(self.upimglist)`) self.progress.SetValue((count*2)+2) self.scrollsizer.Remove(button) self.pathlist.remove(button.GetToolTip().GetTip()) #clear pathlist button.Destroy() self.scrollsizer.Layout() self.imgpanel.Layout() self.imgpanel.Refresh() self.imgpanel.Update() self.upcount += 1 else: #hack for progess update using same event self.progress.SetValue((count*2)+1) self.lastupcount = count def OnAddButton(self, event): wildcard = "All Supported Images|*.gif;*.jpg;*.jpeg;*.png|" \ "JPEG Images|*.jpg;*jpeg|" \ "GIF Images|*.gif|" \ "PNG Images|*.png" dlg = wx.FileDialog( self, message="Choose Images", defaultDir=self.conf.getLastPath(), defaultFile="", wildcard=wildcard, style=wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR) if dlg.ShowModal() == wx.ID_OK: self.imgpanel.Enable(False) self.imgpanel.Refresh() self.imgpanel.Update() self.addbutton.Enable(False) self.upbutton.Enable(False) self.delbutton.Enable(False) self.addImages(dlg) self.addbutton.Enable(True) self.upbutton.Enable(True) if len(self.delimglist) > 0: self.delbutton.Enable(True) self.imgpanel.Enable(True) self.imgpanel.Refresh() self.imgpanel.Update() self.updateMessage() dlg.Destroy() def OnDelButton(self, event): for button in self.delimglist: if self.conf.debug: print "Removing: %s" % button.GetToolTip().GetTip() self.scrollsizer.Detach(button) self.pathlist.remove(button.GetToolTip().GetTip()) #clear pathlist self.upimglist.remove(button) button.Destroy() #redraw wx.Yield() self.scrollsizer.Layout() self.imgpanel.Layout() self.imgpanel.Refresh() self.imgpanel.Update() self.imgpanel.SetupScrolling() self.delimglist = [] if len(self.pathlist) > 0: self.upbutton.Enable(True) if not len(self.delimglist): self.delbutton.Enable(False) else: self.upbutton.Enable(False) self.delbutton.Enable(False) self.updateMessage() def OnUpButton(self, event): connectionbroke = False self.scrollsizer.Layout() self.imgpanel.Layout() self.imgpanel.SetupScrolling() self.imgpanel.Enable(False) self.imgpanel.Refresh() self.imgpanel.Update() if self.uploading: if self.conf.debug: print "Cancel" self.cancelnow = True self.uploading = False self.upbutton.Enable(False) self.showMessage('cancelling upload..') self.uploader.abortUpload() else: for b in self.upimglist: # reset selected for delete b.SetBackgroundColour("WHITE") b.SetValue(False) self.upbutton.SetLabel("Cancel") self.upbutton.SetToolTipString("Cancel Upload") self.addbutton.Enable(False) self.delbutton.Enable(False) self.progress.Show(True) self.progress.SetRange(len(self.upimglist) * 2) self.upcount = 0 self.lastupcount = -1 self.uploading = True self.showMessage('starting upload...') self.uploader.uploadFiles(self.upimglist) def postUpload(self, connectionbroke): if self.cancelnow: self.cancelnow = False elif len(self.upimglist) == self.upcount: self.upimglist = [] # all uploaded else: self.upimglist = self.upimglist[self.upcount:] #slice out uploaded if len(self.upimglist) > 0: # upload cancelled in middle for button in self.upimglist: button.Update() self.upbutton.Enable(True) else: self.upbutton.Enable(False) #reset control flags self.uploading = False self.upcount = 0 self.delimglist = [] #always reset delete list once in upload self.upbutton.SetLabel("Upload") self.upbutton.SetToolTipString("Upload Images") self.upbutton.Enable(True) self.addbutton.Enable(True) self.progress.SetRange(0) self.progress.Enable(False) self.imgpanel.Enable(True) self.scrollsizer.Layout() self.imgpanel.Layout() self.imgpanel.SetupScrolling() self.imgpanel.Refresh() self.imgpanel.Update() if connectionbroke: self.showUploadFailedMessage() else: self.updateMessage() def OnImgButton(self, event): self.delbutton.Enable(True) button = event.GetEventObject() if button in self.delimglist: self.delimglist.remove(button) button.SetBackgroundColour("WHITE") self.multiDesel(button) self.lastdesel = button self.lastsel = None else: self.delimglist.append(button) button.SetBackgroundColour("ORANGE1") self.multiSel(button) self.lastsel = button self.lastdesel = None if len(self.delimglist) > 0: self.delbutton.Enable(True) else: self.delbutton.Enable(False) self.updateMessage() def multiDesel(self, button): if not self.shifted: return if self.lastdesel == None: return if not self.lastdesel in self.upimglist: return x = self.upimglist.index(self.lastdesel) y = self.upimglist.index(button) if x < 0 or y < 0: return if x < y: start = x end = y else: start = y end = x for i in range(len(self.upimglist)): if i > start and i < end: b = self.upimglist[i] if b in self.delimglist: # safe remove self.delimglist.remove(b) b.SetBackgroundColour("WHITE") b.SetValue(False) b.Update() wx.Yield() self.imgpanel.Refresh() self.imgpanel.Update() def multiSel(self, button): if not self.shifted: return if self.lastsel == None: return if not self.lastsel in self.upimglist: return x = self.upimglist.index(self.lastsel) y = self.upimglist.index(button) if x < 0 or y < 0: return if x < y: start = x end = y else: start = y end = x for i in range(len(self.upimglist)): if i > start and i < end: b = self.upimglist[i] if not b in self.delimglist: # safe append self.delimglist.append(b) b.SetBackgroundColour("ORANGE1") b.SetValue(True) b.Update() wx.Yield() self.imgpanel.Refresh() self.imgpanel.Update() def OnHelpButton(self, event): about = AboutDialog(self) about.showAbout(self.conf.version) about.Destroy() def OnKeyDown(self, evt): if evt.GetKeyCode() == wx.WXK_SHIFT: self.shifted = True def OnKeyUp(self, evt): if evt.GetKeyCode() == wx.WXK_SHIFT: self.shifted = False
def mouseUpdate(self): if pygame.time.get_ticks() >= self.mouseNext: if pygame.mouse.get_pressed()[0]: if self.state == "Main": for button in self.mainButtons: if button.checkClicked(pygame.mouse.get_pos()): self.state = button.click() elif self.state == "Login": for button in self.loginButtons: if button.checkClicked(pygame.mouse.get_pos()): self.state = button.click() if self.state == "Main": if self.connected: self.connected = False self.socket.send("STOP") if self.state == "Lobby": if self.ip.input != "" and self.port.input != "" and self.username.input != "" and self.password.input != "": message = self.username.input + ":" + self.password.input if not self.connected: try: self.socket = Connect(self.ip.input, int(self.port.input)) self.connected = True except: self.loginStatus = "No Server" self.state = "Login" if self.connected: self.socket.send("LOG:" + message) self.state = "Login" self.loginStatus = "Waiting" # modifiedMessage = self.socket.receive() # modifiedMessage = modifiedMessage.split(":") # self.loginStatus = "" # if modifiedMessage[0] == "Invalid Password": # self.loginStatus = "Invalid Password" # self.state = "Login" # elif modifiedMessage[0] == "Success": # self.connected = False # self.state = "Lobby" # elif modifiedMessage[0] == "": # self.loginStatus = "Waiting" # self.state = "Login" else: self.state = "Login" self.loginStatus = "Missing Field(s)" self.ip.checkClicked(pygame.mouse.get_pos()) self.port.checkClicked(pygame.mouse.get_pos()) self.username.checkClicked(pygame.mouse.get_pos()) self.password.checkClicked(pygame.mouse.get_pos()) self.mouseNext = pygame.time.get_ticks() + self.mouseDelay
class Main_Menu(): def __init__(self, screen, screenw, screenh, spriteList, soundManager): self.sprites = spriteList self.screen = screen self.screenw = screenw self.screenh = screenh self.soundManager = soundManager self.state = "Main" self.mainButtons = [] self.mainButtons.append(Button(self.screen, self.sprites.getSprite("login"), self.sprites.getSprite("loginHighlighted"), 368, 350, 281, 68, "Login", 'Start Button.ogg', soundManager)) self.mainButtons.append(Button(self.screen, self.sprites.getSprite("start"), self.sprites.getSprite("startHighlighted"), 368, 442, 281, 68, "Game", 'Start Button.ogg', soundManager)) self.mainButtons.append(Button(self.screen, self.sprites.getSprite("exit"), self.sprites.getSprite("exitHighlighted"), 368, 534, 281, 68, "Exit", 'Exit.ogg', soundManager)) self.fontsize = 30 self.font = pygame.font.Font(os.path.join('Fonts', 'nasalization-rg.ttf'), self.fontsize) self.loginButtons = [] self.ip = textInput(self.screen, "Server IP", (50, 30), (self.font.get_height() * 8), 50, 15) self.port = textInput(self.screen, "Port", (300 + (self.font.get_height() * 8), 30), (self.font.get_height() * 5), 50, 5) self.username = textInput(self.screen, "Username", (self.screenw/2 - 200, 130), (self.font.get_height() * 8), 50, 8) self.password = textInput(self.screen, "Password", (self.screenw/2 - 200, 230), (self.font.get_height() * 8), 50, 8, True) self.loginButtons.append(Button(self.screen, self.sprites.getSprite("login"), self.sprites.getSprite("loginHighlighted"), 368, 442, 281, 68, "Lobby", 'Start Button.ogg', soundManager)) self.loginButtons.append(Button(self.screen, self.sprites.getSprite("exit"), self.sprites.getSprite("exitHighlighted"), 368, 534, 281, 68, "Main", 'Exit.ogg', soundManager)) self.mouseDelay = 50 self.mouseNext = pygame.time.get_ticks() self.connected = False #for server self.socket = None self.loginStatus = "" def draw(self): if self.state == "Main": self.screen.blit(self.sprites.getSprite("titlescreen"), (0, 0)) for button in self.mainButtons: button.draw() elif self.state == "Login": self.screen.blit(self.sprites.getSprite("titlescreenbg"), (0, 0)) self.ip.draw() self.port.draw() self.username.draw() self.password.draw() if self.loginStatus == "Invalid Password": self.screen.blit(self.font.render("Wrong Password. Try again.", True, pygame.Color(255,255,255)),(300,self.screenh/2 - 100)) elif self.loginStatus == "No Server": self.screen.blit(self.font.render("Could not reach server. Wrong Info/Poor connection.", True, pygame.Color(255,255,255)),(100,self.screenh/2 - 100)) elif self.loginStatus == "Waiting": self.screen.blit(self.font.render("Waiting for server.", True, pygame.Color(255,255,255)),(self.screenw/2 - (len("Invalid Format.") * 30)/4,self.screenh/2 - 100)) elif self.loginStatus == "Missing Field(s)": self.screen.blit(self.font.render("Missing Field(s).", True, pygame.Color(255,255,255)),(self.screenw/2 - (len("Invalid Format.") * 30)/4,self.screenh/2 - 100)) for button in self.loginButtons: button.draw() def mouseUpdate(self): if pygame.time.get_ticks() >= self.mouseNext: if pygame.mouse.get_pressed()[0]: if self.state == "Main": for button in self.mainButtons: if button.checkClicked(pygame.mouse.get_pos()): self.state = button.click() elif self.state == "Login": for button in self.loginButtons: if button.checkClicked(pygame.mouse.get_pos()): self.state = button.click() if self.state == "Main": if self.connected: self.connected = False self.socket.send("STOP") if self.state == "Lobby": if self.ip.input != "" and self.port.input != "" and self.username.input != "" and self.password.input != "": message = self.username.input + ":" + self.password.input if not self.connected: try: self.socket = Connect(self.ip.input, int(self.port.input)) self.connected = True except: self.loginStatus = "No Server" self.state = "Login" if self.connected: self.socket.send("LOG:" + message) self.state = "Login" self.loginStatus = "Waiting" # modifiedMessage = self.socket.receive() # modifiedMessage = modifiedMessage.split(":") # self.loginStatus = "" # if modifiedMessage[0] == "Invalid Password": # self.loginStatus = "Invalid Password" # self.state = "Login" # elif modifiedMessage[0] == "Success": # self.connected = False # self.state = "Lobby" # elif modifiedMessage[0] == "": # self.loginStatus = "Waiting" # self.state = "Login" else: self.state = "Login" self.loginStatus = "Missing Field(s)" self.ip.checkClicked(pygame.mouse.get_pos()) self.port.checkClicked(pygame.mouse.get_pos()) self.username.checkClicked(pygame.mouse.get_pos()) self.password.checkClicked(pygame.mouse.get_pos()) self.mouseNext = pygame.time.get_ticks() + self.mouseDelay def update(self): self.mouseUpdate() if self.state == "Main": for button in self.mainButtons: button.checkHover(pygame.mouse.get_pos()) return "Menu" elif self.state == "Login": if self.connected: message = None while message != "": message = self.socket.receive() if message != None: modifiedMessage = message.split(":") if modifiedMessage[0] == "Invalid Password": self.loginStatus = "Invalid Password" self.state = "Login" elif modifiedMessage[0] == "Success": self.loginStatus = "" self.connected = False self.state = "Lobby" else: if self.loginStatus == "Waiting": #self.state = "Login" self.socket.send("CHECKLOG") for button in self.loginButtons: button.checkHover(pygame.mouse.get_pos()) self.ip.update() self.port.update() self.username.update() self.password.update() return "Menu" else: return self.state