def main(speed=1, fps=Game.fps, bounciness=Game.bounciness, debug_mode=False, draw_outlines=False): """ Initialize and run the game. keyword arguments: speed=1 Speed multiplier for the game (e.g. speed=2 is twice as fast) fps=60 Max FPS limiter (does not affect game speed) bounciness=0.9 Bounciness of objects (1: 100% elastic, 0: 0% elastic) debug_mode=False Flag to indicate 'debug mode' state draw_outlines=False If in debug_mode, draw collision outlines of objects instead of blitting an image """ debug._DebugMode = debug_mode debug.debug.DrawOutlines = draw_outlines Game.fps = min(max(fps, 10), 120) Game.bounciness = min(max(bounciness, 0), 1) Game._speed = min(max(speed, .01), 10) # Set up an SDL environment video parameter, required for pygame. os.environ['SDL_VIDEO_CENTERED'] = '1' pygame.init() game.init() Game.run()
def main(): game.init() while game.is_running: game.update() game.close()
def mousePressed(event, data): if data.levelSelect: count = 0 for y in range(250, 650, 50): if count >= len(data.levels): return if y < event.y < y + 50: data.mode = "game" data.room = data.levels[count] data.player = Player(data.width // 2, data.height - 100) game.init(data) count += 1 return if (data.width // 4 < event.x < data.width * 3 // 4 and data.height // 3 < event.y < data.height * 4 // 9): data.mode = "game" game.newGame(data) elif (data.width // 4 < event.x < data.width * 3 // 4 and data.height * 4 / 9 < event.y < data.height * 3 / 5): data.levelSelect = True elif (data.width // 4 < event.x < data.width * 3 // 4 and data.height * 3 / 5 < event.y < data.height * 5 / 7): data.mode = "level editor" levelEditor.init(data) elif (data.width // 4 < event.x < data.width * 3 // 4 and data.height * 5 / 7 < event.y < data.height * 8 / 9): data.instructions = True
def init(self, parent, config_dict): """ 初始化:parent是父进程的proxy """ import game self.parent = parent config.__dict__.update(config_dict) common.update_config(config) game.init(self)
def start(): global movingLeft,movingRight,running,lastMove running = True movingLeft = False movingRight = False game.init() musicOn()
def run(self): import game game.init(self) sys.modules['app'] = self self.names = None #subgame names self.sub_mgr = subgame.SubGameMgr(self) self.sub_mgr.start() self.rpc_svr.bind(self.admin_addr) self.rpc_svr.register(self) self.rpc_svr.start() self._init_web() self.web_svr.start() log.info('app started') while 1: try: self._waiter.wait() break except KeyboardInterrupt: log.info('app stoped:KeyboardInterrupt') except SystemExit: log.info('app stoped:SystemExit') except: log.log_except() break log.info('spawn app stop') spawn(self.stop) sleep(0.2) cmd = ' '.join(map(str, [sys.executable,] + sys.argv)) log.info('*****app(%s) stoped', cmd) self.stop() #守护进程方式,重启服务 if self.restarted and hasattr(self, 'daemon_runner'): self.daemon_runner.domain_restart()
def main(args=sys.argv[1:]): parser = argparse.ArgumentParser(description="The connecticut game") parser.add_argument("--ClearDB", action="store_true", required=False, help="clears all data from the database") parser.add_argument("--ClearTable", type=str, required=False, default=None, help="clears all data from a specific table") args = parser.parse_args(args) if args.ClearDB: game.open_connection(game.db, drop=True) elif args.ClearTable is not None: for i in game.database.BaseModel.__subclasses__(): if i.__name__ == args.ClearTable: i.delete() break else: print("table not found") exit() else: game.init(game.db) #start the ui server api = game.Server().run_in_thread()
def main(): # initialise pygame here so all modules # have instant access to pygame functions pygame.init() render.init() import game game.init() game.run()
def init(): font.init() img.init() anim.init() menu.init() instruct.init() game.init() map.init() end.init() director.director.push(menu.menu_scene)
def test_init(): """ Тест с заглушкой запуска _Game.run_, что бы охватить секцию __main__ """ fake_value = 'bla-bla-bla' def fake_run(self): game.Game.fake_attr = fake_value with mock.patch.object(game, "__name__", "__main__"): with mock.patch.object(game.Game, 'run', fake_run): game.init() assert game.Game.fake_attr == fake_value
def main(window): renderer.initialize() curses.curs_set(0) dimens = window.getmaxyx() main_window = window.subwin(22, 20, dimens[0] // 2 - 11, dimens[1] // 2 - 10) main_window.nodelay(1) main_window.keypad(1) game.init() game.add_state_and_switch("main_menu", MainMenuState(main_window)) game.add_state("paused", PauseState(main_window)) game.add_state("game", GameState(main_window)) game.run()
def main(): pygame.init() size = width, height = [640,480+16] renderer.init(size) pygame.display.set_caption("snake") menu.init() # number of player, game type, lives, mapname while 1: gametype = menu.choose ("", \ [{ "label" : "Single Player", "value": "1p"}, \ { "label" : "Multi Players Game", "value": "multi"}, \ { "label" : "Join a Network Game", "value" : "join"}, \ { "label" : "QUIT", "value": None}]) if gametype == None : break if game.init (gametype): game.mainloop () pygame.display.quit()
def train(self): for i in range(self.episodes): if i % 10000 == 0: print("==============", i, "==============") episode = [] s = game.init() ps = s[0] ds = s[1] r = 0 while r == 0: a = self.policy(self.get_e(s), self.Q[ps, ds]) # print(a) r, s = game.step([ps, ds], a) # print("r",r,a,ps,ds) episode.append([[ps, ds], a, r]) if a == 0: # print(r) break else: ps = s[0] ds = s[1] self.control(episode) return self.Q
def start(): pg.init() pg.display.set_mode((width, height), flags=pg.SCALED | pg.RESIZABLE) pg.display.set_caption('card game') save.init() image_handler.init() spritesheet.init() customsheet.init() menu.init() client.init() game.init() network.init() builder.init() ui.init() main_menu = ui.Menu(get_objects=menu.main_menu) main_menu.run() pg.quit()
def __init__(self): self.running = False game.init() self.screen = screen.Screen() game.game = self game.screen = self.screen self.clock = pygame.time.Clock() self.scene_num = 0 self.scenes = [] fx.init() self.ldraw = None self.activescenestack = [] self.teen = contactnode.make_teen() game.teen = self.teen self.script = game.script = scriptmanager.ScriptManager("../res/script.txt", "../res/contacts.txt") #game.active_node = emailnode.test_email() #game.active_node = commentgame.CommentGame() #game.active_node = title.Title() sound.play_music()
def main(): if '-h' in sys.argv: print u""" 使用nose测试框架, 运行测试需要先安装nose: easy_install nose 使用方式: python main.py test 运行test目录下的所有测试 说明: 测试函数中可以使用log模块记录错误信息 只运行部分测试的方法(参考test_other/test_speed.py代码): 1.先在测试函数前,增加common.attr的装饰 2.运行时参数如: python main.py test -a speed """.decode('utf-8').encode(encoding) sys.exit(0) #下面代码中,level不起作用,nose会去处理 from corelib import log log.console_config(False) import game game.Game.app = 'test' if '-g' in sys.argv: sys.argv.remove('-g') from game import SimpleGame game = SimpleGame(config.res_dir) game.init(config.db_engine, config.setting_url_mongodb) try: try: print u'测试路径:%s' % here from nose import main as nose_main if sys.platform in ['cygwin']: os.environ['NOSE_INCLUDE_EXE'] = '1' nose_main(defaultTest=here) finally: pass except ImportError: print u'需要安装nose包,请执行:easy_install -U nose'
def main(): pygame.init() pygame.display.set_caption("Fanorona v0.9") gfx.init() game.init() while not game.finished: game.clock.tick(60) gfx.update() for event in pygame.event.get(): if event.type is pygame.QUIT: # QUIT # game.finished = True break if game.current == game.player: # player's turn if event.type is pygame.MOUSEBUTTONDOWN and event.button == 1: game.player_move( game.grid.collision(pygame.mouse.get_pos())) if event.type is pygame.KEYDOWN and event.key == pygame.K_ESCAPE: game.finished = True if game.current == game.cpu and not game.game_over(): # computer's turn game.cpu_move() if not game.moving and game.game_over(): game.finished = True if game.winner == game.player: gfx.text = "YOU WIN!" else: gfx.text = "YOU LOSE!" quitting = False while not quitting: game.clock.tick(60) gfx.update() for event in pygame.event.get(): if event.type is pygame.QUIT: quitting = True
def translate_path(self, path): print "path: " + path if path == "/song": print "play a song" elif path == "/reset": game.init() elif path == "/resetScore": print "hi" elif path == ("/join/red"): game.joinTeam("red") elif path == ("/join/blue"): game.joinTeam("blue") elif path == ("/correct/red"): game.correct("red") elif path == ("/correct/blue"): game.correct("blue") else: print "Unkown command: " + path return path[1:]
def __init__(self): self.running = False game.init() self.screen = screen.Screen() game.game = self game.screen = self.screen self.clock = pygame.time.Clock() self.scene_num = 0 self.scenes = [] fx.init() self.ldraw = None self.activescenestack = [] self.teen = contactnode.make_teen() game.teen = self.teen self.script = game.script = scriptmanager.ScriptManager( "../res/script.txt", "../res/contacts.txt") #game.active_node = emailnode.test_email() #game.active_node = commentgame.CommentGame() #game.active_node = title.Title() sound.play_music()
def execute(): #Static Settings settings_file_name = "settings.wdf" #Modifiable Settings try: from wdf_test_package import wdf settings = wdf.load(settings_file_name) except: print("\n", "Error: Couldnt load required file (WDF-Package)", "\n") return #Imports try: import msvcrt import iocontrol import menu import time import game except: print("\n", settings["err_import"], "\n") return #Menu loop returned = int while True: returned = menu.main(settings) if returned == 0: break if returned == int(settings["mm_pos_play"]): game.init(settings) elif returned == int(settings["mm_pos_reload_settings"]): print(settings["settings_reload"]) settings = wdf.load(settings_file_name) time.sleep(float(settings["normal_sleep_time"])) elif returned == int(settings["mm_pos_exit"]): iocontrol.message(settings, "leave") break
def main(): # 初始化底层库 # 配置文件 gconfig.init() # 日志 glog.init() # 网络 gnet.init() # 数据库 #gdb.init() # mgr #account_mgr.init() #player_mgr.init() # 游戏逻辑 game.init() # 开始服务 gnet.start_loop()
def main(): game.init() pyglet.app.run()
count += 1 if i != -1: pygame.draw.rect(gameDisplay, (200 - ((int)(math.log(i, 2))) * 10, 230 - ((int)(math.log(i, 2))) * 10, 240 - ((int)(math.log(i, 2))) * 10), (50 + count % 4 * 100, 150 + (int)(count / 4) * 100, 99, 99)) message_display(i, (100 + count % 4 * 100, 200 + ((int)( (count / 4))) * 100)) printScore(score) #------------------------------------------------------------------------------------------------------------------- matrix = game.init() draw(matrix) while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: temp = game.do(matrix, score, 0) matrix = temp[0] score = temp[1] run = temp[3] if event.key == pygame.K_DOWN: temp = game.do(matrix, score, 2) matrix = temp[0]
def start_game(): import game game.init() game.track_event()
def main(): game = Game() game.init() game.run()
def main(): """ Methode principale du programme, porte l'initialisation, la boucle de jeu et le calcul du résultat. """ # Demander le nom du joueur print("Bonjour ! Prêt pour une nouvelle partie de pendu ?") name = input("Entrez votre nom :") score.init(name) format_print("Votre score actuel est de : {}", score.get()) game.init(random_word.get()) print("Mot choisi !\nC'est parti !") # Tant que pas trouver afficher le # mot decomposé first = True while game.can_play(): if first: first = False else: print("Rejouez !") format_print("Il vous reste {} coups", game.get_countdown()) format_print("Mot à trouver : {}", game.get_found()) # On cherhche la proposition du # joueur dans le mot à trouver proposal = input("Proposez une lettre :") try: # Proposition trouvée : on # l'affiche et on peut rejouer if game.find(proposal): format_print("Oui ! Il y a bien un {} dans le mot.", proposal) # Sinon on perd un tour else: format_print("Et non, pas de {} dans le mot !", proposal) # Si la proposition n'est pas # correcte except ValueError as error: format_print("Erreur de proposition : {}", error) # Si trouvé en moins de 8 coups # enregistre le score if game.result(): format_print( "Gagné !\nLe mot était bien {word}\nVous gagnez {score} points de score", word=game.get_to_find(), score=game.get_countdown()) score.add(game.get_countdown()) score.save() # Sinon, perdu ! else: format_print("Perdu !\nLe mot était : {}", game.get_to_find())
import game from Box2D import b2World game.init(world=b2World(gravity=(0, 0), doSleep=True)) #import rule_connect #rule_connect.add() from camera import Camera Camera().add() import camera_control camera_control.add() import b2draw b2draw.init() '''from firefly import Firefly import random for _ in range(100): Firefly(random.randint(-40, 40), random.randint(-30, 30)).add()''' from tilemap import TileMap, SolidBlock tilemap = TileMap((0, 0), (10, 10)) tilemap.add() game.start()
def init(): globals()['SAVE'] = save.get_save() game.init() spritesheet.init() client.init()
def main() -> None: game.init() game.run()
def init(): global state game.init() graphics.drawGame() state = 0
def init(): pygame.key.set_repeat(True) game.init(500, 480)
def main(defconround, teams): seed = random.randint(0, pow(2,64)-1) print("=== seed:", seed) rnd_size = 500 * 1000000 rnd_path = os.path.join(BASEPATH,"rnd.bin") input_path = os.path.join(BASEPATH,"inputs/") chain_path = os.path.join(BASEPATH,"chains/") run_cmd(["./rnd_generator", str(seed), str(rnd_size), rnd_path]) processes = OrderedDict() solution_hash_dict = {} for defcon_id in teams.keys(): fname = os.path.join(input_path, "team%d"%defcon_id) solution_hash_dict[defcon_id] = get_file_hash(fname) p = run_cmd(["./stub_process", rnd_path, fname], traceme=True, wait=False) processes[defcon_id] = p print(p) for p in processes.values(): pid = p.pid pid, status = os.waitpid(pid, 0) print(pid, wait_status_to_string(status)) ptrace(PTRACE_CONT, pid, 0, 0) for p in processes.values(): pid = p.pid pid, status = os.waitpid(pid, 0) print(pid, wait_status_to_string(status)) regs = user_regs_struct() res = ptrace(PTRACE_GETREGS, pid, 0, ctypes.addressof(regs)) regs.rip = COMPUTING_AREA_START ptrace(PTRACE_SETREGS, pid, 0, ctypes.addressof(regs)) fd = os.open("/proc/%d/mem" % pid, os.O_RDWR) writen(fd, b"\xcc"*SECCOMP_SIZE, SECCOMP_AREA) os.close(fd) res = ptrace(PTRACE_CONT, pid, 0, 0) time.sleep(COMPUTING_CHAIN_TIMEOUT) for p in processes.values(): p.send_signal(19) for defcon_id, p in processes.items(): pid = p.pid pid, status = os.waitpid(pid, 0) print(pid, wait_status_to_string(status)) try: fd = os.open("/proc/%d/mem" % pid, os.O_RDWR) cc = readn(fd, OUTPUT_SIZE, OUTPUT_AREA) os.close(fd) p.kill() except OSError as e: print("+++", "Getting chain for proces", type(e), pid) cc = b"" p.wait() with open(os.path.join(BASEPATH,"chains/team%d.chain"%defcon_id), "wb") as out_fd: out_fd.write(cc) print("="*5, datetime.now(), "start rop chains") processes = OrderedDict() for defcon_id in teams.keys(): p = run_cmd(["./stub_ropping", rnd_path, os.path.join(chain_path, "team%d.chain"%defcon_id)], traceme=True, wait=False) processes[defcon_id] = p print(p) for p in processes.values(): pid = p.pid pid, status = os.waitpid(pid, 0) print(pid, wait_status_to_string(status)) ptrace(PTRACE_CONT, pid, 0, 0) for p in processes.values(): pid = p.pid pid, status = os.waitpid(pid, 0) print(pid, wait_status_to_string(status)) fd = os.open("/proc/%d/mem" % pid, os.O_RDWR) writen(fd, b"\xcc"*SECCOMP_SIZE, SECCOMP_AREA) os.close(fd) states = [] state = game.init(teams, defconround, seed) for tid, team in state.teams.items(): team.solution_hash = solution_hash_dict[team.defcon_id] print("=", state.tick) states.append(copy.deepcopy(state)) while True: moves = get_moves(state, processes) state = game.next_state(state, moves) states.append(copy.deepcopy(state)) if state.tick >= GAMENTICK-1: dump_states(states) break if (len(states) % STATEDUMPINTERVAL) == 0: dump_states(states) for p in processes.values(): try: p.kill() except OSError as e: print("+++", "Exception killing process", type(e), pid) p.wait()
from game import init, gameloop if __name__ == '__main__': init() gameloop()
import pygame,rabbyt,sys import game,data import logging logging.basicConfig(level=5,stream=sys.stdout,format='%(levelname)s: %(name)s - %(message)s') log = logging.getLogger("core") def init(): log.info("Setting up") pygame.init() game.window = pygame.display.set_mode(game.config.size,game.config.screenargs) rabbyt.set_viewport(game.config.size) rabbyt.set_default_attribs() if __name__ == '__main__': init() data.init() game.init() game.loop()
import pygame import pickle import numpy as np from game import init, iterate from ann import NeuralNetwork import utils # Architecture (Specify archetecture here.) network = NeuralNetwork(layers=[7, 14, 14, 7, 1], activations=['sigmoid', 'sigmoid', 'sigmoid', 'tanh']) lr = 0.1 losses = [] screen, font = init() # Game Loop / Train Loop frame_count, score, _, _, x = iterate.iterate(screen, font, 0, 0) game = True run = True prediction = 0 while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False prediction = utils.forward(x, network) frame_count, score, game, run, x = iterate.iterate(screen, font, frame_count, score, game, run, prediction) loss = utils.backward(prediction, x, lr, network) losses.append(loss) pygame.quit()
def Button_Play(self): print("button play clicked") click_sound.play() game.init(WIDTH, HEIGHT) game.run(screen)
def main(): init( strategy=args.strategy, used_map=args.map ) start()
def init(): game.init() graphics.drawGame() graphics.update()
def play(): global game_over #initialize pygame & window screen = pygame.display.get_surface() #fill background bg = pygame.Surface((screen.get_size())) bg.fill(BG) bg = bg.convert() screen.blit(bg, (0, 0)) #initialize scoreboard score_board = Score(bg) score_board.game_over = game_over_screen score_board.win = win_screen #initialize the wall (bricks) wall, wall_g = init_wall(score_board) #initialize the bat bat = Bat(10) batsprite = pygame.sprite.RenderPlain(bat) #initialize the ball ball = Ball((255, 255, 255), 5, bat, wall, score_board) ballsprite = pygame.sprite.RenderPlain(ball) clock = pygame.time.Clock() pause = False game.init() t1 = threading.Thread(target=tutorial, args=()) t1.start() out_count = 0 while True: while pause == True: clock.tick(60) pygame.mouse.set_visible(True) pygame.display.flip() for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: bat.movepos = [0,0] pause = False game.resume() game.notify("Game Resumed") elif event.type == QUIT: sys.exit(0) else: game.handle_pause_event(event) while game_over == True: clock.tick(60) pygame.mouse.set_visible(True) game.game_over_screen() pygame.display.flip() for event in pygame.event.get(): if event.type == QUIT: sys.exit(0) else: game.handle_event(event) while win == True: clock.tick(60) pygame.mouse.set_visible(True) game.win_screen() pygame.display.flip() for event in pygame.event.get(): if event.type == QUIT: sys.exit(0) else: game.handle_win_event(event) #handle events while pause == False and game_over == False and win == False: clock.tick(60) #max frame rate for event in pygame.event.get(): if event.type == QUIT: sys.exit(0) if event.type == KEYDOWN: if event.key == K_LEFT: bat.moveleft() elif event.key == K_RIGHT: bat.moveright() elif event.key == K_SPACE: screen.blit(bg, ball.rect, ball.rect) ball.shoot() elif event.key == K_ESCAPE: pause = True game.pause() elif event.type == KEYUP: if event.key == K_LEFT or event.key == K_RIGHT: bat.movepos = [0, 0] elif event.type == MOUSEMOTION: pygame.mouse.set_visible(False) x, y = pygame.mouse.get_pos() bx, by = bat.rect.midtop if x > screen.get_width()-(bat.width/2): x = screen.get_width()-(bat.width/2) elif x < bat.width/2: x = bat.width/2 screen.blit(bg, bat.rect, bat.rect) bat.rect.midtop = (x,by) if not screen.get_rect().contains(ball.rect): out_count += 1 if out_count >= 10: score_board.die() else: out_count = 0 cols, side = break_wall(ballsprite, wall_g) if cols: if side is 'left' or side is 'right': ball.deflect(1.5) if side is 'top' or side is 'bottom': ball.deflect(2.5) elif side == 'topright' or side == 'topleft': ball.deflect(1) elif side == 'bottomright' or side == 'bottomleft': ball.deflect(1) else: ball.deflect(1) for i in range(len(cols)): cols[i].destroy() side = coll_side(ball.area.get_rect(), ball.rect, True, True) if side == 'top': score_board.die() if score_board.updated_level != 0: print 'speed increased' ball.increment_speed = 3 if pause == False: for y in range(5): for i in range(30): if wall[y][i].destroyed == False: screen.blit(bg, wall[y][i].rect, wall[y][i].rect) #wall[y][i].destroy() score_board.update() screen.blit(bg, bat.rect, bat.rect) screen.blit(bg, ball.rect, ball.rect) ballsprite.update() batsprite.update() ballsprite.draw(screen) batsprite.draw(screen) wall_g.draw(screen) pygame.display.update()
vote.draw() def input(self, events): if self.mode != 'title': self.begin_button.input(events) for s in self.links: s.input(events) for e in events: if e.type == pygame.KEYDOWN and e.key == pygame.K_SPACE and self.paused: pass def from_script(val): result = CommentGame() print vars(val) val.comment1result = json.loads(val.comment1result) val.comment2result = json.loads(val.comment2result) val.comment3result = json.loads(val.comment3result) result.generate(val.article, val.comment1, val.comment1result, val.comment2, val.comment2result, val.comment3, val.comment3result) return result if __name__ == '__main__': game.init() game.screen = screen.Screen() cg = CommentGame() cg.act() cg.draw()
def learn(self): matrix = game.init() score = 0 run = True while run: inputs = [] outputs = [] for i in matrix: if i[0] == i[1]: inputs.append(1) else: inputs.append(-1) if i[0] == i[2]: inputs.append(1) else: inputs.append(-1) if i[0] == i[3]: inputs.append(1) else: inputs.append(-1) if i[1] == i[2]: inputs.append(1) else: inputs.append(-1) if i[1] == i[3]: inputs.append(1) else: inputs.append(-1) if i[2] == i[3]: inputs.append(1) else: inputs.append(-1) for i in range(4): if matrix[0][i] == matrix[1][i]: inputs.append(1) else: inputs.append(-1) if matrix[0][i] == matrix[2][i]: inputs.append(1) else: inputs.append(-1) if matrix[0][i] == matrix[3][i]: inputs.append(1) else: inputs.append(-1) if matrix[1][i] == matrix[2][i]: inputs.append(1) else: inputs.append(-1) if matrix[1][i] == matrix[3][i]: inputs.append(1) else: inputs.append(-1) if matrix[2][i] == matrix[3][i]: inputs.append(1) else: inputs.append(-1) for i in matrix: sum1 = 0 for x in i: if x != -1: sum1 += 1 inputs.append(sum1) for i in range(4): sum1 for x in range(4): if matrix[x][i] != -1: sum1 += 1 inputs.append(sum1) inputs.append(1) h1 = NeuralNetwork.sigmoid(np.dot(inputs, w1)) h1 = np.append(h1, 1) h2 = NeuralNetwork.sigmoid(np.dot(h1, w2)) h2 = np.append(h2, 1) h3 = NeuralNetwork.sigmoid(np.dot(h2, w3)) h3 = np.append(h3, 1) outputs = NeuralNetwork.sigmoid(np.dot(h3, w4)) for i in range(4): index = NeuralNetwork.index(self, outputs, i) temp = game.do(matrix, score, index) matrix = temp[0] score = temp[1] run = temp[3] if temp[2] == True: break return score