How to use logged_in method in autotest

Best Python code snippet using autotest_python

cgs.py

Source:cgs.py Github

copy

Full Screen

1import pygame as pg, sys, pickle2import cgs_checkers, cgs_othello, cgs_connect4, cgs3from passlib.hash import pbkdf2_sha2564import gspread5from oauth2client.service_account import ServiceAccountCredentials6import ast7def left_panel_event(game, screen, event, logged_in, mode, difficulty, board, turn, game_over):8 """This function is not used in the cgs file but is used in all of the other games so is placed here to reference9 universally. It deals with any event in the left panel that occurs in any of the games."""10 def reset_progress(mode, logged_in, name):11 """Function that resets the user's currently saved game progress in their profile and then dumps that info back12 into the general game data."""13 logged_in['current_' + name][0] = []14 if mode == 0: # if human mode than player 1 starts game15 logged_in['current_' + name][1] = 116 elif mode == 1: # if AI mode then player 2 (AI) starts game17 logged_in['current_' + name][1] = 018 # sets names and files depending on which game function was called from19 if game == 0:20 name = 'connect4'21 file = cgs_connect422 elif game == 1:23 name = 'othello'24 file = cgs_othello25 elif game == 2:26 name = 'checkers'27 file = cgs_checkers28 if 250 < event.pos[1] < 315: # NEW GAME button clicked29 reset_progress(mode, logged_in, name) # function that resets the user's current saved game position30 dump(logged_in)31 file.main(screen) # calls the main function of game called from to restart the game32 elif 150 < event.pos[1] < 215: # EXIT button is clicked33 if not game_over: # saves data with function in cgs b4 exiting34 logged_in = cgs.save_data(board, turn, game, logged_in, difficulty, mode=mode)35 cgs.dump(logged_in) # dumps the newly updated user account36 cgs.main() # calls cgs.main function to return to game option window (homepage when logged in)37 elif 475 < event.pos[1] < 510: # user wants to change MODE38 '''All data from ongoing game is lost when user switches mode'''39 if 10 < event.pos[0] < 95: # user clicks on HUMAN40 if mode == 1: # if the mode is currently AI then41 mode = 0 # switch mode to human42 logged_in['current_' + name][2] = mode # save mode to profile43 logged_in['current_' + name][3] = 0 # save difficulty to profile44 reset_progress(mode, logged_in, name) # function that resets the user's current saved game position45 cgs.dump(logged_in) # saves edited logged_in data to file46 file.main(screen) # calls the main function to restart the game47 elif 95 < event.pos[0] < 180: # user clicks on AI48 if mode == 0: # if the mode is currently HUMAN then49 mode = 1 # switch mode to AI50 logged_in['current_' + name][2] = mode # save mode to profile51 logged_in['current_' + name][3] = 2 # save difficulty to profile52 reset_progress(mode, logged_in, name) # reset progress in account53 cgs.dump(logged_in) # saves edited logged_in data to file54 file.main(screen) # calls the main function to restart the game55 elif 675 < event.pos[1] < 710: # User changes difficulty56 if mode == 1: # if in AI mode57 if 10 < event.pos[0] < 64:58 if difficulty != 2:59 difficulty = 2 # changes difficulty and saves data60 logged_in['current_' + name][3] = difficulty # save difficulty to profile61 cgs.dump(logged_in)62 if 64 < event.pos[0] < 128: # user clicks on AI63 if difficulty != 4:64 difficulty = 4 # changes difficulty and saves data65 logged_in['current_' + name][3] = difficulty # save difficulty to profile66 cgs.dump(logged_in)67 if 128 < event.pos[0] < 190: # user clicks on AI68 if difficulty != 6:69 difficulty = 6 # changes difficulty and saves data70 logged_in['current_' + name][3] = difficulty # save difficulty to profile71 cgs.dump(logged_in)72 cgs.draw_records(screen, game, mode, logged_in,73 difficulty) # draws left panel of game suite from cgs to re-draw updated difficulty74 return mode, difficulty75def draw_records(screen, game, mode, logged_in, difficulty):76 """This function is not used in the cgs file but is used in all of the other games so is placed here to reference77 universally. It draws the left panel of each game. It accepts the screen the game is using and all of the data78 printed on left panel."""79 pg.draw.rect(screen, (0, 0, 0), (0, 0, 200, 900)) # draws left black box80 make_fonts_global()81 pg.draw.rect(screen, (0, 150, 0), (10, 150, 180, 65)) # draws green new game box82 new_game = font50.render("New Game", 1, (250, 250, 250))83 pg.draw.rect(screen, (0, 150, 0), (10, 250, 180, 65)) # draws green EXIT box84 exit = font50.render("EXIT", 1, (250, 250, 250))85 screen.blit(exit, (65, 170))86 screen.blit(new_game, (12, 270))87 games = ['connect4', 'othello', 'checkers'] # game parameter --> (C4 = 0, O = 1, C= 2)88 record = font28.render('(Wins, Losses, Ties)', 1, (250, 50, 50), (0, 0, 0)) # shows counter place holders89 screen.blit(record, (8, 350))90 twoplayer = font20.render('vs Human', 1, (200, 200, 200), (0, 0, 0)) # human column for counter91 screen.blit(twoplayer, (30, 375))92 ai = font20.render('vs AI', 1, (200, 200, 200), (0, 0, 0)) # ai column for counter93 screen.blit(ai, (135, 375))94 display = str(games[game]) + '_record' # alters record based on game95 record = font28.render(str(logged_in[display]), 1, (250, 0, 0), (0, 0, 0))96 screen.blit(record, (30, 395)) # shows human record97 record = font28.render(str(logged_in[display + '_ai']), 1, (250, 0, 0), (0, 0, 0))98 screen.blit(record, (118, 395)) # shows AI record99 mode_type = font30.render('MODE:', 1, (250, 250, 250), (0, 0, 0)) # mode selector (human/AI)100 screen.blit(mode_type, (67, 445))101 pg.draw.rect(screen, (90, 150, 240), (10, 475, 180, 35)) # blue box for mode selector102 pg.draw.rect(screen, (240, 240, 90), (95, 475, 2, 35)) # line dividing mode selector options103 if mode == 0: # sets color for mode selector if in human mode104 ai_color = (250, 250, 250)105 human_color = (240, 240, 90)106 x1 = 10107 x2 = 95108 else: # sets color for mode selector if in AI mode109 ai_color = (240, 240, 90)110 human_color = (250, 250, 250)111 x1 = 95112 x2 = 190113 human = font30.render('HUMAN', 1, human_color) # puts text of human/AI into mode selector114 screen.blit(human, (14, 484))115 ai = font45.render('AI', 1, ai_color)116 screen.blit(ai, (125, 480))117 pg.draw.aalines(screen, (240, 240, 90), True, ((x1, 475),118 (x1, 510),119 (x2, 510),120 (x2, 475)), 1) # highlights which mode is active121 if difficulty > 0:122 mode_type = font30.render('DIFFICULTY:', 1, (250, 250, 250), (0, 0, 0)) # shows difficulty selector123 screen.blit(mode_type, (42, 650))124 pg.draw.rect(screen, (75, 0, 130), (10, 675, 180, 35)) # draws purple difficulty buttons125 easy = font50.render('*', 1, (240, 240, 90)) # first level126 med = font50.render('**', 1, (240, 240, 90)) # second level127 hard = font50.render('***', 1, (240, 240, 90)) # third level128 screen.blit(easy, (32, 685))129 screen.blit(med, (86, 685))130 screen.blit(hard, (143, 685))131 pg.draw.rect(screen, (90, 150, 240), (64, 675, 2, 35)) # dividers between difficulty options132 pg.draw.rect(screen, (90, 150, 240), (128, 675, 2, 35))133 # alters coordinates for highlighting box based on difficulty134 if difficulty == 2:135 x1 = 10136 x2 = 64137 elif difficulty == 4:138 x1 = 64139 x2 = 128140 elif difficulty == 6:141 x1 = 128142 x2 = 190143 pg.draw.aalines(screen, (90, 150, 240), True, ((x1, 675),144 (x1, 710),145 (x2, 710),146 (x2, 675)), 1) # highlights current difficulty box147def dump(logged_in):148 """This function is not directly used in the cgs file but is used in all of the other games so is placed here to149 reference universally. It accepts the logged_in variable/dictionary that is edited throughout the game and replaces150 whatever is in the saved file logged_in with the edited variable. This function ensures safe saving of progress.151 It is similar to the serial function but accepts a parameter instead of using a global variable."""152 pickle_out_logged_in = open("logged_in", "wb") # opens logged_in file that holds currently logged in153 pickle.dump(logged_in, pickle_out_logged_in) # replaces whatever is there with last saved data from game154 pickle_out_logged_in.close() # closes file155# Above functions not directly used in cgs.py file156def draw_homescreen(box=None):157 """This function sets the window caption and also draws the homepage screen before selecting login or sign up"""158 pg.display.set_caption('CGS')159 pg.draw.rect(screen, (0, 0, 0), (0, 0, 700, 800)) # black box160 pg.draw.rect(screen, (255, 0, 0), (20, 20, 50, 50)) # red exit box161 exit = font85.render("X", 1, (250, 250, 250))162 screen.blit(exit, (25, 19))163 exit = font50.render("CAPSTONE GAME SUITE", 1, (250, 220, 90)) # yellow label164 screen.blit(exit, (135, 30))165 if box == 'login': # if the166 pg.draw.rect(screen, (0, 100, 255), (140, 310, 140, 50)) # if hover over login then draw blue box around it167 elif box == 'create_account':168 pg.draw.rect(screen, (0, 100, 255), (330, 310, 275, 50)) # if hover over create acnt draw blue box around it169 login = font50.render("Login", 1, (250, 250, 250))170 screen.blit(login, (165, 320))171 exit = font50.render("Create Account", 1, (250, 250, 250))172 screen.blit(exit, (340, 320))173def draw_main_page():174 """This function draws the main menu page once the user is logged in. It displays the users records for each game,175 and has buttons to commence game play for each of the three games"""176 pg.draw.rect(screen, (0, 0, 0), (0, 80, 700, 800)) # black box177 name = font85.render(str('@' + logged_in['username']), 1, (200, 200, 200))178 screen.blit(name, (50, 100)) # @NAME179 pg.draw.rect(screen, (100, 255, 0), (550, 97, 95, 30)) # green box for log out button180 logout = font35.render("Logout", 1, (250, 250, 250))181 screen.blit(logout, (555, 100))182 record = font35.render('(Wins, Losses, Ties)', 1, (250, 50, 50)) # shows record place holders183 screen.blit(record, (410, 185))184 ai = font20.render('vs AI', 1, (200, 200, 200)) # small sub text185 screen.blit(ai, (560, 215))186 twoplayer = font20.render('vs Human', 1, (200, 200, 200)) # small sub text187 screen.blit(twoplayer, (440, 215))188 pg.draw.rect(screen, (0, 65, 0), (180, 250, 210, 65)) # green othello box189 exit = font50.render("OTHELLO", 1, (250, 250, 250))190 screen.blit(exit, (202, 270))191 pg.draw.rect(screen, (0, 100, 255), (180, 400, 210, 65)) # blue connect4 box192 exit = font50.render("CONNECT 4", 1, (250, 250, 250))193 screen.blit(exit, (185, 420))194 pg.draw.rect(screen, (90, 45, 0), (180, 550, 210, 65)) # red checkers box195 exit = font50.render("CHECKERS", 1, (250, 250, 250))196 screen.blit(exit, (185, 570))197 record = font35.render(str(logged_in['othello_record']), 1, (250, 0, 0)) # othello record198 screen.blit(record, (430, 270))199 record = font35.render(str(logged_in['othello_record_ai']), 1, (250, 0, 0)) # othello AI record200 screen.blit(record, (540, 270))201 record = font35.render(str(logged_in['connect4_record']), 1, (250, 0, 0)) # connect4 record202 screen.blit(record, (430, 420))203 record = font35.render(str(logged_in['connect4_record_ai']), 1, (250, 0, 0)) # connect4 AI record204 screen.blit(record, (540, 420))205 record = font35.render(str(logged_in['checkers_record']), 1, (250, 0, 0)) # checkers record206 screen.blit(record, (430, 570))207 record = font35.render(str(logged_in['checkers_record_ai']), 1, (250, 0, 0)) # checkers AI record208 screen.blit(record, (540, 570))209def save_data(board, turn, game, logged_in, difficulty, mode):210 """This function takes the current board from any game and whose turn it is and saves it to their account. It is211 called when the user exits a game in the middle (AUTO-SAVE FEATURE)"""212 if game == 0: # if the function was called from connect4213 if board != [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0],214 [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]: # generic connect4 board215 logged_in['current_connect4'][0] = board # saves progress in profile216 logged_in['current_connect4'][1] = turn217 logged_in['current_connect4'][2] = mode218 logged_in['current_connect4'][3] = difficulty219 elif game == 1:220 if board != [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],221 [0, 0, 0, 2, 1, 0, 0, 0], [0, 0, 0, 1, 2, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],222 [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]: # generic othello board223 logged_in['current_othello'][0] = board # saves progress in profile224 logged_in['current_othello'][1] = turn225 logged_in['current_othello'][2] = mode226 logged_in['current_othello'][3] = difficulty227 elif game == 2:228 if board != [[0, 1, 0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0, 1],229 [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [2, 0, 2, 0, 2, 0, 2, 0],230 [0, 2, 0, 2, 0, 2, 0, 2], [2, 0, 2, 0, 2, 0, 2, 0]]: # generic checkers board231 logged_in['current_checkers'][0] = board # saves progress in profile232 logged_in['current_checkers'][1] = turn233 logged_in['current_checkers'][2] = mode234 logged_in['current_checkers'][3] = difficulty235 return logged_in # returns the edited/updated account dictionary (who ever is currently logged in)236def get_data_from_drive(username):237 """After a user logs in, this function is called to retrieve their data from their profile and turn it into a238 usable format for their stay in the app"""239 pos = sheet.find(username) # finds their designated row in sheet240 row = sheet.row_values(pos.row) # gets all of the values in their row241 variables = ['username', 'password', 'connect4_record_ai', 'connect4_record', 'checkers_record_ai',242 'checkers_record', 'othello_record_ai', 'othello_record', 'current_checkers', 'current_connect4',243 'current_othello'] # list of corresponding/parallel variable names244 dictionary = {} # blank dictionary to add their data to245 for i in range(len(variables)):246 if i > 1: # sets each variable in list equal to corresponding value from sheet247 dictionary[variables[i]] = ast.literal_eval(row[i + 1]) # (uses module to convert string to literal)248 else:249 dictionary[variables[i]] = row[i + 1]250 return dictionary251def submit_data(username, password):252 """This function accepts the data (username and password) that the user has provided in the login process and253 cross references it with the google sheet to see if their account exists, if they are logged in somewhere else254 already or if they entered the wrong password."""255 if username.lower() in users: # if the global value of users (list of all users in sheet) contains this username:256 pos = sheet.find(username) # then find the row that the user's data is in257 if sheet.cell(pos.row, 13).value == '0': # if they are not logged in elsewhere then check password258 if not pbkdf2_sha256.verify(password, sheet.cell(pos.row, 3).value):259 # cross references password entered with de-hashed one their account on sheet260 return [False, 'Incorrect Password'] # if their password is wrong, return error message261 else: # if their password is correct then update column of sheet stating that they are logged in somewhere262 sheet.update_cell(pos.row, 13, '1')263 return [True, "You're in!"]264 else: # if last column of their profile is 1 then they are logged in elsewhere265 return [False, 'Already logged in somewhere']266 else: # they do not have an account267 return [False, "No profile associated with that username. Try again"]268def create_account(name, password):269 """This function accepts the text for the username and password that the user entered. It then creates a profile270 for them."""271 if len(name) > 7 or len(name) < 2: # if username length is out of boundary, return error272 return [False, 'Username must be longer than 2 characters and less than 7']273 elif name.lower() in users: # if username already in database then return error274 return [False, 'User already exists. Try Logging In']275 else:276 username = name # username variable is the submitted name277 name = name.lower() # name variable is lowercase version of submitted name278 hash_key = pbkdf2_sha256.hash(password) # hashed version of password279 # generic data for beginner account280 data = [name, str(username), str(hash_key), str([0, 0, 0]), str([0, 0, 0]), str([0, 0, 0]), str([0, 0, 0]),281 str([0, 0, 0]), str([0, 0, 0]), str([[], 1, 0, 0]), str([[], 1, 0, 0]), str([[], 1, 0, 0]), 1]282 row = len(sheet.col_values(1)) + 1 # designate next available row for new user283 cell_list = sheet.range('A' + str(row) + ':M' + str(row)) # Selects a cell range284 for i in range(len(cell_list)): # updates local version of sheet with corresponding data285 cell_list[i].value = data[i]286 sheet.update_cells(cell_list) # pastes local edited sheet to web one287 return [True, '']288def serial(exit=None):289 """This function serials the user data into the local logged_in file"""290 pickle_out_logged_in = open("logged_in", "wb") # opens the logged_in file291 if exit: # if the optional exit parameter is specified then dump False (no user data) and the close app292 pickle.dump(False, pickle_out_logged_in)293 pickle_out_logged_in.close()294 sys.exit()295 else: # otherwise pickle out their data (used for closing games but not entire app)296 pickle.dump(logged_in, pickle_out_logged_in)297 pickle_out_logged_in.close()298def login():299 """This function is called various times throughout the logging in process and creating account process. It draws300 the page according to the clicks that it the screen resopnds to."""301 pg.draw.rect(screen, (250, 250, 250), (0, 80, 700, 800)) # white box background302 pg.draw.rect(screen, (88, 140, 170), (30, 100, 60, 25)) # blue box for back button303 arrow = font50.render("<---", 1, (250, 250, 250)) # back button304 screen.blit(arrow, (32, 93))305 pg.draw.rect(screen, (190, 190, 190), (250, 197, 350, 40)) # grey box for text username306 username = font50.render("USERNAME:", 1, (0, 0, 0))307 screen.blit(username, (25, 200))308 if typing == 'username': # if user is typing then highlight box309 pg.draw.aalines(screen, (250, 220, 90), True, ((250, 195),310 (250, 235),311 (600, 235),312 (600, 195)), 1)313 pg.draw.rect(screen, (190, 190, 190), (250, 277, 350, 40)) # grey box for text password314 password = font50.render("PASSWORD:", 1, (0, 0, 0))315 screen.blit(password, (25, 280))316 if typing == 'password': # if user is typing then highlight box317 pg.draw.aalines(screen, (250, 220, 90), True, ((250, 275),318 (250, 315),319 (600, 315),320 (600, 275)), 1)321 if len(password_text) > 0: # if the text entered for password is longer than 0, show the (show/hide) button322 pg.draw.rect(screen, (220, 220, 220), (550, 278, 49, 38)) # show/hide button background323 if show_text: # if text is being shown, give hide option324 text = font20.render(" HIDE", 1, (200, 100, 50))325 else: # if text is not being shown then give show option326 text = font20.render("SHOW", 1, (200, 100, 50))327 screen.blit(text, (555, 290))328 pg.draw.rect(screen, (20, 250, 20), (250, 363, 145, 40)) # draw green submit button329 if loggining_in: # alter text depending on which option you chose330 username = font40.render("Login", 1, (250, 250, 250))331 elif creating_account:332 username = font40.render("Sign Up", 1, (250, 250, 250))333 screen.blit(username, (273, 370))334def save_progress():335 """This function takes the user's records and saved game progress and pastes it into their account file on the336 google sheet."""337 if logged_in != False: # if the user is still logged in338 data = [*logged_in.values()] # then turn the dictionary of their data into a list339 data.append('0') # add a zero for the status column of the drive340 row = sheet.find(data[0]) # find their name in the drive and store the row of their name341 # Select a cell range to paste their content to342 cell_list = sheet.range('B' + str(row.row) +':M' + str(row.row))343 # Update values344 for i in range(len(cell_list)):345 cell_list[i].value = str(data[i]) # updates temporary local sheet346 sheet.update_cells(cell_list) # replaces online sheet with it347def setup_drive():348 """This function sets (with the help of service account credentials)up the global variable that modifies the349 google sheet"""350 global sheet351 scope = ['https://www.googleapis.com/auth/drive'] # link of authorization352 credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope) # credentials of sheet353 client = gspread.authorize(credentials) # authorizes credentials354 sheet = client.open('CGS_DATA').sheet1 # opens the sheet up into the sheet variable355def make_fonts_global():356 """This font instantiates the font options as global variables to be used throughout the program."""357 global font25, font40, font85, font50, font35, font20, font28, font45, font30358 pg.font.init() # sets up fonts within pygame359 font40 = pg.font.SysFont('Comic Sans MS', 40)360 font25 = pg.font.SysFont('Comic Sans MS', 25)361 font85 = pg.font.SysFont('Comic Sans MS', 85)362 font50 = pg.font.SysFont('Comic Sans MS', 50)363 font35 = pg.font.SysFont('Comic Sans MS', 35)364 font20 = pg.font.SysFont('Comic Sans MS', 20)365 font28 = pg.font.SysFont('Comic Sans MS', 28)366 font45 = pg.font.SysFont('Comic Sans MS', 45)367 font30 = pg.font.SysFont('Comic Sans MS', 30)368def main():369 """This function is called when the app is opened and is the heart of the entire app. It sets default variables370 and then opens infinite loop that app is ran in."""371 global screen, game_over, logged_in, users, typing, loggining_in, creating_account, password_text, show_text372 make_fonts_global() # makes fonts global throughout373 screen = pg.display.set_mode((700, 800)) # sets screen size374 loggining_in, creating_account, typing, show_text = False, False, False, False # sets variables to defaults375 username, password, password_text, typing = '', '', '', '' # sets temp text variables to blank376 setup_drive() # sets up google sheet variable with credentials377 users = sheet.col_values(1) # gets list of all user names378 try:379 pickle_in_logged_in = open("logged_in", "rb") # try to pickle in logged_in data from local file380 logged_in = pickle.load(pickle_in_logged_in)381 except FileNotFoundError:382 logged_in = False # if file does not exist then nobody is logged in383 draw_homescreen() # draws the home screen before user selects login or create_account384 while True: # opens infinite loop that app runs in385 for event in pg.event.get():386 if logged_in != False: # IF THE USER IS LOGGED IN387 draw_main_page() # draws main menu with all three game options388 if event.type == pg.MOUSEBUTTONDOWN:389 if 200 < event.pos[0] < 450: # if user selects to play game390 if 250 < event.pos[1] < 315: # reformat screen and start othello game391 pg.display.set_mode((900, 800))392 cgs_othello.main(screen)393 elif 400 < event.pos[1] < 465: # reformat screen and start connect4 game394 pg.display.set_mode((900, 800))395 cgs_connect4.main(screen)396 elif 550 < event.pos[1] < 615:397 pg.display.set_mode((900, 800)) # reformat screen and start othello game398 cgs_checkers.main(screen)399 elif 550 < event.pos[0] < 645 and 97 < event.pos[1] < 127: # if user opts to log out400 save_progress() # save their progress to the google drive401 logged_in = False # set logged_in to False402 serial() # serial the logged_in variable out into its local file403 draw_homescreen() # draw the original homes creen with options to log in or create account404 else: # IF THE USER IS NOT LOGGED IN405 if not loggining_in and not creating_account: # IF THE USER IS ON HOMEPAGE406 if event.type == pg.MOUSEMOTION: # if user hovers over option407 if 140 < event.pos[0] < 280 and 310 < event.pos[1] < 360:408 draw_homescreen('login') # if user hovers over login then it draws login page409 elif 330 < event.pos[0] < 605 and 310 < event.pos[1] < 360:410 draw_homescreen('create_account') # if user hovers on create account then draws that page411 if event.type == pg.MOUSEBUTTONDOWN:412 if 310 < event.pos[1] < 360:413 if 140 < event.pos[0] < 280:414 # if user clicks login then set variable415 loggining_in = True416 elif 330 < event.pos[0] < 605:417 # if user clicks create account then set variable418 creating_account = True419 login() # call login function420 elif loggining_in or creating_account: # IF THE USER IS LOGGING IN421 if event.type == pg.MOUSEBUTTONDOWN:422 if 250 < event.pos[0] < 600: # if user clicks on text box423 if 200 < event.pos[1] < 240:424 typing = 'username' # if user clicks username textbox then set variable425 elif 277 < event.pos[1] < 317:426 typing = 'password' # if user clicks password textbox then set variable427 if event.pos[0] > 545 and len(password_text) > 0: # if click on show/hide button428 if show_text: # flip the button's state if clicked429 show_text = False430 else:431 show_text = True432 else: # otherwise user has de-selected typing box433 typing = ''434 login() # re-calls login function to re-draw page without text box highlighting435 if 30 < event.pos[0] < 90 and 100 < event.pos[1] < 125: # if user clicks back button then exit436 main()437 if 250 < event.pos[0] < 395 and 364 < event.pos[1] < 404: # if user clicks submit438 if loggining_in: # if user is logging in then submit their data439 response = submit_data(username.lower(), password) # submits user data and gets status440 show_text = False # re-hide their text441 if response[0]: # if they have account and entered data correctly442 loggining_in = False # user is no longer logging in443 logged_in = get_data_from_drive(username) # gets dictionary of data to be used444 # sets variable to data from profile that will be edited during their stay445 serial() # saves their newly logged_in state (and data) to the local file446 else:447 error = font28.render(str(response[1]), True, (250, 0, 0), (250,250, 250))448 screen.blit(error, (100, 485)) # if wrong info entered print error message449 username, password, password_text = '', '', '' # reset type variables to empty450 elif creating_account:451 response = create_account(username, password) # call function to create account452 if not response[0]: # if error in creating account453 username, password, password_text = '', '', '' # clear text boxes454 error = font28.render(str(response[1]), True, (250, 0, 0), (250, 250, 250))455 screen.blit(error, (100, 485)) # print error message456 else:457 creating_account = False # no longer creating account458 logged_in = get_data_from_drive(username) # gets dictionary of data to be used459 serial() # saves their newly logged_in state (and data) to the local file460 elif event.type == pg.KEYDOWN: # if user clicks key on keyboard461 if event.key == pg.K_ESCAPE:462 main() # if user clicks escape then exit to main/home screen463 if event.key == pg.K_BACKSPACE: # if user clicks backspace464 if typing == 'username': # and they are typing in username textbox465 username = username[:-1] # then delete one character from username variable466 elif typing == 'password': # or they are typing in password textbox467 password = password[:-1] # then delete one character from password variable468 password_text = password_text[:-1] # and delete one character from text variable (***)469 else:470 break471 elif event.key == pg.K_TAB: # if user clicks tab or enter472 if typing == 'username': # if they are typing username then switch to password473 typing = 'password'474 login() # re-draw board475 else: # otherwise (if they are typing) add the character to their textbox476 if typing == 'username':477 username += event.unicode478 elif typing == 'password':479 password += event.unicode480 if event.key != pg.K_LSHIFT and event.key != pg.K_RSHIFT:481 password_text += '*' # if they hit any char except shift, add it to *** counter482 else:483 break484 login() # redraw login page485 username_blit = font45.render(str(username), True, (250, 250, 250)) # paste username486 if show_text: # paste password or *** version487 password_blit = font45.render(str(password), True, (250, 250, 250))488 else:489 password_blit = font45.render(str(password_text), True, (250, 250, 250))490 screen.blit(username_blit, (260, 203))491 screen.blit(password_blit, (260, 283))492 if event.type == pg.QUIT: # if user tries to quit then save progress to drive and serial out493 save_progress()494 serial(True)495 if event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE:496 main() # if they click497 if event.type == pg.MOUSEBUTTONDOWN: # if user clicks app's red X button then save progress and serial out498 if 20 < event.pos[0] < 70 and 20 < event.pos[1] < 70:499 save_progress()500 serial(True)501 pg.display.update() # update screen502if __name__ == '__main__':...

