def menu(player,inventory): while True: if player.hp <= 0: break choice = input(textwrap.dedent(""" Menu 0 - Go out to the fields and train 1 - Check character status 2 - Enter the castle! NOTE: I would advise saving at this point. 3 - Use potion 4 - Save. Please save often. 5 - Quit Game """)) if choice == "0": player = random_battle(player, inventory) elif choice == "1": player_status(player) delay = input("Press enter to continue...") elif choice == "2": #The choice you make alters storyline. Sorry its not really creative haha. print("As you reach the castle, you hear a mysterious voice. \"I can grant you power beyond your imagination. In return, I only ask of you to slay the Dragon King for me.\"") selection = input("You are curious yet hesitant and suspicious about this voice's offer. What do you do? Input 0 to accept and 1 to ignore the voice and venture forth.\n") if selection == "1": boss_battle(player,inventory) elif selection == "0": boss_battle2(player,inventory) break elif choice == "3": player.use_potion(inventory) elif choice == "4": save(player,inventory) elif choice == "5": print("Good Bye!") break
def download(self, url): l = self.pattern_match(url) aux = [self.parse_uri_problem (self.URI_PREFIX + l[0] + self.URI_SUFFIX)] letters = ['uri' + l[0]] for i, in_out in enumerate(aux): save.save('uri', l[0], in_out)
def handle(self): self.data = self.request.recv(1024).strip() print "{} wrote:".format(self.client_address[0]) print self.data da=json.loads(self.data) save.save(da) if not self.client_address[0] in allhostips: allhostips.append(self.client_address[0]) print 'a new ip \'' +self.client_address[0]+'\' is add to the list!'
def atraining(charact): rt = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) j = random.choice(rt) if j <= 4: charact.attack += 1 charact.exp += 1 print("\nBrawo! Obecnie wartość punktów ataku wynosi: ", charact.attack) print("Dodano 1 pkt EXP") save.save(charact) else: print("Trening nie przyniósł efektów")
def dtraining(charact): rt = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) j = random.choice(rt) if j <= 5: charact.health += 2 charact.exp += 1 print("\nBrawo! Obecnie wartość punktów zdrowia wynosi: ", charact.health) print("Dodano 1 pkt EXP") save.save(charact) else: print("Trening nie przyniósł efektów :(")
def run(): os.system('bash rmold.sh') os.system('rm rmold.sh') prompt = input('What is your terminal username? >>>').strip() print('Saving name...') user.User.name = prompt save.save() print('Copying .alert file...') os.system('cp .alert ~') print('Installing mult funcs. in .bashrc....') os.system('bash bh') print('Done!')
def download(self, url): l = self.pattern_match(url) probs = [] if l[1] is None: probs = self.parse_codeforces_contest('http://codeforces.com/contest/' + l[0]) letters = map(lambda x: chr(x + ord('a')), range( len(probs) ) ) else: probs = [u'http://codeforces.com/contest/' + l[0] +'/problem/' + l[1].upper()] letters = [l[1]] aux = [self.parse_codeforces_problem(p) for p in probs] for i, in_out in enumerate(aux): save.save('cf', l[0] + letters[i], in_out)
def run(self): print "run the worker" lan, y0, t, delta, g, gamma, xi, f, n = RK4Process.queue.get() print y0, delta, g, gamma data = [t] for i in range(n): k = ku.RK4(lan,y0,t, \ args=(delta,g,gamma,xi,f)) # RK4Process.resultLock.acquire() # RK4Process.result.append(k) # RK4Process.resultLock.release() data.append(k) save.save(xi_var,xi_mean,gamma,delta,g,data) print "calling the worker finished" RK4Process.queue.task_done()
def run_devise(image_vecs, image_labels, word_vecs, n_epochs, checkpoint_file, iters_per_checkpoint, iters_per_eval, validation_inds, logfile, step_rate=1e-4, decay=0.9, dm_thresh=0.1): # TODO: n_samples = len(image_labels) n_minibatch = 1 n_iters = int(np.ceil(n_epochs * n_samples / n_minibatch)) word_dim = word_vecs.shape[1] image_dim = image_vecs.shape[1] # Initialize M m_flat = np.random.randn(word_dim * image_dim) # m_flat = np.zeros(word_dim * image_dim) # m_flat = np.random.randn(word_dim * image_dim) # Beware momentum, as it can cause nonconvergence. devise_args = make_minibatch_iterator(image_vecs, image_labels, word_vecs, n_minibatch=1) #opt = climin.RmsProp(m_flat, devise_loss_one_sample, step_rate=step_rate, decay=decay, args=devise_args) opt = climin.GradientDescent(m_flat, devise_loss_one_sample, step_rate=step_rate, momentum=.95, args=devise_args) old_m_flat = np.copy(m_flat) last_validation_loss = np.nan lf = open(logfile, 'w') for info in opt: if info["n_iter"] % iters_per_checkpoint == 0: save.save(checkpoint_file, info=info, m_flat=m_flat, last_validation_loss=last_validation_loss) # No validation set yet if info["n_iter"] % iters_per_eval == 0: dm = np.linalg.norm(m_flat - old_m_flat, 1) if dm < dm_thresh: print("Optimization converged at %d iters: dm < %g." % (info["n_iter"], dm)) return (M, info) old_m_flat = np.copy(m_flat) last_validation_loss = validation_loss(m_flat, image_vecs, image_labels, word_vecs, validation_inds) print("Iter %d, dM (1-norm) = %g, validation loss = %g" % (info["n_iter"], dm, last_validation_loss)) lf.write("Iter %d, dM (1-norm) = %g, validation loss = %g\n" % (info["n_iter"], dm, last_validation_loss)) lf.flush() if info["n_iter"] == n_iters: M = np.reshape(m_flat, (word_dim, image_dim)) lf.close() return (M, info)
def update_stats(games, won, lost, moves, hit, destroyed, time_spent): """ updates stats when stats are looked up ore game is closed :param games: int; games played since stats have been updated :param won: int; games won since stats have been updated :param lost: int; games lost since stats have been updated :param moves: int; moves done since stats have been updated :param hit: int; ships hit since stats have been updated :param destroyed: int; ships destroyed since stats have been updated :param time_spent: int; time spent since stats have been updated in minutes """ stat_vals = [games, won, lost, time_spent, moves, hit, destroyed] # new stats count = 0 for difficulty in DIFFICULTIES: # goes through all difficulties for i in range(7): # goes through all stats stat_val = save.load("int", STATS[i], 1, resource_path, "stats/" + difficulty) # loads stat's value stat_val += stat_vals[i][count] # adds new value save.save(stat_val, "int", STATS[i], 1, resource_path, "stats/" + difficulty) # saves updated value count += 1
def save(save): # save the game global i global previ global player if player == None: player = make_player() s.save(player, save, 'player') # save the player s.save(world._world, save, 'world') # save the world (no this isn't something the player does :P) s.save({'turn': i, 'prev. turn': previ}, save, 'game') # save the current turn
def get_save_quit_menu(player, state_stack): options = [] game_state = player.game_state.value exit_menu_function = menu.BackToGameFunction(state_stack) save_and_quit_graphic_active = graphic.GraphicChar(None, colors.WHITE, icon.GUNSLINGER_THIN) save_and_quit_graphic_inactive = graphic.GraphicChar(None, colors.GRAY, icon.GUNSLINGER_THIN) options.append(menu.MenuOptionWithSymbols("Save and Quit", save_and_quit_graphic_active, save_and_quit_graphic_inactive, [lambda: save.save(game_state), exit_menu_function, game_state.current_stack.pop, (lambda: player.actor.add_energy_spent(gametime.single_turn))])) give_up_graphic_active = graphic.GraphicChar(None, colors.WHITE, icon.SKULL) give_up_graphic_inactive = graphic.GraphicChar(None, colors.GRAY, icon.SKULL) options.append(menu.MenuOptionWithSymbols("Give Up", give_up_graphic_active, give_up_graphic_inactive, [player.health_modifier.kill, exit_menu_function, (lambda: player.actor.add_energy_spent(gametime.single_turn))])) return get_menu_with_options(options, state_stack, 6, 5)
def main(): login.setup() if data.user != "*": out = run(data.user) if out == "logout": save() exit() elif out == "exit": save() exit() elif out == "deluser": save() exit() else: exit()
def save_changes(self): save.save(im) self.pic.close() if os.path.exists('img.jpg'): os.remove('img.jpg')
pause = pygame.image.load(IMGPATH+"pause.png") pauserect=pause.get_rect() screen.blit(back,backrect) screen.blit(ball, ballrect) screen.blit(base, baserect) for i in range(0,len(blocks)): if blocks[i].life>0: screen.blit(blocks[i].imgsr,blocks[i].rect) for event in pygame.event.get(): key=pygame.key.get_pressed() name+=screeninput.whatchar(key) if key[pygame.K_BACKSPACE]: name=name[:len(name)-1] if key[pygame.K_RETURN]: #print "IO SALVO" save.save(name,point) pygame.quit() sys.exit() if event.type == pygame.QUIT or key[pygame.K_ESCAPE]: print name pygame.quit() sys.exit() ren=fontolo.render(name+" : "+str(point), 1, (255,255,255)) n=1 for i in hs: screen.blit(i, (width/2,height/2+(n*16))) n+=1 screen.blit(pause,pauserect) screen.blit(ren, (width/2,height/2))
exit() elif pressed == 0: #up corner[1] += -5 print corner, width, height elif pressed == 3: #right corner[0] += 5 print corner, width, height elif pressed == 1: #down corner[1] += 5 print corner, width, height elif pressed == 2: #left corner[0] += -5 print corner, width, height elif pressed == 97: #right width += 5 print corner, width, height elif pressed == 115: #down width += -5 print corner, width, height elif pressed == 100: #left height += 5 print corner, width, height elif pressed == 102: #left height += -5 print corner, width, height elif pressed == 99: #left _,frame_= cam.read() elif pressed >= 48 and pressed <=57: save(procframe, pressed - 48) elif pressed !=255: print pressed
def play(user): #sets up pygame pygame.init() fpsClock = pygame.time.Clock() font = pygame.font.SysFont(None, 30) #saves progress save.save(user, '1') #sets up window WINDOWWIDTH = 1120 WINDOWHEIGHT = 600 window = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) pygame.display.set_caption('Pants vs. Kosbie') #sets up images #used some graphics from the orginal game background1 = pygame.image.load('Graphics/Frontyard.jpg') kosbieCutsceneImg = pygame.image.load('Graphics/kosbie cutscene.png') speechBoxImg = pygame.image.load('Graphics/speechbox.png') cooldownImg = pygame.image.load('Graphics/cooldown.png') nextDayImg = pygame.image.load('Graphics/nextday.png') endtxtImg = pygame.image.load('Graphics/endtext.png') #sets up sounds #sound from freesound.org victorySound = pygame.mixer.Sound('Sounds/victory.ogg') #The next day transition while True: timer = 0 nextdayX = 330 nextdayY = 0 endY = 200 while True: window.fill((0, 0, 0)) window.blit(nextDayImg, (nextdayX, nextdayY)) if nextdayY == endY: #break out of the transition when nextdayY hits endY time.sleep(2) break for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYUP: if event.key == K_ESCAPE: pygame.quit() sys.exit() nextdayY += 10 pygame.display.update() break #The beginning cutscene while True: pygame.mixer.music.load('Sounds/victory.ogg') curSpeech = 0 pygame.mixer.music.play(-1, 0.0) while True: speech = 'Graphics/14speech' + str(curSpeech) + '.png' try: speechImg = pygame.image.load(speech) except: #when Kosbie runs out of things to say break window.blit(background1, (0, 0)) kosbieX = 200 kosbieY = 22 window.blit(kosbieCutsceneImg, (kosbieX, kosbieY)) speechboxX = 450 speechboxY = 115 window.blit(speechBoxImg, (speechboxX, speechboxY)) window.blit(speechImg, (speechboxX, speechboxY)) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYUP: if event.key == K_ESCAPE: pygame.quit() sys.exit() if event.key == K_SPACE: curSpeech += 1 pygame.display.update() break while True: timer = 0 nextdayX = 330 nextdayY = 200 while True: window.fill((0, 0, 0)) window.blit(endtxtImg, (nextdayX, nextdayY)) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYUP: if event.key == K_ESCAPE: pygame.quit() sys.exit() if event.type == MOUSEBUTTONUP: import RunMe pygame.display.update() break
import os from menu import menu from printTheatre import printTheatre from reset import reset from save import save from load import load pos = [] temp = [] f = open("theater.txt", "a+") # if theater.txt does not exist, create theater.txt if os.stat("theater.txt").st_size == 0: # if theater.txt is empty, create pos reset(pos) print("Instantiated theater.txt") else: # else load pos from theater.txt load(pos) print("Loaded theater.txt") menu(pos) # run program save(pos) # save pos to theater.txt
def main(): from argparse import ArgumentParser, RawTextHelpFormatter import os parser = ArgumentParser(description="Command line support for the 'aion' project", formatter_class=RawTextHelpFormatter, add_help=False) parser.add_argument("command", nargs="+") args = parser.parse_args() try: command = args.command[0].strip() if os.path.isfile(command): import __init__ __init__.ExecuteAionFile(command) elif command == "help" or command == "-help" or command == "--help": print(help) elif command == "start" or command == "run": os.system("python3 " + atils.aion_path + "/main.py") elif command == "install": errno = "77227" arglen_check(args.command, 2) package = args.command[1] if package == "aion": must_be_sudo() Install.aion() print("Installed aion") elif package == "respeaker": must_be_sudo() Install.respeaker(yesno("Install in compatibility mode? (installs older kernel version)? (y/n): ")) print("Installed respeaker") elif os.path.exists(package): if package.strip() == "skill.aion": Install.skill_from_aion_file(package) elif package.strip() == "plugin.aion": Install.plugin_from_aion_file(package) elif package.endswith(".skill"): Install.skill_from_skill_file(package) elif package.endswith(".plugin"): Install.plugin_from_plugin_file(package) else: AionShellError(package + " is an unknowing skill / plugin. Type 'aion help' for help", errno) else: AionShellError(package + " is an unknowing skill / plugin. Type 'aion help' for help", errno) elif args.command in ["kill", "stop"]: # kist arglen_check(args.command, 1) is_aion_running(command) import variable import signal avar = variable.Variable() os.kill(int(avar.get_value("AION_PID")), signal.SIGKILL) elif command == "load": arglen_check(args.command, 2, 3) import save as asave if len(args.command) == 3: asave.load_save(str(args.command[1]), str(args.command[2])) else: asave.load_save(str(args.command[1])) elif command == "pack": no_skill_plugin_file_errno = "27177" no_dir_errno = "27178" arglen_check(args.command, 2) dir = args.command[1] if os.path.isdir(dir): if os.path.isfile(dir + "/skill.aion"): Pack.skill(dir) elif os.path.isfile(dir + "/plugin.aion"): Pack.plugin(dir) else: AionShellError("couldn't find 'skill.aion' or 'plugin.aion' in " + dir + ". See 'create_skill_file' function in 'aionlib.skill' to create a 'skill.aion' file" "or 'create_plugin_file' function in 'aionlib.plugin' to create a 'plugin.aion' file", no_skill_plugin_file_errno) else: AionShellError("couldn't find directory " + dir, no_dir_errno) elif command == "pid": arglen_check(args.command, 1) is_aion_running(command) import variable avar = variable.Variable() print(avar.get_value("AION_PID")) elif command == "save": arglen_check(args.command, 2) import save as asave asave.save(args.command[1]) elif command == "saves": arglen_check(args.command, 1) import save as asave print(" ".join(asave.saves())) elif command in ["remove", "uninstall"]: # UnRem errno = "07340" arglen_check(args.command, 2) package = args.command[1] if command == "uninstall": name = "Uninstall" else: name = "Remove" question = yesno(name + " " + package + "? (y/n): ") if name == "Remove": name = "Remov" if package == "aion": if question is True: question = yesno("Should your personal data ('/etc/aion_data/': custom skills / plugins, version saves, language files, ...) deleted as well? (y/n): ") UnRem.aion(question) print(name + "ed aion") print("You should reboot now to complete the " + name.lower() + " process") elif package == "aionlib": if question is True: UnRem.aionlib() print(name + "ed aionlib") elif package == "respeaker": if question is True: UnRem.respeaker() print(name + "ed respeaker") else: package_type = which_package(package, "Type in the number of your package type: ") if package_type == -1: AionShellError("couldn't find skill / plugin " + package, errno) elif package_type == 0: UnRem.skill(package) elif package_type == 1: UnRem.run_after_plugin(package) elif package_type == 2: UnRem.run_before_plugin(package) elif command in ["run", "start"]: arglen_check(args.command, 1) import start from os import geteuid if geteuid() == 0: start(True) elif geteuid() == 1000: start(False) elif command == "update": errno = "43503" arglen_check(args.command, 2) package = args.command[1] if package == "aion": Update.aion() elif package == "aionlib": Update.aionlib() else: package_type = which_package(package, "Type in the number of your package type: ") if package_type == -1: AionShellError("couldn't find skill / plugin " + package, errno) elif package_type == 0: Update.skill(package) elif package_type == 1: Update.run_after_plugin(package) elif package_type == 2: Update.run_before_plugin(package) elif command == "variable": arglen_check(args.command, 2) command_variable = args.command[1] import variable avar = variable.Variable() print(avar.get_value(command_variable)) elif command == "version": errno = "56297" arglen_check(args.command, 2) package = args.command[1] if package == "aion": Version.aion() elif package == "aionlib": Version.aionlib() else: package_type = which_package(package, "Type in the number of your package type: ") if package_type == -1: AionShellError("couldn't find skill / plugin " + package, errno) elif package_type == 0: Version.skill(package) elif package_type == 1: Version.run_after_plugin(package) elif package_type == 2: Version.run_before_plugin(package) else: errno = "12345" AionShellError(" ".join(args.command) + " isn't a command. Type 'aion help' to get help", errno) except KeyboardInterrupt: exit(-1)
import pymongo from save import save save() client = pymongo.MongoClient('localhost', 40001, retryWrites=False) db = client['news-db'] news_collection = db['news'] news_collection.delete_many({ })
def save(self, epoch): save.save(self.model, epoch, self.train_out)
def main(): esize = 16 lvl = level("level0.lvl", esize) l = glob.glob("data/*.lvl") lvl_anz = len(l) try: pygame.mixer.init() music = pygame.mixer.Sound(os.path.join("data", "music.ogg")) except: print "No Sound avaiable" pygame.init() screen = pygame.display.set_mode((lvl.esize * len(lvl.lvl[0]), lvl.esize * len(lvl.lvl))) img = image(str(esize)) try: music.play(1) except: pass pygame.key.set_repeat(80, 50) for i in range(lvl_anz): play = player() lvl = level("level" + str(i) + ".lvl", esize) objects = [] screen = pygame.display.set_mode((lvl.esize * len(lvl.lvl[0]), lvl.esize * len(lvl.lvl))) for y in range(len(lvl.lvl)): objects.append([]) for x in range(len(lvl.lvl[0])): o = GameObject(img[lvl.lvl[y][x]], x * lvl.esize, y * lvl.esize, screen) objects[y].append(o) if lvl.lvl[y][x] == "S": pl = GameObject(img["player"], x * lvl.esize, y * lvl.esize, screen) btime = time.time() while not play.finish: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: txt = "Closing ..." centered_txt(screen, lvl, txt, 50) music.fadeout(2100) time.sleep(2) return if event.key == pygame.K_DOWN: pl.move(0, 1, lvl, img, objects, play) if event.key == pygame.K_UP: pl.move(0, -1, lvl, img, objects, play) if event.key == pygame.K_RIGHT: pl.move(1, 0, lvl, img, objects, play) if event.key == pygame.K_LEFT: pl.move(-1, 0, lvl, img, objects, play) if event.key == pygame.K_n: pass play.finish = 1 for j in range(len(objects)): for o in objects[j]: o.draw() pl.draw() time.sleep(0.08) pygame.display.update() dtime = time.time() - btime sav = save("User") sav.write(play.points, pl.moves, dtime) print "Ziel erreicht:", play.points, "gesammelt" print "Moves:", pl.moves print dtime won = 1 try: if lvl.conf["moves"] > 0: if pl.moves < lvl.conf["moves"]: print "moves OK" else: print "too many steps" won = 0 except: print "Maximal moves not given" try: if lvl.conf["time"] > 0: if dtime < lvl.conf["time"]: print "time OK" else: print "too slow" won = 0 except: print "Maximal time not given" try: if lvl.conf["points"] > 0: if play.points > lvl.conf["points"]: print "points OK" else: print "not enought points" won = 0 except: print "Minimal points not given" if won == 1: print "You finished this level" if i < lvl_anz - 1: txt = "Next level ..." centered_txt(screen, lvl, txt, 50) time.sleep(1) txt = "Finished ..." centered_txt(screen, lvl, txt, 50) music.fadeout(2100) time.sleep(2)
import save import load import cv2 import numpy as np import os import init init.init() #print(os.getcwd()) store = dict() for file in os.listdir(".\\Images"): print(file) save.save(file, store) img = load.load("Screenshot_20190410-232140.rna") cv2.imshow('image', np.array(img)) # Maintain output window utill # user presses a key cv2.waitKey(0) # Destroying present windows on screen cv2.destroyAllWindows()
def saved_mode(username): print "saved mode" # main_2.destroy() save.save(main_2, username)
def save(self): save.save(self.mainLayout)
import parse import save url_list = [ 'https://udn.com/news/story/6813/2515948', 'https://udn.com/news/story/6813/2515978', 'https://udn.com/news/story/6813/2515977', 'https://udn.com/news/story/6813/2515931', 'https://udn.com/news/story/6813/2515838', 'https://udn.com/news/story/6813/2515735' ] for url in url_list: news = parse.parse_news(url=url) save.save(news=news) print('saved...%s' % url)
print("WITAJ W GRZE TEKSTOWEJ, symulującej walki gladiatorów.") print(''' 1 - Wyświetl bohatera \ Edytuj imię 2 - Walcz na arenie 3 - Trenuj umiejętności obronne 4 - Trenuj atakowanie 5 - Zakończ ''') hero1 = save.read() if hero1: print('Wczytano bohatera') else: hero1 = hero.Hero() hero1.create() save.save(hero1) x = int(input("Wybieram: ")) if x == 1: # Wyświetla bohatera save.view(hero1) elif x == 2: # Walka import enemy enemy1 = enemy.Enemy() enemy1.create_enemy() fight.fth(hero1, enemy1) elif x == 3: # Trening obronny import training training.dtraining(hero1) elif x == 4: # Trening Atakowania import training training.atraining(hero1) elif x == 5:
def signal_new_level(self): self.camera.center_on_entity(self.player) self.dungeon_needs_redraw = True if not self.first_round: save(self)
def game_loop(): screen = settings.screen b_surf = screen.subsurface((5, 200), (400, 275)) p_surf = screen.subsurface((5, 5), (350, 190)) m_surf = screen.subsurface((360, 5), (240, 120)) pet_surf = screen.subsurface((360, 130), (240, 65)) fashu_surf = screen.subsurface((410, 200), (190, 100)) count_surf = screen.subsurface((410, 305), (190, 170)) toolbar_surf = screen.subsurface((605, 5), (190, 470)) cangku_surf = screen.subsurface((5, 5), (595, 470)) pet_cangku_surf = screen.subsurface((5, 5), (595, 470)) hecheng_surf = screen.subsurface((5, 5), (595, 470)) ronghe_surf = screen.subsurface((5, 5), (595, 470)) fuwen_surf = screen.subsurface((5, 5), (595, 470)) lianbao_surf = screen.subsurface((5, 5), (595, 470)) xiulian_surf = screen.subsurface((5, 5), (790, 470)) set_surf = screen.subsurface((5, 5), (790, 470)) show_equip_surf = screen.subsurface((5, 5), (790, 470)) player_detail_surf = screen.subsurface((5, 5), (790, 470)) login_surf = screen.subsurface((5, 5), (790, 470)) ditu = settings.ditu if settings.use_load: if settings.link_load: screen.blit(waiting_pic, (0, 0)) pygame.display.update() url_data = link.load_online() if url_data: a_p, time_n, battle_n, use_money = url_data p = a_p else: settings.game_stage = 'start' settings.use_load = False settings.link_load = False return else: p = save.load() settings.battle_set = p.battle_set.copy() p.game_version = settings.VERSION p.enemys = [] p.attack_all = [] p.attacking = None p.defending = None p.jisuan_shuxin() if str(p.place.__class__) == 'codes.place.Fuben': place.change_place(place.changan, p) settings.in_fuben = False if p.place.name == u'\u901a\u5929\u5854': place.change_place(place.changan, p) settings.in_ttt = False if settings.link_load: if p.place.name != u'\u957f\u5b89': for i in range(battle_n): battle.battle(p) functions.msg(u'\u53d6\u56de\u6210\u529f\uff0c\u6302\u673a\u65f6\u957f' + link.count_guaji_time(time_n), settings.FPS * 10) functions.msg(u'\u6263\u9664\u70b9\u6570\uff1a%s \u70b9' % unicode(use_money), settings.FPS * 10) settings.bc_base_time -= time_n else: if settings.rw_select[3] == u'\u4eba\u65cf': p = player.Zhongzu_Ren(settings.rw_select) elif settings.rw_select[3] == u'\u9b54\u65cf': p = player.Zhongzu_Mo(settings.rw_select) else: p = player.Zhongzu_Xian(settings.rw_select) with file('yourname.txt', 'r') as f: name = unicode(f.readline(), 'gbk')[:10].strip() if name != u'': p.name = name p.place = place.Place(place.place_data_list[0]) w = equip.Weapon(equip.weapon_list_0[random.randint(0, 11)]) while w.type not in p.adept_weapons: w = equip.Weapon(equip.weapon_list_0[random.randint(0, 11)]) w.get_pr() w.get(p) w.equip() for i in range(15): ch = random.choice(random.choice(p.place.spoils)) exec 'e = equip.%s(ch)' % settings.equip_list[ch[1]] e.get_pr() e.get(p) e.equip() cl_list = ['shuiyuezhi', 'liuyanhuo', 'xuanminshi', 'honglianshengquan', 'zichengtie', 'xuanyebin', 'cangleijinshi', 'bixinsha'] random.shuffle(cl_list) cl_use = cl_list[:4] for i in cl_use: cl = fabao.Fabao_Cailiao(i) cl.get(p) pet = monster.Pet(monster.monsters_dict['yefendanqi'], p) p.pet_bag.append(pet) pet = monster.Pet(monster.monsters_dict['boji'], p) p.pet_bag.append(pet) p.add_kucun_exp(10000) if settings.TEST: p.add_exp(5000000000L) p.money = enc.en(5000000000L) p.shengli = enc.en(100000) p.get_skill('weiguanzhidao') p.get_skill('xunshouzhidao') for i in range(4): g = goods.BB_Skill_Forget_Book() g.get(p) g = goods.MoonStone() g.get(p) for i in range(2): fw = goods.Fuwen_suipian() fw.get(p) for i in range(60): pet = monster.Pet(monster.monsters_dict[random.choice(p.place.monsters)], p) p.pet_bag.append(pet) draw_init.draw_init(p) if settings.battle_set['4beijiasu']: pygame.time.set_timer(settings.EVT_BATTLE, settings.TIME_BATTLE_SHORT) else: pygame.time.set_timer(settings.EVT_BATTLE, settings.TIME_BATTLE) pygame.time.set_timer(EVT_SAVE, TIME_SAVE) pygame.time.set_timer(EVT_SAVE_2, TIME_SAVE_2) b_surf.blit(settings.b_surf_init, (0, 0)) settings.bt_surf = b_surf.copy() while settings.game_stage == 'game': for event in gui.setEvents(pygame.event.get()): if event.type == QUIT: pygame.quit() exit() if event.type == MOUSEBUTTONUP: settings.mouse.click = True settings.mouse.button = event.button if event.type == EVT_BATTLE: check = [settings.map_open, settings.cangku_open, settings.hecheng_open, settings.xiulian_open, settings.ronghe_open, settings.set_open, settings.fuwen_open, settings.lianbao_open] if True not in check: if p.place.name != u'\u957f\u5b89': battle.battle(p) else: battle.stay_in_changan(p) if pygame.display.get_active(): draw.b_draw_surf(b_surf) if event.type == EVT_SAVE: save.save(p) if event.type == EVT_SAVE_2: save.save_2(p) screen.fill(GRAY) if pygame.display.get_active(): if settings.map_open: draw.map_open(ditu, p) elif settings.cangku_open: draw.cangku_open(p, cangku_surf) draw.cangku_bag_draw_surf(p, toolbar_surf) elif settings.pet_cangku_open: draw.pet_cangku_open(p, pet_cangku_surf) draw.pet_cangku_bag_draw_surf(p, toolbar_surf) elif settings.hecheng_open: draw.hecheng_open(p, hecheng_surf) draw.hecheng_bag_draw_surf(p, toolbar_surf) elif settings.ronghe_open: draw.ronghe_open(p, ronghe_surf) draw.ronghe_pet_bag_draw_surf(p, toolbar_surf) elif settings.xiulian_open: draw.xiulian_open(p, xiulian_surf) elif settings.fuwen_open: draw.fuwen_open(p, fuwen_surf) draw.fuwen_bag_draw_surf(p, toolbar_surf) elif settings.lianbao_open: draw.lianbao_open(p, lianbao_surf) draw.lianbao_bag_draw_surf(p, toolbar_surf) elif settings.set_open: draw.set_open(p, set_surf) elif settings.show_equip_open: draw.show_equip_open(p, show_equip_surf) elif settings.player_detail_open: draw.player_detail_open(p, login_surf) elif settings.login_open: draw.login_open(p, login_surf) else: draw.bt_draw_surf(b_surf) draw.p_draw_surf(p, p_surf) draw.m_draw_surf(p, m_surf, settings.font_14) draw.pet_draw_surf(p, pet_surf, settings.font_14) draw.fashu_draw_surf(p, fashu_surf) draw.count_draw_surf(p, count_surf) draw.toolbar_draw_surf(p, toolbar_surf) draw.detect_mouse(p) draw.message_draw_surf() settings.mouse.fresh() settings.clock.tick(settings.FPS) pygame.display.update() return
if 'idlelib.run' in sysModule.modules: print("You probably want to run this from the command line.") else: terminal.out(""" ██╗ ██╗ █████╗ ██████╗██╗ ██╗███████╗██╗ ██╗███████╗\n\ ██║ ██║██╔══██╗██╔════╝██║ ██╔╝██╔════╝╚██╗ ██╔╝██╔════╝\n\ ███████║███████║██║ █████╔╝ ███████╗ ╚████╔╝ ███████╗\n\ ██╔══██║██╔══██║██║ ██╔═██╗ ╚════██║ ╚██╔╝ ╚════██║\n\ ██║ ██║██║ ██║╚██████╗██║ ██╗███████║ ██║ ███████║\n\ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚══════╝\n\ version {} """.format(__version__)) time.sleep(2) utils.serverBootSequence(sysCont.userSystem, terminal) while True: if sysCont.userSystem.status == system.Statuses.UNBOOTABLE: terminal.error("ERROR: SYSTEM UNBOOTABLE") while True: continue userInput = terminal.get(sysCont.userSystem.IP + sysCont.userSystem.fileSystem.getPath()) ret = comCont.feed(userInput, sysCont, sysCont.userSystem, terminal) comCont.outputType = 0 terminal.out('') if ret == 99: sysModule.exit() else: save.save(sysCont) continue
def texts_iter(filename,word): for f in sorted(os.listdir('.')): if f[0] != '.' and os.path.isdir(f): try: with codecs.open(f + "/" + filename, "r", "utf-8", "ignore") as a: print "Submission by ", f raw_text = a.read() yield (f, search(raw_text,word)) except IOError: print "No file for ", f pass if __name__ == "__main__": args = docopt(__doc__) docs, raw_texts, texts = zip(*list(texts_iter(args['<textfile>']))) dictionary = gensim.corpora.dictionary.Dictionary(texts) dictionary.compactify() corpus = map(dictionary.doc2bow, texts) save.save(args['<datafile>'], docs=docs, texts=texts, raw_texts=raw_texts, corpus=corpus, dictionary=dictionary)
def fetch_it(parsr,website): firstid,page_nb,i,nb,find_id=None,parsr.start,0,0,False parsr=parse.update(parsr) # Update the values html.update(parsr,website) # Prettify according to arguments if parsr.no_blessings: init_tty,message=verbose.bck_init_tty,verbose.bck_message else: init_tty,message=verbose.init_tty,verbose.message save_name=parsr.save_name to_fetch,listIdParsed=website.build_request(parsr.tags),[] print 'Results will be saved in "'+save_name+'.html"' ht=html.hCreate(save_name) html.hHeader(ht) def post_operations(): parsr.stop=page_nb parse.name(parsr) def new_page(ht): end=parsr.stop post_operations() html.hFooter(ht) html.hClose(ht,save_name,parsr.save_name) parsr.stop=end parsr.start=page_nb parse.name(parsr) ht=html.hCreate(parsr.save_name) html.hHeader(ht) return ht total_duration=init_tty(parsr,website) try: for page_nb in xrange(parsr.start,parsr.stop+1): parsr.wait_fn(parsr) found,r=False,requests.get(website.get_page_number(to_fetch,page_nb)) r.raise_for_status() soup=BeautifulSoup(r.text,"html5lib") message(parsr,website,page_nb,0,i,to_fetch,total_duration,1) for nb,link,pict in website.find_next_picture(soup,parsr.find): found,i=True,i+1 message(parsr,website,page_nb,nb,i,to_fetch,total_duration,2) if firstid==None: save.save(parsr,nb) firstid=nb if parsr.check_links: # Find a better testing tst=requests.head(pict) if tst.status_code>=300: continue if nb not in listIdParsed: # Maybe it's getting useless... html.hAddline(ht,nb,link,pict,website,parsr) listIdParsed.append(nb) else: print "Error on pict",i,nb if nb==parsr.find: print "Found {}, exiting search".format(nb) find_id=True raise GTFOError if parsr.split!=0: if i%parsr.split==0: parsr.img_nb=i ht=new_page(ht) save_name=parsr.save_name if not found: page_nb-=1 print " > [PAGE {}] No pictures were fetch".format(page_nb+1) raise GTFOError except GTFOError: post_operations() except KeyboardInterrupt: print "Not cool... you killed me dude, NOT cool..." post_operations() except: logging.exception("Unknown error") # Finishing if parsr.verbose>0: message(parsr,website,page_nb,nb,i,to_fetch,total_duration,1) if parsr.find>0 and not find_id: print " > [FIND] Couldn't find id",parsr.find html.hFooter(ht) html.hClose(ht,save_name,parsr.save_name)
def transform_word(word): # don't stem # return word.lower().rstrip(string.punctuation) return stemmer.stem(word.lower().strip(string.punctuation)) def transform_text(text): words = text.split() return remove_stopwords(map(transform_word, words)) def texts_iter(filename): for f in sorted(os.listdir('.')): if f[0] != '.' and os.path.isdir(f): with codecs.open(f + "/" + filename, "r", "utf-8", "ignore") as a: print "Submission by ", f raw_text = a.read() yield (f, raw_text, transform_text(raw_text)) if __name__ == "__main__": args = docopt(__doc__) students, raw_texts, texts = zip(*list(texts_iter(args['<textfile>']))) dictionary = gensim.corpora.dictionary.Dictionary(texts) dictionary.compactify() corpus = map(dictionary.doc2bow, texts) save.save(args['<datafile>'], students=students, texts=texts, raw_texts=raw_texts, corpus=corpus, dictionary=dictionary)
bzfile_path = 'dewiktionary-latest-pages-articles-multistream.xml.bz2' bz = BZ2File(bzfile_path) data = [] for record in Parser(bz, custom_methods=[extend_flexion]): # Titel muss Buchstabend enthalten if re.search(r'([a-zA-Z]+)', record['title']) is None: continue if re.search(r'{{Schweizer und Liechtensteiner Schreibweise\|[^}]+}}', record['wikitext']): continue if re.search(r'{{Alte Schreibweise\|[^}]+}}', record['wikitext']): continue if record['inflected'] is True: continue if 'language' not in record or record['language'].lower() != 'deutsch': continue if 'pos' not in record or 'Substantiv' not in record['pos']: continue data.append(record) save('local.db', data) print(f'Saved {len(data)} records')
def main(): nrows = 30_000_000 train, val, ENDPOINT, AGE, SEX, vocab_size, sequence_length, n_individuals = get_dataset(nrows = nrows) print('Data loaded, number of individuals:', n_individuals) print('GAN type:', GAN_type) print('Relativistic average:', relativistic_average) # Train the GAN G = RelationalMemoryGenerator(mem_slots, head_size, embed_size, vocab_size, temperature, num_heads, num_blocks) D = RelGANDiscriminator(n_embeddings, vocab_size, embed_size, sequence_length, out_channels, filter_sizes, use_aux_info, use_mbd, mbd_out_features, mbd_kernel_dims) ''' if torch.cuda.device_count() > 1: print("Using", torch.cuda.device_count(), "GPUs") G = nn.DataParallel(G) D = nn.DataParallel(D) elif cuda: print("Using 1 GPU") ''' N_max = 11 prefix = 'Before:' G.eval() data1, ages1, sexes1, data_fake1, ages_fake1, sexes_fake1 = get_real_and_fake_data(G, train, ignore_similar, dummy_batch_size, sequence_length, True) data2, ages2, sexes2, data_fake2, ages_fake2, sexes_fake2 = get_real_and_fake_data(G, val, ignore_similar, dummy_batch_size, sequence_length, True) ''' predictor_name = 'I9_STR_EXH' event_name = 'I9_HEARTFAIL_NS' analyse(data1, data_fake1, True, True, ENDPOINT, event_name, predictor_name) analyse(data2, data_fake2, True, False, ENDPOINT, event_name, predictor_name) predictor_name = 'I9_ANGINA' event_name = 'I9_HYPTENS' analyse(data1, data_fake1, True, True, ENDPOINT, event_name, predictor_name) analyse(data2, data_fake2, True, False, ENDPOINT, event_name, predictor_name) ''' save_frequency_comparisons(data_fake1, data_fake2, vocab_size, ENDPOINT, prefix, N_max) test_generator(data1, ages1, sexes1, data_fake1, ages_fake1, sexes_fake1, True, True, ENDPOINT, SEX, vocab_size, sequence_length) test_generator(data2, ages2, sexes2, data_fake2, ages_fake2, sexes_fake2, True, False, ENDPOINT, SEX, vocab_size, sequence_length) G.train() start_time = time.time() # Call train function scores1_train, transition_scores_mean_train, similarity_score1_train, similarity_score2_train, mode_collapse_score_train, \ scores1_val, transition_scores_mean_val, similarity_score1_val, similarity_score2_val, mode_collapse_score_val, \ accuracies_real, accuracies_fake = train_GAN( G, D, train, val, ENDPOINT, batch_size, vocab_size, sequence_length, n_epochs, lr, temperature, GAN_type, n_critic, print_step, get_scores, ignore_time, dummy_batch_size, ignore_similar, one_sided_label_smoothing, relativistic_average, False, use_gp, lambda_gp ) print('Time taken:', round_to_n(time.time() - start_time, n = 3), 'seconds') torch.save(G.state_dict(), G_filename) G.eval() prefix = 'After:' data1, ages1, sexes1, data_fake1, ages_fake1, sexes_fake1 = get_real_and_fake_data(G, train, ignore_similar, dummy_batch_size, sequence_length, True) data2, ages2, sexes2, data_fake2, ages_fake2, sexes_fake2 = get_real_and_fake_data(G, val, ignore_similar, dummy_batch_size, sequence_length, True) save_frequency_comparisons(data_fake1, data_fake2, vocab_size, ENDPOINT, prefix, N_max) save_plots_of_train_scores(scores1_train, transition_scores_mean_train, similarity_score1_train, similarity_score2_train, mode_collapse_score_train, \ scores1_val, transition_scores_mean_val, similarity_score1_val, similarity_score2_val, mode_collapse_score_val, \ accuracies_real, accuracies_fake, ignore_time, sequence_length, vocab_size, ENDPOINT) test_generator(data1, ages1, sexes1, data_fake1, ages_fake1, sexes_fake1, False, True, ENDPOINT, SEX, vocab_size, sequence_length) test_generator(data2, ages2, sexes2, data_fake2, ages_fake2, sexes_fake2, False, False, ENDPOINT, SEX, vocab_size, sequence_length) predictor_name = 'I9_STR_EXH' event_name = 'I9_HEARTFAIL_NS' analyse(data1, data_fake1, False, True, ENDPOINT, event_name, predictor_name) analyse(data2, data_fake2, False, False, ENDPOINT, event_name, predictor_name) predictor_name = 'I9_ANGINA' event_name = 'I9_HYPTENS' analyse(data1, data_fake1, False, True, ENDPOINT, event_name, predictor_name) analyse(data2, data_fake2, False, False, ENDPOINT, event_name, predictor_name) save(data1, data_fake1, train = True) save(data2, data_fake2, train = False) test_size = 10 visualize_output(G, test_size, val, sequence_length, ENDPOINT, SEX)
result = make_prediction(neighbors) predictions.append(result) # Calculate and print the accuracy of the classification accuracy = get_accuracy(testing_set, predictions) print('\nFull accuracy : ' + repr(accuracy) + '%') # Print the accuracy for each class accuracy_by_class = get_accuracy_by_class(testing_set, predictions) print '\nClasses found in the set :', accuracy_by_class[0] print 'Size of the set :', accuracy_by_class[1] print 'Accuracy per class' for pc in accuracy_by_class[2].keys(): print '\tClass', pc, '(' + repr(accuracy_by_class[2][pc]) + '/' + \ repr(accuracy_by_class[4][pc]) + ')', ':', \ repr(accuracy_by_class[3][pc]) + '%' # If print the results if the 3rd argument is 'o' if verbose == True: output(predictions, testing_set) elif save == True: save(predictions, testing_set, training_set, k, accuracy, accuracy_by_class) # Run the classification if __name__ == '__main__': main()
def do_work(self, depth, url): content = downloader.download(url) links = page_parser.parser(content) urls = page_parser.link_parser(url, links) self.feedback(depth + 1, urls) save.save(url, content)
def reset_stats(resource_path): for diff in DIFFICULTIES: for stat in STATS: save.save(0, "int", stat, 1, resource_path, "stats/" + diff)
if (user.get_firstName() == 'unknown'): print('\nWelcome back, ' + user.get_username()) else: print('\nWelcome back, ' + user.get_firstName()) if(user.get_admin() == 1): print(MENU_MESSAGE + 'Moderate Administrate') elif(user.get_moderator() == 1): print(MENU_MESSAGE + 'Moderate') else: print(' Info Update SingOut') cmd = input(user.get_username() + '@home:') if('INFO' == cmd.upper()): user.print() elif('UPDATE' == cmd.upper()): update_user_info(user) save(user) elif('SINGOUT' == cmd.upper()): save(user) del user user = User(None, None) logged_in = False elif('MODERATE' == cmd.upper()): if(user.get_moderator() == 1 or user.get_admin() == 1): moderator_menu(user) else: print('You do not have privilages') elif('ADMINISTRATE' == cmd.upper()): if(user.get_admin() == 1): admin_menu(user else: print('You do not have privilages')
vaccination = vaccination + x.get() print(x.get(), end=" ") print() vaccination_level.append(vaccination / run) k = [] for i in range(15): k.append(k13[i] / k12[i]) data = 'run=' + str(run) + ' ' + 'generation=' + str( generation) + ' ' + 'omega=' + str(omega) + ' ' + 'N=' + str( N ) + ' ' + 'deg=' + str(deg) + ' ' + 'initial_vaccination_level=' + str( initial_vaccination_level) + ' ' + 'k11=' + str( k11) + ' ' + 'k22=' + str(k22) + ' ' + 'k33=' + str( k33) + ' ' + 'k23=' + str(k23) + '\n' + 'k12=' + str( k12) + '\n' + 'k13=' + str(k13) + ' ' + 'vcost=' + str( v_cost) + ' ' + 'icost=' + str( i_cost) + ' ' + 'r0=' + str(r0) + '\n' data = data + '[' for v in vaccination_level: data = data + str(v) + ',' data = data + ']' save(path=path, data=data) plot(xaxis=k, yaxis=vaccination_level, xlabel='kVUI/kVUH', ylabel='Final Vaccination Level', path=path, name=name)
import matplotlib.image as mpimg import numpy as np import random import array import cv2 from noise import noise from loader import MNIST from save import save __all__ = [MNIST, ] absPath = os.path.dirname(__file__) mnist = MNIST(absPath) noise = noise() filesave = save() def serialize(image): im_array = np.zeros(784, np.int32) #im_array = array.array('i', (0 for k in range(784))) k = 0 for i in xrange(image.__len__()): for j in xrange(image[i].__len__()): im_array[k] = int(round(image[i, j])) if im_array[k] < 0: im_array[k] = 0 k = k + 1 return im_array
def game_loop(file, state): # 게임을 플레이 if not state: quiz_word, slice_word, length, life, mistake, already_input_alph, already_input_word, check, score = initGame() else: quiz_word, slice_word, length, life, mistake, already_input_alph, already_input_word, check = load(file) times,score=get_game_info() print ('Start game') print ('Length of word is', length) print("Score: " + str(score)) word_bool(length, slice_word, check) print("||", end='') for i in range(0,mistake): print(mistake_sign[i], end="") print("\n" + 'Already input Alphabet: ', already_input_alph) print("Already input Words: ", already_input_word) state=False Bool=True while Bool: print("1. Main Menu") input_alph = input("Alphabet or Word(No a capital letter): ") if len(input_alph) > 1: already_input_word.append(input_alph) if quiz_word==input_alph: print("Congratulations! You Win! ") Bool=False else: print("Sorry. That's wrong. ") print("Score: " + str(score)) mistake = mistake+1 check, check_bool = checkExistence(slice_word, input_alph, check) word_bool(length,slice_word,check) elif input_alph == "1": save(quiz_word, mistake, check, already_input_word, already_input_alph) break else: already_input_alph.append(input_alph) print("Score: " + str(score)) check, check_bool = checkExistence(slice_word, input_alph, check) word_bool(length,slice_word,check) if not check_bool: mistake += 1 if np.sum(check==1) == length: print("Congratulations! You Win! ") Bool=False if mistake==6: print("Sorry. You lose. Answer is " + quiz_word) Bool=False if Bool==True: print("||", end='') for i in range(0,mistake): print(mistake_sign[i], end="") print("\n" + 'Already input Alphabet: ', already_input_alph) print("Already input Words: ", already_input_word) if Bool==False: # 게임 정보 불러오기. times, score = get_game_info() new_score = count_score(score, mistake, quiz_word, already_input_alph) # 게임 정보 쓰기. set_game_info(times, new_score) print("Countiune:1 Menu:2 End:3") user_choice=int(input("Choice: ")) if user_choice==1: Bool=True quiz_word, slice_word, length, life, mistake, already_input_alph, already_input_word, check, score = initGame() elif user_choice==3: print("Bye~") time.sleep(2) sys.exit()
bzfile_path = 'C:/Users/Gregor/Downloads/dewiktionary-latest-pages-articles-multistream.xml.bz2' bz = BZ2File(bzfile_path) data = [] for record in Parser(bz, custom_methods=[extend_flexion]): # Titel muss Buchstabend enthalten if re.search(r'([a-zA-Z]+)', record['title']) is None: continue if re.search(r'{{Schweizer und Liechtensteiner Schreibweise\|[^}]+}}', record['wikitext']): continue if re.search(r'{{Alte Schreibweise\|[^}]+}}', record['wikitext']): continue if record['inflected'] is True: continue if 'language' not in record or record['language'].lower() != 'deutsch': continue if 'pos' not in record or 'Substantiv' not in record['pos']: continue data.append(record) save('../nouns.csv', data) print(f'Saved {len(data)} records')
def save(self): from save import save save(self)
turn = 0 elif input_number == 3: print("You checked your stats!") print("You have {:2} medpacks".format(med)) print("You have {:2} NRG drinks".format(nrg)) print("You have {:2} energy for attack 1".format(attack1)) print("You have {:2} energy for attack 2".format(attack2)) print("You have {:2} energy for attack 3".format(attack3)) print("You have {:2} energy for attack 4".format(attack4)) print("Your health is: {:2}".format(health)) print("The enemy's health is: {:2}".format(enemy)) elif input_number == 4: print("Nothing here yet!") elif input_number == 5: save1(health) save(enemy) save(med) save(nrg) save(attack1) save(attack2) save(attack3) save(attack4) save(ai_attack1) save(ai_attack2) save(ai_attack3) save(ai_attack4) save(ai_nrg) save(ai_med) save(turn) print("Bye!") sys.exit()
def play(user): #sets up pygame pygame.init() fpsClock = pygame.time.Clock() font = pygame.font.SysFont(None, 30) #saves progress save.save(user, '2') #sets up window WINDOWWIDTH = 1120 WINDOWHEIGHT = 600 window = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) pygame.display.set_caption('Pants vs. Kosbie') #sets up images #used some graphics from the orginal game emptySeedImg = pygame.image.load('Graphics/empty_seed.png') background1 = pygame.image.load('Graphics/Frontyard.jpg') khakiImage = pygame.image.load('Graphics/pants.png') peashooterImg = pygame.image.load('Graphics/Pea_Shooter copy.png') peashooterSeedImg = pygame.image.load('Graphics/PeashooterSeed.png') peashooterBulletImg = pygame.image.load('Graphics/Pea_Shooter_Bullet.png') sunImg = pygame.image.load('Graphics/Sun.png') selectedSlotImg = pygame.image.load('Graphics/selected.png') sunCounterImg = pygame.image.load('Graphics/sun_counter.png') wallnutImg = pygame.image.load('Graphics/wallnut.png') wallnutCracked1Img = pygame.image.load('Graphics/Wallnut_cracked1.png') wallnutCracked2Img = pygame.image.load('Graphics/Wallnut_cracked2.png') wallnutSeedImg = pygame.image.load('Graphics/WallNutSeed.png') sunflowerImg = pygame.image.load('Graphics/sunflower.png') sunflowerSeedImg = pygame.image.load('Graphics/SunflowerSeed.png') repeaterImg = pygame.image.load('Graphics/Repeater.png') repeaterSeedImg = pygame.image.load('Graphics/RepeaterSeed.png') snowpeaImg = pygame.image.load('Graphics/Snowpea.png') snowpeaSeedImg = pygame.image.load('Graphics/SnowpeaSeed.png') snowpeaBulletImg = pygame.image.load('Graphics/SnowpeaBullet.png') frozenkhakiImg = pygame.image.load('Graphics/frozen pants.png') cherryBombImg = pygame.image.load('Graphics/Cherrybomb.png') cherryBomb2Img = pygame.image.load('Graphics/Cherrybomb2.png') cherryBombSeedImg = pygame.image.load('Graphics/CherrybombSeed.png') cherryBombExpImg = pygame.image.load('Graphics/Cherryexplosion.png') pmineImg = pygame.image.load('Graphics/pmine1.png') pmine2Img = pygame.image.load('Graphics/pmine2.png') pmineSeedImg = pygame.image.load('Graphics/pmine seed.png') pmineExpImg = pygame.image.load('Graphics/PotatoMine_mashed.png') jeansImg = pygame.image.load('Graphics/jeans.png') frozenJeansImg = pygame.image.load('Graphics/jeans frozen.png') kosbieNoPantsImg = pygame.image.load('Graphics/small kosbie.png') kosbieKhakisImg = pygame.image.load('Graphics/small kosbie khakis.png') kosbieJeansImg = pygame.image.load('Graphics/small kosbie jeans.png') shortsImg = pygame.image.load('Graphics/shorts.png') frozenShortsImg = pygame.image.load('Graphics/frozen shorts.png') kosbieShortsImg = pygame.image.load('Graphics/small kosbie shorts.png') shovelImg = pygame.image.load('Graphics/shovel.png') shovelSelectedImg = pygame.image.load('Graphics/shovel selected.png') kosbieCutsceneImg = pygame.image.load('Graphics/kosbie cutscene.png') kosbieSadCutsceneImg = pygame.image.load('Graphics/kosbie cutscene sad.png') speechBoxImg = pygame.image.load('Graphics/speechbox.png') pausedBgImg = pygame.image.load('Graphics/paused bg.png') pausedSignImg = pygame.image.load('Graphics/paused.png') quitSignImg = pygame.image.load('Graphics/quit.png') quitSignHoverImg = pygame.image.load('Graphics/quit hover.png') quitSignClickedImg = pygame.image.load('Graphics/quit clicked.png') pauseButtonImg = pygame.image.load('Graphics/pausebutton.png') pauseButtonClickedImg =pygame.image.load('Graphics/pausebutton clicked.png') cooldownImg = pygame.image.load('Graphics/cooldown.png') nextDayImg = pygame.image.load('Graphics/nextday.png') #sets up sounds #sounds from freesound.org #and the offical game hitSound = pygame.mixer.Sound('Sounds/splat.ogg') plantingSound = pygame.mixer.Sound('Sounds/planting.wav') sunSound = pygame.mixer.Sound('Sounds/sun.ogg') owSound = pygame.mixer.Sound('Sounds/ow.ogg') explosionSound = pygame.mixer.Sound('Sounds/explosion.ogg') smExplosionSound = pygame.mixer.Sound('Sounds/small explosion.ogg') #The next day transition while True: timer = 0 nextdayX = 330 nextdayY = 0 endY = 200 while True: window.fill((0,0,0)) window.blit(nextDayImg, (nextdayX, nextdayY)) if nextdayY == endY: #break out of the transition when nextdayY hits endY time.sleep(2) break for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYUP: if event.key == K_ESCAPE: pygame.quit() sys.exit() nextdayY += 10 pygame.display.update() break #The beginning cutscene while True: pygame.mixer.music.load('Sounds/intmusic.ogg') curSpeech = 0 pygame.mixer.music.play(-1, 0.0) while True: speech = 'Graphics/4speech' + str(curSpeech) + '.png' try: speechImg = pygame.image.load(speech) except: #when Kosbie runs out of things to say break window.blit(background1 ,(0,0)) kosbieX = 200 kosbieY = 22 window.blit(kosbieCutsceneImg, (kosbieX, kosbieY)) speechboxX = 450 speechboxY = 115 window.blit(speechBoxImg, (speechboxX, speechboxY)) window.blit(speechImg, (speechboxX, speechboxY)) if curSpeech == 4: imgX = 650 imgY = 270 window.blit(repeaterImg, (imgX,imgY)) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYUP: if event.key == K_ESCAPE: pygame.quit() sys.exit() if event.key == K_SPACE: curSpeech += 1 pygame.display.update() break def drawText(text, font, surface, x, y, color): #taken from http://www.pygame.org/project-Plants+vs+Zombies-2632-.html textobj = font.render(text, True, color) textrect = textobj.get_rect() textrect.topleft = (x, y) surface.blit(textobj, textrect) def findRowCol(x, y): #returns the row and column based of the x and y of the mouse cellH = 98 cellW = 82 top = 84 left = 252 bottom = 574 right = 995 if x < left or y < top: return None, None elif x > right or y > bottom: return None, None else: return (y - top) / cellH, (x - left) / cellW def checkIfBaddieInRow(myRow, baddieList): #checks if there is a baddie in the row of the plant for b in baddieList: if b.row == myRow: return True return False def gameOver(): #the cutscene if the user loses while True: curSpeech = 0 while True: speech = 'Graphics/2speech' + str(curSpeech) + '.png' try: speechImg = pygame.image.load(speech) except: break window.blit(background1 ,(0,0)) kosbieX = 200 kosbieY = 22 window.blit(kosbieSadCutsceneImg, (kosbieX,kosbieY)) speechboxX = 450 speechboxY = 115 window.blit(speechBoxImg, (speechboxX, speechboxY)) window.blit(speechImg, (speechboxX, speechboxY)) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYUP: if event.key == K_ESCAPE: pygame.quit() sys.exit() if event.key == K_SPACE: curSpeech += 1 pygame.display.update() break def victory(): # The cutscene if the user wins the level while True: curSpeech = 0 while True: speech = 'Graphics/5speech' + str(curSpeech) + '.png' try: speechImg = pygame.image.load(speech) except: import level3 level3.play(user) window.blit(background1 ,(0,0)) kosbieX = 200 kosbieY = 22 window.blit(kosbieCutsceneImg, (kosbieX, kosbieY)) speechboxX = 450 speechboxY = 115 window.blit(speechBoxImg, (speechboxX, speechboxY)) window.blit(speechImg, (speechboxX, speechboxY)) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYUP: if event.key == K_ESCAPE: pygame.quit() sys.exit() if event.key == K_SPACE: curSpeech += 1 pygame.display.update() break class shovel(object): def __init__(self): slotH = 57 offset = 21 y = 25 x = 230 sizeX = 72 sizeY = 47 self.rect = pygame.Rect(x, y, sizeX, sizeY) self.surface = pygame.transform.scale(shovelImg, (sizeX,sizeY)) self.selected = False def select(self): self.selected = True shovelObj.surface = shovelSelectedImg def deselect(self): self.selected = False shovelObj.surface = shovelImg class kosbie(object): def __init__(self): self.x = 190 self.y = 170 self.sizeX = 55 self.sizeY = 163 self.rect = pygame.Rect(self.x,self.y,self.sizeX,self.sizeY) self.surface = kosbieNoPantsImg self.walkingDown = True self.patrolTop = 170 self.patrolBot = 320 def move(self): #kosbie walking up and down if self.walkingDown: if self.y < self.patrolBot: self.y += 1 self.rect = pygame.Rect(self.x,self.y,self.sizeX,self.sizeY) else: self.walkingDown = False else: if self.y > self.patrolTop: self.y -= 1 self.rect = pygame.Rect(self.x,self.y,self.sizeX,self.sizeY) else: self.walkingDown = True def update(self, baddietype): #kosbie changing his model if a pant gets to him if baddietype == jeans: self.surface = kosbieJeansImg elif baddietype == khaki: self.surface = kosbieKhakisImg elif baddietype == shorts: self.surface = kosbieShortsImg class field(object): #sets up the game board def __init__(self): self.rows = 5 self.cols = 9 self.board = [] for row in xrange(self.rows): self.board += [[None]*self.cols] class sun(object): def __init__(self, natural, x=None, y=None): if natural: #if generated from the sun left = 252 right = 995 self.x = random.randint(left, right) self.y = 0 top = 126 bottom = 560 self.endY = random.randint(top, bottom) self.speed = random.randint(1,2) self.life = 0 self.lifeSpan = 200 size = 30 self.rect = pygame.Rect(self.x, self.y, size, size) self.surface = pygame.transform.scale(sunImg, (size, size)) else: #if generated from a sunflower xOffset = 14 self.x = x + xOffset self.y = y self.endY = y + 42 self.speed = 1 self.life = 0 self.lifeSpan = 200 size = 30 self.rect = pygame.Rect(self.x, self.y, size, size) self.surface = pygame.transform.scale(sunImg, (size, size)) class peashooterPacket(object): #sets up the seed slot for the peashooter def __init__(self, slot): self.cost = 100 self.slot = slot slotH = 57 offset = 21 y = slot * slotH + offset x = 20 self.sizeX = 76 self.sizeY = 47 self.rect = pygame.Rect(x, y, self.sizeX, self.sizeY) self.surface = pygame.transform.scale(peashooterSeedImg, (self.sizeX,self.sizeY)) self.cooldown = 90.0 self.curCooldown = 0 def makeNewPlant(self, row, col): return peashooter(row, col) class peashooterBullet(object): #sets up the bullets for the peashooter def __init__(self, x, y): self.speed = 15 self.size = 24 xOffset = 40 self.x = x + xOffset self.y = y self.rect = pygame.Rect(self.x, self.y, self.size, self.size) self.surface = pygame.transform.scale(peashooterBulletImg, (self.size,self.size)) class peashooter(object): #sets up the peashooter plant def __init__(self, row, col): self.health = 75 self.cost = 100 self.row = row self.col = col self.size = 56 cellW = 80 cellH = 98 xOffset = 260 yOffset = 90 self.x = (col * cellW) + xOffset self.y= (row* cellH) + yOffset self.rect = pygame.Rect(self.x, self.y, self.size, self.size) self.surface = pygame.transform.scale(peashooterImg, (self.size, self.size)) self.curBullet = None self.lastShot = time.time() def shoot(self, bulletList, baddieList): timeSinceLastShot = time.time() - self.lastShot if not checkIfBaddieInRow(self.row, baddieList): #dont shoot if no baddies in the same row pass elif self.curBullet == None and timeSinceLastShot > 1: self.lastShot = time.time() bullet = peashooterBullet(self.x, self.y) bulletList.append(bullet) self.curBullet = bullet else: if self.curBullet not in bulletList: self.curBullet = None class wallnutPacket(object): #sets up the seed slot for the wallnut def __init__(self, slot): self.cost = 50 self.slot = slot slotH = 57 offset = 21 y = slot * slotH + offset x = 20 self.sizeX = 76 self.sizeY = 48 self.rect = pygame.Rect(x, y, self.sizeX, self.sizeY) self.surface = pygame.transform.scale(wallnutSeedImg, (self.sizeX, self.sizeY)) self.cooldown = 300.0 self.curCooldown = 0 def makeNewPlant(self, row, col): return wallnut(row, col) class wallnut(object): #sets up the wallnut plant def __init__(self, row, col): self.health = 300 self.cost = 50 self.row = row self.col = col self.fireRate = 1 self.sizeX = 62 self.sizeY = 71 cellW = 82 cellH = 98 xOffset = 260 yOffset = 84 self.top = (col * cellW) + xOffset self.left= (row * cellH) + yOffset self.rect = pygame.Rect(self.top, self.left, self.sizeX, self.sizeY) self.surface = pygame.transform.scale(wallnutImg, (self.sizeX, self.sizeY)) self.timeAlive = 0 def update(self, zlist): #updates model when wallnut is damaged if self.health <= 100: self.surface = wallnutCracked2Img elif self.health > 100 and self.health <= 200: self.surface = wallnutCracked1Img class sunflowerPacket(object): #sets up the seed slot for the sunflower def __init__(self, slot): self.cost = 50 self.slot = slot slotH = 57 offset = 21 y = slot * slotH + offset x = 20 self.sizeX = 76 self.sizeY = 48 self.rect = pygame.Rect(x, y, self.sizeX, self.sizeY) self.surface = pygame.transform.scale(sunflowerSeedImg, (self.sizeX, self.sizeY)) self.cooldown = 90.0 self.curCooldown = 0 def makeNewPlant(self, row, col): return sunflower(row, col) class sunflower(object): #sets up the sunflower plant def __init__(self, row, col): self.health = 75 self.cost = 50 self.row = row self.col = col self.fireRate = 180 #sun generating rate self.sizeX = 60 self.sizeY = 63 cellW = 79 cellH = 98 xOffset = 270 yOffset = 88 self.top = (col * cellW) + xOffset self.left= (row * cellH) + yOffset self.rect = pygame.Rect(self.top, self.left, self.sizeX, self.sizeY) self.surface = pygame.transform.scale(sunflowerImg, (self.sizeX,self.sizeY)) self.timeAlive = 0 def update(self, zlist): #generates sun self.timeAlive += 1 if self.timeAlive == self.fireRate: self.timeAlive = 0 newSun = sun(False, self.top, self.left) sunList.append(newSun) class repeater(object): #sets up the plant repeater, which is very similar to the peashooter def __init__(self, row, col): self.health = 75 self.cost = 200 self.row = row self.col = col self.sizeX = 63 self.sizeY = 60 cellW = 80 cellH = 98 xOffset = 260 yOffset = 90 self.x = (col * cellW) + xOffset self.y= (row* cellH) + yOffset self.rect = pygame.Rect(self.x, self.y, self.sizeX, self.sizeY) self.surface = pygame.transform.scale(repeaterImg, (self.sizeX,self.sizeY)) self.curBullet = None self.lastShot = time.time() def shoot(self, bulletList, baddieList): #shoots two bullets instead of one timeSinceLastShot = time.time() - self.lastShot if not checkIfBaddieInRow(self.row, baddieList): pass elif self.curBullet == None and timeSinceLastShot > 1: self.lastShot = time.time() gapInBetweenBullets = 21 bullet1 = peashooterBullet(self.x + gapInBetweenBullets, self.y) bulletList.append(bullet1) bullet2 = peashooterBullet(self.x, self.y) bulletList.append(bullet2) self.curBullet = bullet2 else: if self.curBullet not in bulletList: self.curBullet = None class repeaterPacket(object): #sets up the seed slot for the repeater def __init__(self, slot): self.cost = 200 self.slot = slot slotH = 57 offset = 21 y = slot * slotH + offset x = 20 self.sizeX = 76 self.sizeY = 46 self.rect = pygame.Rect(x, y, self.sizeX, self.sizeY) self.surface = pygame.transform.scale(repeaterSeedImg, (self.sizeX,self.sizeY)) self.cooldown = 105.0 self.curCooldown = 0 def makeNewPlant(self, row, col): return repeater(row, col) class snowpea(object): #sets up the plant snowpea def __init__(self, row, col): self.health = 75 self.cost = 175 self.row = row self.col = col self.sizeX = 57 self.sizeY = 62 cellW = 80 cellH = 98 xOffset = 260 yOffset = 90 self.x = (col * cellW) + xOffset self.y = (row* cellH) + yOffset self.rect = pygame.Rect(self.x, self.y, self.sizeX, self.sizeY) self.surface = pygame.transform.scale(snowpeaImg, (self.sizeX,self.sizeY)) self.curBullet = None self.lastShot = time.time() def shoot(self, bulletList, baddieList): timeSinceLastShot = time.time() - self.lastShot if not checkIfBaddieInRow(self.row, baddieList): pass elif self.curBullet == None and timeSinceLastShot > 1: self.lastShot = time.time() bullet = snowpeaBullet(self.x, self.y) bulletList.append(bullet) self.curBullet = bullet else: if self.curBullet not in bulletList: self.curBullet = None class snowpeaPacket(object): #sets up the seed slot for the snowpea def __init__(self, slot): self.cost = 175 self.slot = slot slotH = 57 offset = 21 y = slot * slotH + offset x = 20 self.sizeX = 76 self.sizeY = 46 self.rect = pygame.Rect(x, y, self.sizeX, self.sizeY) self.surface = pygame.transform.scale(snowpeaSeedImg, (self.sizeX,self.sizeY)) self.cooldown = 105.0 self.curCooldown = 0 def makeNewPlant(self, row, col): return snowpea(row, col) class snowpeaBullet(object): #sets up the bullet for the snowpea def __init__(self, x, y): self.speed = 15 self.size = 26 xOffset = 40 self.x = x + xOffset self.y = y self.rect = pygame.Rect(self.x, self.y, self.size, self.size) self.surface = pygame.transform.scale(snowpeaBulletImg, (self.size,self.size)) class cherrybomb(object): #sets up the plant cherry bomb def __init__(self, row, col): self.health = 130 self.cost = 150 self.row = row self.col = col self.fireRate = 30 self.warningTime = 15 self.deathTime = 32 self.sizeX = 102 self.sizeY = 89 self.cellW = 80 self.cellH = 98 xOffset = 244 yOffset = 70 self.x = (col * self.cellW) + xOffset self.y = (row* self.cellH) + yOffset self.rect = pygame.Rect(self.x, self.y, self.sizeX, self.sizeY) self.surface = pygame.transform.scale(cherryBombImg, (self.sizeX,self.sizeY)) self.timeAlive = 0 def update(self, zlist): #updates the model when the cherry bomb explodes self.timeAlive += 1 if self.timeAlive > self.fireRate: xOffset = 250 yOffset = 75 self.x = (self.col - 1) * self.cellW + xOffset self.y = (self.row - 1) * self.cellH + yOffset sizeX = 238 sizeY = 301 self.rect = pygame.Rect(self.x, self.y, sizeX, sizeY) self.surface = pygame.transform.scale(cherryBombExpImg, (sizeX,sizeY)) explosionSound.play() for z in zlist: if z.rect.colliderect(self.rect): zlist.remove(z) elif self.timeAlive == self.warningTime: self.surface = pygame.transform.scale(cherryBomb2Img, (self.sizeX, self.sizeY)) class cherrybombPacket(object): #sets up the seed slot for the chery bomb def __init__(self, slot): self.cost = 150 self.slot = slot slotH = 57 offset = 21 y = slot * slotH + offset x = 20 self.sizeX = 76 self.sizeY = 48 self.rect = pygame.Rect(x, y, self.sizeX, self.sizeY) self.surface = pygame.transform.scale(cherryBombSeedImg, (self.sizeX,self.sizeY)) self.cooldown = 450.0 self.curCooldown = 0 def makeNewPlant(self, row, col): return cherrybomb(row, col) class potatomine(object): #sets up the plant potato mine def __init__(self, row, col): self.health = 100 self.cost = 25 self.row = row self.col = col self.fireRate = 50 self.sizeX = 73 self.sizeY = 52 cellW = 82 cellH = 98 xOffset = 252 yOffset = 98 self.x = (col * cellW) + xOffset self.y = (row * cellH) + yOffset self.rect = pygame.Rect(self.x, self.y, self.sizeX, self.sizeY) self.surface = pygame.transform.scale(pmineImg, (self.sizeX,self.sizeY)) self.timeAlive = 0 self.deathTime = None self.splattered = False def update(self, zlist): #updates the model for potato mine when it explodes self.timeAlive += 1 if self.splattered: self.surface = pmineExpImg self.deathTime = 5 elif self.timeAlive == self.fireRate: self.surface = pygame.transform.scale(pmine2Img, (self.sizeX,self.sizeY)) elif self.timeAlive > self.fireRate: for z in zlist: if z.rect.colliderect(self.rect): smExplosionSound.play() zlist.remove(z) self.splattered = True self.timeAlive = 0 class potatominePacket(object): #sets up the seed slot for the potato mine def __init__(self, slot): self.cost = 25 self.slot = slot slotH = 57 offset = 21 y = slot * slotH + offset x = 20 self.sizeX = 76 self.sizeY = 47 self.rect = pygame.Rect(x, y, self.sizeX, self.sizeY) self.surface = pygame.transform.scale(pmineSeedImg, (self.sizeX,self.sizeY)) self.cooldown = 300.0 self.curCooldown = 0 def makeNewPlant(self, row, col): return potatomine(row, col) class khaki(object): #sets up the baddie Khaki Pants def __init__(self,row,spawnTime): self.health = 12 self.normalSpeed = 1 self.speed = self.normalSpeed self.sizeX = 56 self.sizeY = 100 self.row = row self.spawnTime = spawnTime cellH = 98 yOffset = 56 self.x = WINDOWWIDTH self.y = (self.row* cellH) + yOffset self.rect = pygame.Rect(self.x, self.y, self.sizeX, self.sizeY) self.surface = pygame.transform.scale(khakiImage, (self.sizeX,self.sizeY)) self.eating = False self.frozen = False self.frozenSpeed = 1 self.thawTimer = 0 self.thawTime = 60 def checkIfHit(self, bulletList): #checks if it is hit by a bullet for b in bulletList: if b.rect.colliderect(self.rect): if type(b) == snowpeaBullet: self.frozen = True self.thawTimer = 0 hitSound.play() bulletList.remove(b) self.health -= 1 def checkIfEat(self,plantsList, board): #checks if it should be eating a plant collision = self.rect.collidelist(plantsList) if collision != -1: for p in plantsList: if p.rect.colliderect(self.rect): if self.row == p.row: self.eating = True p.health -= 1 owSound.play() if p.health <= 0: board[p.row][p.col] = None plantsList.remove(p) self.eating = False else: self.eating = False else: self.eating = False def update(self): #updates the model if frozen if self.frozen: self.speed = self.frozenSpeed self.thawTimer += 1 self.surface = pygame.transform.scale(frozenkhakiImg, (self.sizeX,self.sizeY)) if self.thawTimer == self.thawTime: self.thawTime = 0 self.frozen = False self.speed = self.normalSpeed self.surface = pygame.transform.scale(khakiImage, (self.sizeX,self.sizeY)) class jeans(object): #sets up the baddie Jeans Pants def __init__(self,row,spawnTime): self.health = 25 self.normalSpeed = 1 self.frozenSpeed = 1 self.speed = self.normalSpeed self.sizeX = 56 self.sizeY = 100 self.row = row self.spawnTime = spawnTime cellH = 98 yOffset = 56 self.x = WINDOWWIDTH self.y = (self.row* cellH) + yOffset self.rect = pygame.Rect(self.x, self.y, self.sizeX, self.sizeY) self.surface = pygame.transform.scale(jeansImg, (self.sizeX,self.sizeY)) self.eating = False self.frozen = False self.thawTimer = 0 self.thawTime = 60 def checkIfHit(self, bulletList): #checks if it is hit by a bullet for b in bulletList: if b.rect.colliderect(self.rect): if type(b) == snowpeaBullet: self.thawTimer = 0 self.frozen = True hitSound.play() bulletList.remove(b) self.health -= 1 def checkIfEat(self,plantsList, board): #checks if it should be eating a plant collision = self.rect.collidelist(plantsList) if collision != -1: for p in plantsList: if p.rect.colliderect(self.rect): if self.row == p.row: self.eating = True p.health -= 1 owSound.play() if p.health <= 0: board[p.row][p.col] = None plantsList.remove(p) self.eating = False else: self.eating = False else: self.eating = False def update(self): #updates the model if it is frozen if self.frozen: self.speed = self.frozenSpeed self.thawTimer += 1 self.surface = pygame.transform.scale(frozenJeansImg, (self.sizeX,self.sizeY)) if self.thawTimer == self.thawTime: self.thawTimer = 0 self.frozen = False self.speed = self.normalSpeed self.surface = pygame.transform.scale(jeansImg, (self.sizeX,self.sizeY)) class shorts(object): #sets up the baddie Short Pants def __init__(self,row,spawnTime): self.health = 5 self.normalSpeed = 3 self.frozenSpeed = 1 self.speed = self.normalSpeed self.sizeX = 62 self.sizeY = 75 self.row = row self.spawnTime = spawnTime cellH = 98 yOffset = 56 self.x = WINDOWWIDTH self.y = (self.row* cellH) + yOffset self.rect = pygame.Rect(self.x, self.y, self.sizeX, self.sizeY) self.surface = pygame.transform.scale(shortsImg, (self.sizeX,self.sizeY)) self.eating = False self.frozen = False self.thawTimer = 0 self.thawTime = 60 def checkIfHit(self, bulletList): #checks if it is hit by a bullet for b in bulletList: if b.rect.colliderect(self.rect): if type(b) == snowpeaBullet: self.thawTimer = 0 self.frozen = True hitSound.play() bulletList.remove(b) self.health -= 1 def checkIfEat(self,plantsList, board): #checks if it should be eating a plant collision = self.rect.collidelist(plantsList) if collision != -1: for p in plantsList: if p.rect.colliderect(self.rect): if self.row == p.row: self.eating = True p.health -= 1 owSound.play() if p.health <= 0: board[p.row][p.col] = None plantsList.remove(p) self.eating = False else: self.eating = False else: self.eating = False def update(self): #updates the model if it is frozen if self.frozen: self.speed = self.frozenSpeed self.thawTimer += 1 self.surface = pygame.transform.scale(frozenShortsImg, (self.sizeX,self.sizeY)) if self.thawTimer == self.thawTime: self.thawTimer = 0 self.frozen = False self.speed = self.normalSpeed self.surface = pygame.transform.scale(shortsImg, (self.sizeX,self.sizeY)) class quitSign(object): def __init__(self): y = 264 x = 414 sizeX = 291 sizeY = 54 self.rect = pygame.Rect(x, y, sizeX, sizeY) self.surface = quitSignImg def hover(self): self.surface = quitSignHoverImg def clicked(self): self.surface = quitSignClickedImg def reset(self): self.surface = quitSignImg class pauseButton(object): def __init__(self): y = 20 x = 1070 sizeX = 30 sizeY = 30 self.rect = pygame.Rect(x, y, sizeX, sizeY) self.surface = pauseButtonImg def clicked(self): self.surface = pauseButtonClickedImg def reset(self): self.surface = pauseButtonImg spawnList = [ khaki(2, 400), khaki(1, 800), khaki(4, 1100), khaki(3, 1200), khaki(0, 1350), jeans(2, 1400), khaki(4, 1800), khaki(1, 1950), khaki(0, 1980), khaki(1, 2050), khaki(4, 2130), khaki(2, 2180), jeans(3, 2300), khaki(0, 2550), jeans(1, 2551), khaki(2, 2630), khaki(3, 2800), jeans(4, 2850), jeans(0, 3151), jeans(1, 3152), jeans(2, 3153), jeans(3, 3154), jeans(4, 3155), ] while True: sunSpawnRate = 150 baddieList = [] plantsList = [] bulletList = [] sunList = [] slotList = [] slotList.append(sunflowerPacket(0)) slotList.append(peashooterPacket(1)) slotList.append(repeaterPacket(2)) signsList = [] signsList.append(quitSign()) curSelectedSlot = None curSun = 50 sunValue = 25 khakiAddCounter = 0 sunAddCounter = 0 gameTime = 0 lives = 2 isGameOver = False gamePaused = False gField = field() kosbieObj = kosbie() shovelObj = shovel() pauseObj = pauseButton() pygame.mixer.music.load('Sounds/grasswalk.ogg') pygame.mixer.music.play(-1, 0.0) while True: #main game loop if gamePaused: mouseX, mouseY = pygame.mouse.get_pos() #changes model of sign if hovered for s in signsList: if s.rect.collidepoint(mouseX,mouseY): s.hover() else: s.reset() #checks for user events for event in pygame.event.get(): #checks for exit if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYUP: if event.key == K_ESCAPE: pygame.quit() sys.exit() #checks for unpause if event.type == KEYUP: if event.key == K_p: gamePaused = False if event.type == MOUSEBUTTONUP: #checks if Quit sign is clicked for s in signsList: if s.rect.collidepoint(mouseX,mouseY): s.clicked() import RunMe #checks if pause button is clicked if pauseObj.rect.collidepoint(mouseX, mouseY): pauseObj.reset() gamePaused = False if not gamePaused: gameTime += 1 #used for spawning kosbieObj.move() #makes kosbie patrol #checks for user events for event in pygame.event.get(): #checks for exit if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYUP: if event.key == K_ESCAPE: pygame.quit() sys.exit() #checks for pause if event.key == K_p: gamePaused = True if event.type == MOUSEBUTTONUP: mouseX, mouseY = pygame.mouse.get_pos() mRow, mCol = findRowCol(mouseX,mouseY) # Shovel selected, remove a plant using the shovel if shovelObj.selected: if mRow != None and mCol != None: if gField.board[mRow][mCol] == None: shovelObj.deselect() else: plantsList.remove(gField.board[mRow][mCol]) gField.board[mRow][mCol] = None shovelObj.deselect() elif shovelObj.rect.collidepoint(mouseX, mouseY): #can ignore this case. We deselect later to #avoid conflictions between the two deselects. pass else: shovelObj.deselect() # We have a selected seed, plant it elif curSelectedSlot != None: if mRow != None and mCol != None: #we clicked on the board if gField.board[mRow][mCol] == None: #the current space is not occupied curP = slotList[curSelectedSlot] newPlant = curP.makeNewPlant(mRow, mCol) if curSun >= newPlant.cost: curP.curCooldown = curP.cooldown gField.board[mRow][mCol] = newPlant plantsList.append(newPlant) curSun -= newPlant.cost curSelectedSlot = None plantingSound.play() else: curSelectedSlot = None else: curSelectedSlot = None #checks if a slot is clicked for s in slotList: if s.rect.collidepoint(mouseX, mouseY): if s.curCooldown == 0: curSelectedSlot = s.slot #checks if shovel is selected if shovelObj.rect.collidepoint(mouseX, mouseY): if not shovelObj.selected: shovelObj.select() else: shovelObj.deselect() #checks if pause button is clicked if pauseObj.rect.collidepoint(mouseX, mouseY): pauseObj.clicked() gamePaused = True ################################## Gameplay #################################### # if the game is over, break out of everything if isGameOver: break # if the player has defeated all the baddies, we win if spawnList == [] and baddieList == []: victory() # Checks if mouse is on top of sun. Collects sun. for s in sunList: mouseX, mouseY = pygame.mouse.get_pos() if s.rect.collidepoint(mouseX,mouseY): sunSound.play() sunList.remove(s) curSun += sunValue # Makes the plants shoot for p in plantsList: try: p.shoot(bulletList, baddieList) except: p.update(zlist=baddieList) # Removes plants that are temporary(like cherry bombs) for p in plantsList: try: if p.deathTime != None: if p.timeAlive > p.deathTime: gField.board[p.row][p.col] = None plantsList.remove(p) except: pass #spawns the pants for s in spawnList: if s.spawnTime <= gameTime: baddieList.append(s) spawnList.remove(s) #spawns the sun currency sunAddCounter += 1 if sunAddCounter == sunSpawnRate: sunAddCounter = 0 newSun = sun(True) sunList.append(newSun) #checks for dead pants and removes them for z in baddieList: z.checkIfHit(bulletList) if z.health <= 0: baddieList.remove(z) #checks for expired sun and removes them for s in sunList: if s.life == s.lifeSpan: sunList.remove(s) elif s.rect.top >= s.endY: s.life += 1 for s in slotList: if s.curCooldown > 0: s.curCooldown -= 1 ################################### Movement #################################### # Move the pants forward for z in baddieList: z.update() z.checkIfEat(plantsList, gField.board) if not z.eating: z.rect.move_ip(-1.0*z.speed, 0) # Delete pants that have reached the end. for z in baddieList: if z.rect.left < 252: kosbieObj.update(type(z)) baddieList.remove(z) lives -= 1 if lives == 0: isGameOver = True gameOver() # Move the sun down for s in sunList: if s.rect.top < s.endY: s.rect.move_ip(0, 1*s.speed) # Propels the bullets for b in bulletList: b.rect.move_ip(b.speed, 0) #Removes the bullets that went off map for b in bulletList: if b.rect.left > WINDOWWIDTH: bulletList.remove(b) ################################### DRAWING #################################### # Draw the game world on the window. window.blit(background1, (0, 0)) # Draw the shovel window.blit(shovelObj.surface, shovelObj.rect) # Draw the counter background for the sun counterBgX = 110 counterBgY = 25 window.blit(sunCounterImg, (counterBgX, counterBgY)) # Draw the actual counter white = (255, 255, 255) counterx = 144 countery = 30 drawText(str(curSun), font, window, counterx, countery, white) # Draw Kosbie window.blit(kosbieObj.surface, kosbieObj.rect) # Draw each baddie for z in baddieList: window.blit(z.surface, z.rect) # Draw each bullet for b in bulletList: window.blit(b.surface, b.rect) # Draw each plant for p in plantsList: window.blit(p.surface, p.rect) # Draw each sun for s in sunList: window.blit(s.surface, s.rect) # Draw each slot for s in slotList: window.blit(s.surface, s.rect) cdSizeY = int(round((s.curCooldown/s.cooldown) * s.sizeY)) cooldownChangingImg = pygame.transform.scale(cooldownImg, (s.sizeX, cdSizeY)) window.blit(cooldownChangingImg, s.rect) # Draw selected slot if curSelectedSlot != None: x = 20 slotH = 57 offset = 21 y = (curSelectedSlot * slotH) + offset window.blit(selectedSlotImg, (x, y)) if gamePaused: window.blit(pausedBgImg, (0,0)) #draw the paused sign signX = 414 signY = 200 window.blit(pausedSignImg, (signX, signY)) #draw the other signs for s in signsList: window.blit(s.surface, s.rect) # Draw the pause button window.blit(pauseObj.surface, pauseObj.rect) pygame.display.update() break import RunMe
def saveList(): response = save.save(request.json) return "ok"