Full Screen

Full Screen

sist_gest.py

Source:sist_gest.py Github

copy

Full Screen

1# encoding=utf-82import sist_gest_functs, config_vars3from flask import render_template, request, url_for, redirect, session, g, json4from flaskext.mysql import MySQL5from flask_mail import Mail, Message #pip install Flask-Mail6import datetime, os7import MySQLdb as db8app = config_vars.app_conf()9mail = Mail(app)10mysql = MySQL()11mysql.init_app(app)12#Funcion index, llama a la funcion chequear usuario y retorna las vistas correspondientes13@app.route('/', methods=['GET','POST'])14def index():15 if(request.method == 'POST'): return sist_gest_functs.index_funct(request.form['username'], request.form['password'], session)16 else: return sist_gest_functs.index_funct()17@app.route('/seleccion_persona', methods=['POST'])18def seleccionarPersona():19 if(session.get('logged_in')):20 if request.form['ano'] != None: session['ano_esc'] = request.form['real_id']21 return render_template("seleccionar_tipo.html")22#Funcion seleccionar que muestra la ventana luego del logueo23@app.route('/seleccion')24def seleccionar():25 return sist_gest_functs.selec_funct(session)26#Funcion seleccionar que muestra la ventana luego del logueo27@app.route('/configuracion', methods=['GET'])28def configuracion():29 if(session.get('logged_in')): return render_template("configuracion.html")30 return redirect(url_for('index'))31@app.route('/agregar', methods=['GET','POST'])32def agregar():33 if request.method == 'POST' and session.get('logged_in'):34 return sist_gest_functs.agregar_funct(request.form['inicial'], request.form['final'], mysql.connect(), session)35 else:36 return render_template("agregar_ano.html")37#--------VISTA PERSONAL --------#38@app.route('/personal_ano', methods=['GET'])39def personal():40 # Aqui va el g con el ano escolar41 if session.get('logged_in'): return sist_gest_functs.personal_funct(mysql.connect().cursor())42 return redirect(url_for('index'))43@app.route('/personal_escoger_tipo', methods=['GET'])44def escoger_tipo_personal():45 if(session.get('logged_in')): return sist_gest_functs.escoger_tipo_personal_funct(mysql.connect().cursor(), request.args['id_tipo'])46#Aumenta el contador de inasistencias para los empleados47@app.route('/agregarInasistenciaPersonal', methods=['PUT'])48def agregarInasistenciaPersonal():49 if(session.get('logged_in')): return sist_gest_functs.agregarInasistenciaPersonal_funct(mysql.connect(), request.args['resultado'])50@app.route('/eliminarPersonal', methods=['DELETE'])51def eliminarPersonal():52 if(session.get('logged_in')): return sist_gest_functs.eliminarPersonal_funct(mysql.connect(), request.args['id'], session)53@app.route('/personal')54def getPersonal():55 if(session.get('logged_in')): return sist_gest_functs.getPersonal_funct(mysql.connect().cursor())56@app.route('/editarPersonal', methods=[ 'POST'])57def editarPersonal():58 if request.method == 'POST' and session.get('logged_in'): 59 return sist_gest_functs.editarPersonal_funct(mysql.connect(), request.form['apellidos'], request.form['hiddenCedula'], request.form['cedula'], request.form['nombres'], request.form['telefono'], request.form['id_tipo'], request.form['inasistencia'], request.form['direccion'], request.form['correo'])60@app.route('/anadirPersonal', methods=['GET', 'POST'])61def anadirPersonal():62 if(session.get('logged_in')): return render_template("personal_individual.html") 63#Buscar miembros del personal64@app.route('/buscarPersonal', methods=['POST'])65def buscarPersonal():66 if(session.get('logged_in')): return sist_gest_functs.buscarPersonal_funct(request.form['busqueda'], mysql.connect().cursor())67#Registrar nuevo trabajador68@app.route('/registrarPersonal', methods=['GET', 'POST'])69def registrarPersonal(): 70 if(session.get('logged_in')): return sist_gest_functs.registrarPersonal_funct(request.form.get('nombres'), request.form.get('apellidos'), request.form.get('cedula'), request.form.get('id_tipo'), request.form.get('correo'), request.form.get('direccion'), request.form.get('telefono'), mysql.connect())71#--------VISTA ESTUDIANTES--------#72@app.route('/estudiantes_ano', methods=['GET'])73def def_estudiantes(): 74 # Aqui va el g con el ano escolar75 if session.get('logged_in'): return sist_gest_functs.def_estudiantes_funct(mysql.connect().cursor())76 return redirect(url_for('index'))77#Selecciona el ano que se desee visualizar78@app.route('/estudiantes_escoger_ano', methods=['GET'])79def escoger_ano_estudiantes():80 if(session.get('logged_in')): return sist_gest_functs.escoger_ano_estudiantes_funct(mysql.connect().cursor(), request.args['id_carrera'])81#Aumenta el contador de inasistencias para un estudiante82@app.route('/agregarInasistencia', methods=['PUT'])83def agregarInasistencia():84 if(session.get('logged_in')): return sist_gest_functs.agregarInasistencia_funct(mysql.connect(), request.args['resultado'])85#Elimina un estudiante de un curso86@app.route('/eliminarEstudiante', methods=['DELETE'])87def eliminarEstudiante():88 if(session.get('logged_in')): return sist_gest_functs.eliminarEstudiante_funct(mysql.connect(), request.args['id'], session)89#Elimina una seccion de un curso90@app.route('/eliminarSeccion', methods=['DELETE'])91def eliminarSeccion():92 if(session.get('logged_in')): return sist_gest_functs.eliminarSeccion_funct(request.args['id_carrera'], request.args['cedulas'].split(","), mysql.connect(), session)93@app.route('/editarEstudiante', methods=[ 'POST'])94def editar_estudiantes():95 if request.method == 'POST' and session.get('logged_in'): return sist_gest_functs.editar_estudiantes_funct(mysql.connect(), request.form['apellidos'], request.form['hiddenCedula'], request.form['seccion'], request.form['cedula'], request.form['nombres'], request.form['telefono'], request.form['id_carrera'], request.form['inasistencia'], request.form['direccion'], request.form['correo'], request.form['nombresPadre'], request.form['telefonoPadre'], request.form['correoPadre'])96 return redirect(url_for('def_estudiantes'))97#Agrega una seccion nueva a un curso98@app.route('/agregar_seccion', methods=['GET', 'POST'])99def seccion():100 if request.method == 'POST' and session.get('logged_in'): return sist_gest_functs.seccion_funct(request.form.get('id_carrera'), mysql.connect())101 return render_template("agregar_seccion.html")102#Cantidad de secciones de un curso103@app.route('/cant_secciones')104def getCantidadSecciones():105 if(session.get('logged_in')): return sist_gest_functs.getCantidadSecciones_funct(mysql.connect().cursor(), request.args['id_carrera'])106@app.route('/buscarEstudiante', methods=['POST'])107def buscarEstudiante():108 if(session.get('logged_in')): return sist_gest_functs.buscarEstudiante_funct(request.form['busqueda'], mysql.connect().cursor())109@app.route('/anadirEstudiante', methods=['GET', 'POST'])110def anadirEstudiante():111 if(session.get('logged_in')): return render_template("estudiante_individual.html") 112@app.route('/estudiante')113def getEstudiante():114 if(session.get('logged_in')): return sist_gest_functs.getEstudiante_funct(mysql.connect().cursor())115@app.route('/registrarEstudiante', methods=['GET', 'POST'])116def registrarEstudiante():117 if(session.get('logged_in')): return sist_gest_functs.registrarEstudiante_funct(request.form.get('nombres'), request.form.get('apellidos'), request.form.get('cedula'), request.form.get('fechaNac'), '1900-01-01', request.form.get('id_carrera'), request.form.get('seccion'), request.form.get('correo'), request.form.get('direccion'), request.form.get('telefono'), request.form.get('nombresPadre'), request.form.get('telefonoPadre'), request.form.get('correoPadre'), mysql.connect())118#--------FIN VISTA ESTUDIANTES--------#119# Al darle a seleccionar busco todos los anos y los mando al html120@app.route('/seleccionar')121def seleccion_ano():122 if(session.get('logged_in')): return sist_gest_functs.seleccion_ano_funct(mysql.connect().cursor())123#Vista para eliminar anos124@app.route('/eliminar')125def eliminar_ano():126 if(session.get('logged_in')): return sist_gest_functs.eliminar_ano_funct(mysql.connect().cursor())127#Oculta el ano de la vista128@app.route('/eliminar_ano', methods=['POST'])129def eliminar_anos():130 if(session.get('logged_in')): return sist_gest_functs.eliminar_anos_funct(request.form['real_id'], request.form['ano_escolar'], mysql.connect())131#Vista para recuperar anos132@app.route('/recuperar')133def recuperar_ano():134 if(session.get('logged_in')): return sist_gest_functs.recuperar_ano_funct(mysql.connect().cursor()) 135#Vuelve a colocar el ano en la vista136@app.route('/recuperar_ano', methods=['POST'])137def recuperar_anos():138 if(session.get('logged_in')): return sist_gest_functs.recuperar_anos_funct(request.form['real_id'], request.form['ano_escolar'], mysql.connect())139#-----------FUNCIONES DE CARGAR, EXPORTAR BD Y CERRAR---------#140@app.route('/exportarBD', methods=['GET'])141def exportarBD():142 if(session.get('logged_in')): return sist_gest_functs.exportarBD_funct()143 return redirect(url_for('index'))144def run_sql_file(filename, connection): return sist_gest_functs.run_sql_file_funct(filename, connection)145@app.route('/cargarBD', methods=['POST'])146def cargarBD():147 if(session.get('logged_in')): return sist_gest_functs.cargarBD_funct(request.files['archivo'], db.connect(host="localhost", user="root", passwd="1234"))148 return redirect(url_for('index'))149@app.route('/cerrar_sesion', methods=['GET'])150def cerrar_sesion():151 if(session.get('logged_in')): 152 session.pop('logged_in', None)153 return redirect(url_for('index'))154#-----------ENVIAR CORREO Y UPLOAD DE ARCHIVO---------#155@app.route('/send_mail', methods=['POST'])156def send_mail():157 if session.get('logged_in') and request.method == 'POST': return sist_gest_functs.send_mail_funct(mysql.connect(), request, request.form['asunto'], request.form['Mensaje'], config_vars.app_conf(), mail)158@app.route('/enviar_correo', methods=['GET', 'POST'])159def enviar_correo():160 if session['ano_esc'] != None: 161 return sist_gest_functs.enviar_correo_funct(mysql.connect().cursor())162 else:163 print("Error no selecciono periodo escolar!")164 return render_template("ano_escolar.html")165@app.route('/enviar_correo_personal', methods=['GET', 'POST'])166def enviar_correo_personal():167 if session['ano_esc'] != None:168 return sist_gest_functs.enviar_correo_personal_funct(mysql.connect().cursor())169 else:170 print("Error no selecciono periodo escolar!")171 return render_template("ano_escolar.html")172@app.route('/send_mail_personal', methods=['POST'])173def send_mail_personal():174 if session.get('logged_in') and request.method == 'POST': return sist_gest_functs.send_mail_personal_funct(mysql.connect(), request, request.form['asunto'], request.form['Mensaje'], config_vars.app_conf(), mail)175if __name__ == "__main__":...

Full Screen

Full Screen

F07.py

Source:F07.py Github

copy

Full Screen

1# NIM/Nama Pembuat : 16519092/Rafidika Samekto2# Deskripsi : F07 - Pembelian Tiket. Pembelian tiket yang dilakukakn oleh user3# Kamus4# a adalah input ID wahana yang ingin dibeli tiketnya5# b adalah input tanggal pembelian tiket6# c adalah jumlah tiket yang dibeli7# Algoritma8def beli_tiket():9 if (logged_in[5] != "Admin"):10 a = input("Masukkan ID Wahana: ")11 b = input("Masukkan tanggal hari ini (DD/MM/YYYY): ")12 c = int(input("Jumlah tiket yang dibeli: "))13 wahana_pakai = [] # data wahana yang akan dibeli tiketnya14 for i in range(1,1000):15 if (wahana[i][0] == a):16 wahana_pakai = wahana[i]17 break18 day = int(b[0:2]) # hari pada tanggal hari ini19 month = int(b[3:5]) # bulan pada tanggal hari ini20 year = int(b[6:10]) # tahun pada tanggal hari ini21 x = logged_in[1] # menggunakan data user yang login22 day_birth = int(x[0:2]) # hari lahir user23 month_birth = int(x[3:5]) # bulan lahir user24 year_birth = int(x[6:10]) # tahun lahir user25 umur = year - year_birth # umur user saat membeli tiket26 if (month_birth > month):27 umur = umur - 128 elif (month_birth == month):29 if (day_birth > day):30 umur = umur - 131 # kondisi month_birth < month tidak perlu ditulis karena hasilnya32 # sama saja dengan variabel umur33 def syarat(): # diberikan jika user tidak memenuhi persyaratan wahana yang akan dibeli tiketnya34 print("Anda tidak memenuhi persyaratan untuk memainkan wahana ini.")35 print("Silakan menggunakan wahana lain yang tersedia.")36 def no_saldo(): # diberikan jika user tidak memiliki cukup saldo untuk membeli sejumlah tiket wahana37 print("Saldo Anda tidak cukup")38 print("Silakan mengisi saldo Anda")39 if (wahana_pakai[4] == "1"): # untuk batasan tinggi badan wahana lebih dari 170 cm40 if (int(logged_in[3]) <= 170): # mengecek tinggi badan user41 syarat()42 else: # tinggi badan user di atas 170 cm43 if (wahana_pakai[3] == "1"): # untuk batasan umur wahana kurang dari 17 tahun44 if (umur >= 17):45 syarat()46 else:47 harga_total = int(wahana_pakai[2]) * c48 if (logged_in[5] == "Gold"):49 harga_total = harga_total * 0.550 sisa = int(logged_in[6]) # sisa saldo user51 if (sisa >= harga_total):52 sisa -= harga_total53 logged_in[6] = str(sisa)54 print("")55 print("Selamat bersenang-senang di " + wahana_pakai[1] + ".")56 # proses selanjutnya adalah menyimpan data di atas ke file pembelian dan kepemilikan tiket57 data_beli = [logged_in[3], b, a, str(c)]58 pemilik = [logged_in[3], a, str(c)]59 for i in range(1,1000):60 if (pembelian[i] == None):61 pembelian[i] = data_beli62 break63 for i in range(1,1000):64 if (tiket[i] == None):65 tiket[i] = pemilik66 break67 else:68 no_saldo()69 elif (wahana_pakai[3] == "2"): # untuk batasan umur wahana lebih dari sama dengan 17 tahun70 if (umur < 17):71 syarat()72 else:73 harga_total = int(wahana_pakai[2]) * c74 if (logged_in[5] == "Gold"):75 harga_total = harga_total * 0.576 sisa = int(logged_in[6]) # sisa saldo user77 if (sisa >= harga_total):78 sisa -= harga_total79 logged_in[6] = str(sisa)80 print("")81 print("Selamat bersenang-senang di " + wahana_pakai[1] + ".")82 # proses selanjutnya adalah menyimpan data di atas ke file pembelian dan kepemilikan tiket83 data_beli = [logged_in[3], b, a, str(c)]84 pemilik = [logged_in[3], a, str(c)]85 for i in range(1,1000):86 if (pembelian[i] == None):87 pembelian[i] = data_beli88 break89 for i in range(1,1000):90 if (tiket[i] == None):91 tiket[i] = pemilik92 break93 else:94 no_saldo()95 else: # untuk semua umur96 harga_total = int(wahana_pakai[2]) * c97 if (logged_in[5] == "Gold"):98 harga_total = harga_total * 0.599 sisa = int(logged_in[6]) # sisa saldo user100 if (sisa >= harga_total):101 sisa -= harga_total102 logged_in[6] = str(sisa)103 print("")104 print("Selamat bersenang-senang di " + wahana_pakai[1] + ".")105 # proses selanjutnya adalah menyimpan data di atas ke file pembelian dan kepemilikan tiket106 data_beli = [logged_in[3], b, a, str(c)]107 pemilik = [logged_in[3], a, str(c)]108 for i in range(1,1000):109 if (pembelian[i] == None):110 pembelian[i] = data_beli111 break112 for i in range(1,1000):113 if (tiket[i] == None):114 tiket[i] = pemilik115 break116 else:117 no_saldo()118 else: # untuk wahana tanpa batasan tinggi badan119 if (wahana_pakai[3] == "1"): # untuk batasan umur wahana kurang dari 17 tahun120 if (umur >= 17):121 syarat()122 else:123 harga_total = int(wahana_pakai[2]) * c124 if (logged_in[5] == "Gold"):125 harga_total = harga_total * 0.5126 sisa = int(logged_in[6]) # sisa saldo user127 if (sisa >= harga_total):128 sisa -= harga_total129 logged_in[6] = str(sisa)130 print("")131 print("Selamat bersenang-senang di " + wahana_pakai[1] + ".")132 # proses selanjutnya adalah menyimpan data di atas ke file pembelian dan kepemilikan tiket133 data_beli = [logged_in[3], b, a, str(c)]134 pemilik = [logged_in[3], a, str(c)]135 for i in range(1,1000):136 if (pembelian[i] == None):137 pembelian[i] = data_beli138 break139 for i in range(1,1000):140 if (tiket[i] == None):141 tiket[i] = pemilik142 break143 else:144 no_saldo()145 elif (wahana_pakai[3] == "2"): # untuk batasan umur wahana lebih dari sama dengan 17 tahun146 if (umur < 17):147 syarat()148 else:149 harga_total = int(wahana_pakai[2]) * c150 if (logged_in[5] == "Gold"):151 harga_total = harga_total * 0.5152 sisa = int(logged_in[6]) # sisa saldo user153 if (sisa >= harga_total):154 sisa -= harga_total155 logged_in[6] = str(sisa)156 print("")157 print("Selamat bersenang-senang di " + wahana_pakai[1] + ".")158 # proses selanjutnya adalah menyimpan data di atas ke file pembelian dan kepemilikan tiket159 data_beli = [logged_in[3], b, a, str(c)]160 pemilik = [logged_in[3], a, str(c)]161 for i in range(1,1000):162 if (pembelian[i] == None):163 pembelian[i] = data_beli164 break165 for i in range(1,1000):166 if (tiket[i] == None):167 tiket[i] = pemilik168 break169 else:170 no_saldo()171 else: # untuk semua umur172 harga_total = int(wahana_pakai[2]) * c173 if (logged_in[5] == "Gold"):174 harga_total = harga_total * 0.5175 sisa = int(logged_in[6]) # sisa saldo user176 if (sisa >= harga_total):177 sisa -= harga_total178 logged_in[6] = str(sisa)179 print("")180 print("Selamat bersenang-senang di " + wahana_pakai[1] + ".")181 # proses selanjutnya adalah menyimpan data di atas ke file pembelian dan kepemilikan tiket182 data_beli = [logged_in[3], b, a, str(c)]183 pemilik = [logged_in[3], a, str(c)]184 for i in range(1,1000):185 if (pembelian[i] == None):186 pembelian[i] = data_beli187 break188 for i in range(1,1000):189 if (tiket[i] == None):190 tiket[i] = pemilik191 break192 else:193 no_saldo()194 else:...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful