def set_game_path(self, path): self.game_path = path self.gp.folder.setText(path) self.games = [] if os.path.isdir(Gui.resolved_path(path)): for dirpath, dirnames, filenames in os.walk(Gui.resolved_path(path)): # dirnames[:] = [] for fname in filenames: fpath = os.path.join(dirpath, fname) mgamefilename = re.compile('(.+)Vs(.+)\.([0-9]+)$') m = mgamefilename.match(fname) if m: self.games.append(GameFile(fname, m.group(1), m.group(2), int(m.group(3)), fpath)) if len(self.games): self.gp.status.setText("%d games found" % len(self.games)) self.gp.status.setPalette(Gui.BLUE_TEXT) else: self.gp.status.setText("No games found in '%s'" % path) self.gp.status.setPalette(Gui.RED_TEXT) else: self.gp.status.setText("No folder '%s'" % path) self.gp.status.setPalette(Gui.RED_TEXT) self.gs.combo.clear() self.gs.combo.addItem('Select a game') self.games.sort(key=attrgetter('sort_key')) for g in self.games: self.gs.combo.addItem(str(g)) self.gp.next.setEnabled(len(self.games) > 0) self.gs.next.setEnabled(False)
def runTestTransform(self, xOffset, yOffset, x, y, correction, expectedResult): gui = Gui(ModelMock(), None) gui.xOffset = xOffset gui.yOffset = yOffset actualResult = gui._transform(x, y, correction) self.assertEqual(actualResult, expectedResult)
def __init__(self, data_handler): QMainWindow.__init__(self) self.__data_handler = data_handler self.resize(1400, 840) self.setWindowTitle('gui main window') self.pipelineWidget = PipelineWidget(self, data_handler) self.canvas_map = Gui.Map2D(data_handler, self) self.canvas_map.create_native() self.canvas_map.native.setParent(self) self.canvas_3d = Gui.Canvas3D(data_handler, self, self.pipelineWidget.current_data) self.canvas_3d.create_native() self.canvas_3d.native.setParent(self) self.listWidget = Gui.BuildingListWidget(self, data_handler) self.setupLayout() #self.__focus_building_id = 0 self.set_slice(1592) #1593 self.show()
def mainloop(): # Objects collide with things objects = [Ship(), SpaceObj()] # Effects don't. effects = [] objects[1].moveToXYZ(10.0, 0.0, 5.0) # What we're aiming the camera at target = objects[0] then = pygame.time.get_ticks() frames = 0 while True: now = pygame.time.get_ticks() dt = now - then event = pygame.event.poll() if not handleEvents(event): break handlePlayerEvents(target, dt) for x in objects: x.calc(dt) for x in effects: x.calc(dt) drawStuff(target, objects, effects) Gui.drawCompass(target) Gui.drawVector(target) pygame.display.flip() frames += 1 then = now return frames
def setup(self): """ Initialize the GUI and place it properly. """ # Create the main menu font. WELCOME_FONT_TITLE = pygame.font.SysFont('Consolas', 28) WELCOME_FONT_INSTRUCTIONS = pygame.font.SysFont('Consolas', 20) # Create the title display. self.title_display = Gui.DisplayableText(value='num.type', font=WELCOME_FONT_TITLE, color=Color(rgb=Color.WHITE), align='cc') self.title_display.set_position(640 / 2, 40) self.add_gui(self.title_display) self.title_colors = [ Color(rgb=(200, 20, 20)), Color(rgb=(200, 200, 20)), Color(rgb=(20, 200, 20)), Color(rgb=(20, 200, 200)), Color(rgb=(20, 20, 200)), Color(rgb=(200, 20, 200)) ] self.title_color_current = 0 self.title_color_next = 1 self.title_color_current_began_at = get_ticks() # Create the subtitle display. self.subtitle_display = Gui.DisplayableText( value='a numerical typing game', font=WELCOME_FONT_TITLE, color=Color(rgb=Color.WHITE), align='cc') self.subtitle_display.set_position(640 / 2, 70) self.add_gui(self.subtitle_display) self.subtitle_color_current = 1 self.subtitle_color_next = 2 # Create the instructions display. self.instr_displays = [] instructions = [ 'Attempt to type in numbers as fast as you can.', 'You can only use the numeric keyboard.', 'Every time you "shoot" a target in time, it will grant', 'you points.', 'Every time you miss, you will lose one heart,', 'so type carefully.', 'You can use backspace if you mistype.', 'If a target times out, you will lose points.', 'The game will become progressively harder as you play.', 'Win by accumulating {} points.'.format(VICTORY_POINTS), 'Lose by going below 0 points or losing all hearts.', '', 'Press ENTER to begin.', 'Pressing ESCAPE at any time will end the game in defeat.', 'Good luck!' ] for instruction in instructions: new_display = Gui.DisplayableText(value=instruction, font=WELCOME_FONT_INSTRUCTIONS, color=Color(rgb=Color.WHITE), align='lc') new_display.set_position(20, 120 + 23 * len(self.instr_displays)) self.instr_displays.append(new_display) self.add_gui(new_display)
def right_diag_win(board, position, player): """ This function checks if the user's token has just made a connect 4 in a right diagonal. Input: 2d array board, coordinaes of placed token, players turn Output: Boolean deciding whether the player has won. """ row, col = position pot_coords = pot_layout.r_diag_layout(row, col) if pot_coords == None: return 0 for i in range(len(pot_coords) - 2): layout = [ board[pot_coords[i][0], pot_coords[i][1]], board[pot_coords[i + 1][0], pot_coords[i + 1][1]], board[pot_coords[i + 2][0], pot_coords[i + 2][1]] ] if layout.count(player) >= 3: gui.visualize_winning_tokens( board, [(pot_coords[i][0], pot_coords[i][1]), (pot_coords[i + 1][0], pot_coords[i + 1][1]), (pot_coords[i + 2][0], pot_coords[i + 2][1]), position]) return True return False
def env_change(): global count '''while True: time.sleep(120)''' wall_change() count = 0 Gui.env_change()
class Game: def __init__(self, mx=10, my=10): self.board = Board(mx, my) self.gui = Gui(mx, my) self.last = sdl2.SDLK_UP self.dir = { sdl2.SDLK_UP: [-1, 0], sdl2.SDLK_DOWN: [1, 0], sdl2.SDLK_LEFT: [0, -1], sdl2.SDLK_RIGHT: [0, 1], } def start(self): run = True self.board.init_board() while run: for e in sdl2.ext.get_events(): if e.type == sdl2.SDL_QUIT: exit() if e.type == sdl2.SDL_KEYDOWN: k = e.key.keysym.sym if k in self.dir.keys() and self.last != k: self.last = self.check_key(k) if k == sdl2.SDLK_ESCAPE: self.quit() run = self.move(self.dir[self.last]) self.gui.aff(self.board.get_map()) sdl2.SDL_Delay(200) sdl2.ext.quit() return 0 def check_key(self, k): l = self.dir[self.last] n = self.dir[k] return self.last if n[0] == l[0] or n[1] == l[1] else k def move(self, d): h = self.board.get_head() n = (h[0] + d[0], h[1] + d[1]) self.board.set_head(n[0], n[1]) if self.board.body.is_body(n): return False if self.board.apple.is_apple(n): self.board.body.rise(d) self.board.apple.set_apple(self.board.get_map()) elif self.board.cherry.is_cherry(self.board.get_map(), n): self.board.body.rise(d) self.board.cherry.set_cherry(self.board.get_map()) else: self.board.body.move(d) self.board.update_board() ret = self.board.is_wall(n) return ret def aff(self): self.gui.draw(self.board) def quit(self): exit()
def solve_maze(grid_dimensions, obstacle_coords, start_pos, end_pos) : """Solves the given maze""" start = time.time() path = Bot.solve_maze(grid_dimensions, end_pos, start_pos, obstacle_coords) print("Elapsed time = {}".format(time.time() - start)) Gui.display_path(path)
def __init__(self, score): pygame.key.set_repeat(500, 50) self.buttons = {} self.score = score self.buttons['Add'] = Gui.StandardButton((400, 350, 60, 30), "Add score", center_x=True, font_size=40) self.font = pygame.font.SysFont('Arial', 30) self.textbox = Gui.TextBox(300, 200, 200, 45, enter_action=self.enter_action) super().__init__()
def desktop(): global global_entryPath global global_exitPath if in_out == "in": global_entryPath = "C:\\Users\\" + os.getlogin() + "\\Desktop\\" elif in_out == "out": global_exitPath = "C:\\Users\\" + os.getlogin() + "\\Desktop\\" Gui.window_vis(path_app, -1) Gui.kys(path_app)
def main(): n = 0 agent_name = [] argv = sys.argv GUI = True STOP = False argv.pop(0) i = 0 c = 1 while i < len(argv): x = argv[i] x = x.lower() if x in ['s1', 's2', 'mc', 'dp', 'rd']: agent_name.append(x) elif x == '-g': GUI = True elif x == '-s': STOP = True elif x == '-n': i += 1 x = argv[i] x = x.lower() if isinstance(int(x), int): c = int(x) else: print "Command '-n' should be followed by an intager." print "ERROR command ("+argv[i]+") !!!" sys.exit(-1) else: print "ERROR command ("+argv[i]+") !!!" sys.exit(-1) i += 1 if GUI: app, Form = Gui.app_Form() ui = Gui.Ui_Form() ui.setupUi(Form, app) sys.exit(app.exec_()) else: win = np.zeros((2,2)) while len(agent_name) < 2: agent_name.append('rd') #win = [[# of playerA win, step of playerA], # [# of playerB win, step of playerB]] win = np.zeros((2,2)) for i in range(c): print "#", i win += Game(agent_name, STOP) print "Win percentage of playerA: ", float(win[0, 0])/c print "Average steps of playerA takes to win:", float(win[0, 1])/float(win[0, 0]) if win[0, 0] != 0 else 0 print "Win percentage of playerB: ", float(win[1, 0])/c print "Average steps of playerB takes to win:", float(win[1, 1])/float(win[1, 0]) if win[1, 0] != 0 else 0
def __init__(self, parent, offlineMode=False): """ Recorder constructor """ self.parent = parent self.offlineMode = offlineMode Gui.initialize(parent=self, offlineMode=offlineMode, mainParent=parent) self.createActions()
def __init__(self, mx=10, my=10): self.board = Board(mx, my) self.gui = Gui(mx, my) self.last = sdl2.SDLK_UP self.dir = { sdl2.SDLK_UP: [-1, 0], sdl2.SDLK_DOWN: [1, 0], sdl2.SDLK_LEFT: [0, -1], sdl2.SDLK_RIGHT: [0, 1], }
def finalize(): """ Destroy Singleton """ global Recorder if Recorder: if sys.platform == "win32": Gui.finalize() del Recorder Recorder = None
def __init__(self): self.buttons = {} self.leaderboards_box = Gui.LeaderboardsBox(20, 80, 760, 500) try: self.leaderboards_box.add_cell_data(pickle.load(open("scores.dat", "rb"))) # this sorts the list so the highest score is at the top. Defaults to small to big to you have to reverse it self.leaderboards_box.cell_data.sort(key=operator.itemgetter('score'), reverse=True) except: self.leaderboards_box.cell_data = [] self.buttons['Main Menu'] = Gui.StandardButton((100, 20, 60, 30), 'Main Menu', font_size=40) super().__init__()
def run(): global app #Instantiate our app and Gui stuff. app = QApplication(sys.argv) gui = Gui() gui.on('release', doRelease) #Make the cursor the "cross cursor" for effect app.setOverrideCursor(QCursor(Qt.CrossCursor)) #Exit when our app exits sys.exit(app.exec_())
def main(): try: model = Model() controller = Controller(model) controller.start() gui = Gui(model, controller) gui.show() controller.stop() except FatalException, exc: print('Fehler', exc.getMessage())
def start(self): # I don't think I need further access to instances, but I'll save them anyway # self.root = tk.Tk() self.parent = QtWidgets.QApplication([]) # Gui to handle all main window operations self.guiO = Gui.Observer( ) # model observer callbacks to presenter set here self.guiM = Gui.Model('gui') self.guiV = Gui.View(self.parent) self.guiI = Gui.Interactor( ) # widget event callbacks to presenter set here self.guiP = Gui.Presenter(self.guiV, self.guiI, self.guiM, self.guiO) # Menu for Gui self.menuO = MenuBar.Observer() self.menuM = MenuBar.Model('menu') self.menuV = MenuBar.View(self.guiV) self.menuI = MenuBar.Interactor() self.menuP = MenuBar.Presenter(self.menuV, self.menuI, self.menuM, self.menuO) # # Testing window self.testO = TestWindow.Observer() self.testM = TestWindow.Model('test') self.testV = TestWindow.View(self.guiV) self.testI = TestWindow.Interactor() self.testP = TestWindow.Presenter(self.testV, self.testI, self.testM, self.testO) # # # Generic # self.genM = GenericWindow.Model('generic', {'gui': self.guiM}) # self.genV = GenericWindow.View(self.guiV.window) # self.genP = GenericWindow.Presenter(self.genV, self.genM) # Image labeling window self.imagesM = Images.Model('images') self.labelerO = LabelerWindow.Observer() self.labelerM = LabelerWindow.Model('labeler') self.labelerV = LabelerWindow.View(self.guiV) self.labelerI = LabelerWindow.Interactor() self.labelerP = LabelerWindow.Presenter(self.labelerV, self.labelerI, self.labelerM, self.labelerO) # Options window self.optionsO = OptionsWindow.Observer() self.optionsM = OptionsWindow.Model('options') self.optionsV = OptionsWindow.View(self.guiV) self.optionsI = OptionsWindow.Interactor() self.optionsP = OptionsWindow.Presenter(self.optionsV, self.optionsI, self.optionsM, self.optionsO) # Make labeler the default window self.guiM.window_model_activate('labeler')
def listener_LoadProject(self): # PREGUNTAR POR GUARDAR ANTES EL PROYECTO ACTUAL. home = os.path.expanduser(PV['defaultPath']) fileName = Gui.loadDialog(self.view, home) if fileName[0]: qDebug('Loading project from ' + self._nfc(fileName[0])) msg = self.parser.load(fileName[0]) # return Bool, Deque self._renderAllScenes() self._cureStatesTree() if msg > 0: Gui.loadErrorDialog(self.view, msg) qDebug('Issues with: ' + self._nfc(fileName[0]))
def init_game(): """ This function initializes the game and displays the board. Input: None Output: The initialized board """ board = mp.init_board() gui.display_board(board) player_one = rules.choose_turn() player_two = rules.get_opponent(player_one) return board, player_one, player_two
def closeEvent(self, ev): # Guardar reply = Gui.exitSaveDialog(self) if reply == QMessageBox.Ok: self.emit_SaveProject() # Salir reply2 = Gui.exitDialog(self) if reply2 == QMessageBox.Ok: qDebug(PV['endMsg']) ev.accept() else: ev.ignore()
def done(): global global_entryPath global global_exitPath if text.get() != "": temp = text.get() else: temp = "" if in_out == "in": global_entryPath = temp elif in_out == "out": global_exitPath = temp Gui.window_vis(path_app, -1) Gui.kys(path_app)
def connect_four(): """ This function plays the connect four game is the main function of this project. Input: None Output: Winner of the Connect 4 Game """ board, player_one, player_two = init_game() game_in_progress = True curr_player = player_one winner = None while game_in_progress and mp.full_board(board) == False: gui.display_board(board) if curr_player == ai_player: position = mc.next_move(board, curr_player) if curr_player == other_player: position = mp.random_next_move(board, curr_player) if rules.won_game(board, position, curr_player): game_in_progress = False winner = curr_player if winner == ai_player: gui.create_message(f'AI Player has won Connect Four!') if winner == other_player: gui.create_message(f'Other Player Two won Connect Four!') gui.display_board(board) curr_player = rules.get_opponent(curr_player) # time.sleep(10) return winner
def test_options(self): d = dict(a=1, b=2, c=3) res = Gui.pop_options(d, ['b']) self.assertEquals(len(res), 1) self.assertEquals(len(d), 2) res = Gui.get_options(d, ['a', 'c']) self.assertEquals(len(res), 2) self.assertEquals(len(d), 2) res = Gui.remove_options(d, ['c']) self.assertEquals(len(d), 1) d = dict(side=1, column=2, other=3) options, packopts, gridopts = Gui.split_options(d) self.assertEquals(len(options), 1) self.assertEquals(len(packopts), 1) self.assertEquals(len(gridopts), 1) Gui.override(d, side=2) self.assertEquals(d['side'], 2) Gui.underride(d, column=3, fill=4) self.assertEquals(d['column'], 2) self.assertEquals(d['fill'], 4)
def test_options(self): d = dict(a=1, b=2, c=3) res = Gui.pop_options(d, ['b']) self.assertEqual(len(res), 1) self.assertEqual(len(d), 2) res = Gui.get_options(d, ['a', 'c']) self.assertEqual(len(res), 2) self.assertEqual(len(d), 2) res = Gui.remove_options(d, ['c']) self.assertEqual(len(d), 1) d = dict(side=1, column=2, other=3) options, packopts, gridopts = Gui.split_options(d) self.assertEqual(len(options), 1) self.assertEqual(len(packopts), 1) self.assertEqual(len(gridopts), 1) Gui.override(d, side=2) self.assertEqual(d['side'], 2) Gui.underride(d, column=3, fill=4) self.assertEqual(d['column'], 2) self.assertEqual(d['fill'], 4)
def main(): num_moves = 0 num_iterations = 0 board = np.zeros((BoardSize.size(), BoardSize.size())) Gui.display_board(board) x = 0 # x is the column you are in. imagine x and y as a x-y plot. while x < BoardSize.size(): # If the column is full then backtracing is necessary: if MoveQueen.next_available_row(board=board, x=x) == -1: x -= 1 y = MoveQueen.find_y(board=board, x=x) MoveQueen.backtrace(x=x, y=y, board=board) Gui.display_board(board) num_moves += 1 num_iterations += 1 else: y = MoveQueen.next_available_row(board=board, x=x) MoveQueen.drop_queen(x=x, y=y, board=board) Gui.display_board(board) x += 1 num_moves += 1 Gui.create_message("SUCESS!") time.sleep(5) print(board) print( f"The average number of iterations in DFS are {num_iterations}.\nThe average number of moves in DFS are {num_moves}." )
def Execute(Sender): import math yList = sorted(p[1] for p in Graph.Selected.Points) N = len(yList) Sum = math.fsum(yList) Mean = Sum / N Form = Gui.SimpleDialog(Caption="Statistics", Height=220, ShowCancel=False) Lines = "Statistics for " + Graph.Selected.LegendText + ":" Lines += "\n Mean:\t\t" + format(Mean, ".8g") Lines += "\n Sum:\t\t" + str(Sum) Lines += "\n Median:\t\t" + format( yList[N // 2] if N % 2 else (yList[N // 2 - 1] + yList[N // 2]) / 2, ".8g") Lines += "\n Standard deviation: " + format( math.sqrt(math.fsum([(y - Mean)**2 for y in yList]) / N), ".8g") Lines += "\n 1st quartile:\t" + str(yList[N // 4] if (N // 2) % 2 else (yList[N // 4 - 1] + yList[N // 4]) / 2) Lines += "\n 3rd quartile:\t" + str(yList[math.ceil(N / 2) + N // 4] if ( N // 2) % 2 else (yList[math.ceil(N / 2) + N // 4 - 1] + yList[math.ceil(N / 2) + N // 4]) / 2) Lines += "\n Min:\t\t" + str(min(yList)) Lines += "\n Max:\t\t" + str(max(yList)) Memo = vcl.TMemo(None, Parent=Form.panel, ReadOnly=True, Align="alClient", Color=-16777201, WantReturns=False) Memo.Font.Size = 10 Memo.Lines.Text = Lines Form.ShowModal()
def __init__(self): super().__init__() self.app = QApplication(sys.argv) self.window = gui.GUI() self.displayTh = display.display() self.dataTh = data.TestData() WaveGen.UZPOut.generateLUT() # self.datatimer = QTimer() # self.datatimer.setInterval(10) # self.datatimer.timeout.connect(self.dataTh.start) self.disptimer = QTimer() self.disptimer.setInterval(c.PERIOD_OF_DISP) self.disptimer.timeout.connect(self.displayTh.start) self.window.startScanning.connect(self.startScans) self.window.endScanning.connect(self.endScans) self.displayTh.loadedImage.connect(self.relayImage) # self.dataTh.loadedImage.connect(self.relayImage) self.sendImage.connect(self.window.showGivenImage) self.window.show() sys.exit(self.app.exec_())
def recorderEngaged(self): """ Return if the recorder mode is engaged """ if Gui.instance().recorderActivated: return True return False
def snapshotEngaged(self): """ Return if the snapshot mode is engaged """ if Gui.instance().snapshotActivated: return True return False
def test_canvas(self): gui = Gui.Gui() ca = gui.ca() self.assertEqual(ca.width, 100) self.assertEqual(ca.height, 100) point = [50, 50] box = [[100, 200], [300, 500]] item = ca.arc(box) self.assertTrue(isinstance(item, Gui.Item)) item = ca.line(box) self.assertTrue(isinstance(item, Gui.Item)) item = ca.oval(box) self.assertTrue(isinstance(item, Gui.Item)) item = ca.circle(point, 25) self.assertTrue(isinstance(item, Gui.Item)) item = ca.polygon(box) self.assertTrue(isinstance(item, Gui.Item)) item = ca.rectangle(box) self.assertTrue(isinstance(item, Gui.Item)) item = ca.text(point, 'text') self.assertTrue(isinstance(item, Gui.Item))
def main(): gui = Gui() rawData = readDataset(dataPath) data = parseData(rawData) gui.drawData(data) training, heldout, test = divideData(data) rawdata = unlableData(heldout) for sample in heldout: classification = classify(training, sample) print(sample, classification) gui.getMouse()
def on_browse_folder(self): dialog = QtGui.QFileDialog() dialog.setFileMode(QtGui.QFileDialog.Directory) dialog.setOption(QtGui.QFileDialog.ShowDirsOnly, True) path = dialog.getExistingDirectory(self, 'Directory', Gui.resolved_path(self.default_game_path)) if path: self.set_game_path(path) self.main_window.board_view.setFocus()
def test_bbox(self): bbox = Gui.BBox([[100, 200], [300, 500]]) self.assertEquals(bbox.left, 100) self.assertEquals(bbox.right, 300) self.assertEquals(bbox.top, 200) self.assertEquals(bbox.bottom, 500) self.assertEquals(bbox.width(), 200) self.assertEquals(bbox.height(), 300) # TODO: upperleft, lowerright, midright, midleft, center, union t = bbox.flatten() self.assertEquals(t[0], 100) pairs = [pair for pair in Gui.pairiter(t)] self.assertEquals(len(pairs), 2) seq = Gui.flatten(pairs) self.assertEquals(len(seq), 4)
def display(): def display_QR(): qr_bitstring = polynomials.QRbitstring(entry.get().upper()) i = 0 for i in range(8): canvas = mygui.ca(width=300, height=300) canvas.config(bg='white') g = Mask(i, qr_bitstring) g.drawSquares(canvas) g = Mask(0, qr_bitstring) mygui = Gui() mygui.title('QR Encoder') label = mygui.la(text='Enter the text to encode here:') entry = mygui.en() button = mygui.bu(text='Make QR Code', command=display_QR) mygui.gr(cols=4) mygui.mainloop()
def main(): gui = Gui() rawData = readDataset(dataPath) data = parseData(rawData) gui.drawData(data) # training, heldout, test = divideData(data) gui.getMouse() weights = learn(data) if numClass == 2: gui.drawDivision(weights[0]) gui.getMouse()
def instructions(): # Display Instructions in a new window i = Gui() i.title ("Instructions") text = i.te (height = 42, width = 150, fg = 'darkblue') text.insert (END, " ************************************\n") text.insert (END, " **** Black Jack Instructions ****\n") text.insert (END, " ************************************\n\n") text.insert (END, "Objective: The objective of the game is beat the dealer. In order to win, you must have the most points\n without going over 21\n\n") text.insert (END, "Terms:\n") text.insert (END, " Hit - Get dealt another card\n") text.insert (END, " Stay - Stop with the amount of cards you have\n") text.insert (END, " Bust - To go over 21\n") text.insert (END, "\n\n") text.insert (END, "First thing you do is place a bet. The minimum accepted is $5. The maximum is limited to how much $ you\n have.\n") text.insert (END, "You and the dealer are then given two cards each. You can draw cards with the 'Hit me!' button. If you\n bust you cannot draw more cards.\n") text.insert (END, "When you are happy with your cards press the 'Stay!' button. Once this happens it's the dealers turn.\n") text.insert (END, "\n\n") text.insert (END, "The Rules:\n") text.insert (END, " Whoever is closest to 21 with going over wins.\n") text.insert (END, " If you both have the same amount, the dealer wins.\n") text.insert (END, " If you bust and the dealer doesn't you lose.\n") text.insert (END, " If the dealer busts and you don't, you win.\n") text.insert (END, " If both you and the dealer bust, you win\n") text.insert (END, "\n\n") text.insert (END, " Cards Values:") text.insert (END, " 2 -> 2 pts\n") text.insert (END, " 3 -> 3 pts\n") text.insert (END, " 4 -> 4 pts\n") text.insert (END, " 5 -> 5 pts\n") text.insert (END, " 6 -> 6 pts\n") text.insert (END, " 7 -> 7 pts\n") text.insert (END, " 8 -> 8 pts\n") text.insert (END, " 9 -> 9 pts\n") text.insert (END, " 10 -> 10 pts\n") text.insert (END, " Jack -> 10 pts\n") text.insert (END, " Queen -> 10 pts\n") text.insert (END, " King -> 10 pts\n") text.insert (END, " Ace -> 1 pt or 11 pts\n") text.insert (END, "\n\n")
def on_init(self): pygame.init() self._running = True #instantinate gui self.g = Gui() #instantinate player self.p = [] for i in range(2): self.p.append(Player(i)) self.turn = 0
def make_gui(self): # The Player Menu temp_text = "Insert Text here" self.player_menu = Gui(self.menu_imgs[0], self.size, 1.5) self.player_menu.make_dynamic_text((155, 130), str(self.player.level), (255, 0, 0)) self.player_menu.make_dynamic_text((300, 70), self.player.name, (0,0,0)) self.player_menu.make_dynamic_text((450, 150), self.player.title, (0,0,0), 30) self.player_menu.make_dynamic_text((64, 440), temp_text, (0,0,0), 20) self.player_menu.make_dynamic_text((300, 500), temp_text, (0,0,0), 20) self.player_menu.make_button("exit", (50, 30), (1300, 51), "Exit") self.p_menu = [0.0, False] # HUD Powers buttons self.powers_gui = Gui(self.menu_imgs[2], self.size, 12) self.powers_gui.new_rect.topleft = ((self.size[0] / 22),(self.size[1] / 20 * 18)) self.powers_gui.make_dynamic_text((18, 22), "1", (255, 0, 0)) self.powers_gui.make_dynamic_text((78, 22), "2", (255, 0, 0)) self.powers_gui.make_dynamic_text((138, 22), "3", (255, 0, 0)) self.powers_gui.make_dynamic_text((198, 22), "4", (255, 0, 0)) self.powers_gui.make_dynamic_text((258, 22), "5", (255, 0, 0)) self.powers_gui.make_dynamic_text((318, 22), "6", (255, 0, 0)) self.powers_gui.make_dynamic_text((378, 22), "7", (255, 0, 0)) self.powers_gui.make_dynamic_text((438, 22), "8", (255, 0, 0)) # Setting up the Mouse over self.mouseover = MouseOver(self.menu_imgs[-1])
def run(self): self.g=Gui() self.g.title('Control Panel') #charge self.chgla=self.g.la(text='Charge') self.g.gr(cols=3) minus=self.g.bu(text='-', command=Callable(self.addC, -1)) self.chg=self.g.en() plus=self.g.bu(text='+', command=Callable(self.addC, 1)) self.g.endgr() #position self.pos=self.g.la(text='Position') self.g.gr(cols=3) xla=self.g.la(text='x') yla=self.g.la(text='y') zla=self.g.la(text='z') self.x=self.g.en(text='') self.y=self.g.en(text='') self.z=self.g.en(text='') self.g.endgr() #menu self.men=self.g.mb(text='Change/ Add Charge') hi=self.g.mi(self.men, text='Add point charge', command=Callable(self.addPoint)) self.g.mi(self.men, text='Add line charge', command=Callable(self.addLine)) self.g.mi(self.men, text='Find voltage at point', command=self.findVolt) #add self.g.row([1,1]) self.add=self.g.bu(text='Add') self.rem=self.g.bu(text='Delete', command=self.remove) self.g.endrow() #self.g.bu(text='Quit', command=self.end) self.disp=self.g.mb(text='Voltage Field') self.g.mi(self.disp, text='Voltage Field', command=self.showv) self.g.mi(self.disp, text='Electric Field', command=self.showe) #ans self.ans=self.g.la(text='') self.field.start() for chrg in self.field.charges: chrg.makeMi() self.g.mainloop()
def main(): p1Gui = Gui("Player 1", 1) p2Gui = Gui("Player 2", 2) pos1 = getRandPos() pos2 = getRandPos() agent = Agent() opAction = [0,0,0] result2 = None p1Gui.drawStar(pos1) while True: print(pos2) type1, param1 = opponent(p1Gui, p2Gui) result1 = executeHumanAction(p1Gui, p2Gui, type1, param1, pos1, pos2) if type1 == move: direction = p1Gui.getDirection(pos1, param1) pos1 = param1 param1 = direction p1Gui.clean() p1Gui.drawStar(pos1) opAction[0] = type1 opAction[1] = param1 opAction[2] = result1 type2, param2 = agent.play(2, result2, opAction, pos2) result2 = executeCpuAction(p1Gui, type2, param2, pos2, pos1) if type2 == move: pos2 = param2
from Gui import * g=Gui() g.title("Gui") button=g.bu(text="Press me.") def make_label(): g.la(text="Thank you.") botton2=g.bu(text="No, Press me!",command=make_label()) g.mainloop()
def main(argv): if argv[0] == "GUI": Gui.display() elif argv[0] == "barrier": compute(float(argv[1]), float(argv[2]), float(argv[3]))
from Gui import * g = Gui() g.title('More widgets') entry = g.en(text='Default text.') text = g.te(width=100, height=5) text.insert(END, 'A line of text.') g.mainloop()
from Gui import * g = Gui() g.title('circle demo') canvas = g.ca(width=500, height=500, bg='white') circle = None def callback1(): """called when the user presses 'create circle' """ global circle circle = canvas.circle([0,0], 100) def callback2(): """called when the user presses 'Change color' """ # if the circle hasn't been created yet, do nothing if circle == None: return # get the text from the entry and try to change the circle's color color = entry.get() try: circle.config(fill=color) except TclError: # probably an unknown color name print(message) # create the widgets g.bu(text='Create circle', command=callback1) entry = g.en() g.bu(text='Change color', command=callback2)
from Gui import * g = Gui() g.title('Blue Rectangle') canvas = g.ca(width=500, height=500) canvas.rectangle([[0, 0], [200, 100]], fill='blue', outline='orange', width=10) canvas.oval([[0, 0], [200, 100]], outline='orange', width=10) canvas.line([[0, 100], [100, 200], [200, 100]], width=10) canvas.polygon([[0, 100], [100, 200], [200, 100]], fill='red', outline='orange', width=10) g.mainloop()
from Gui import * g = Gui() g.title('Gui Title') # 1ST kind of TEXT entry = g.en(text='Default text.') # 2ND kind of TEXT text = g.te(width=100, height=5) text.insert(END, 'abc') text.insert(1.1, 'xyz') # row.column # Get function: # text.get(0.0, END) # text.delete(1.2, END) g.mainloop()
def create_circle(): global item item = c.circle([0,0],100,fill='red') def change_color(): try: if 'item' in globals(): item.config(fill=entry.get()) else: g.la(text='First create a circle!!!') return except : g.la(text='Invalid color') from Gui import * g = Gui() b1 = g.bu(text='Press to create a circle',command=create_circle) c = g.ca(width=500,height=500) entry=g.en(text='enter the color') b2 = g.bu(text='Press to change color of circle',command=change_color) g.mainloop()
def main(): gui = Gui() generateGhost() iniProbs = getInitialDist() particles = distributeParticles(particleNum, iniProbs) probs = getProbs(particles) while True: gui.drawProb(probs) pos = gui.getMouse() if pos[1] > numRow-1: if pos[0] >= numRow/2: gui.setBlackColors() moveGhost() particles = moveParticles(particles) probs = getProbs(particles) else: gui.drawEndBtn("blue") pos = gui.getMouse() result = isGhostThere(pos) gui.drawResult(pos, result) revealGhost() break else: color = useSensor(pos) gui.drawSensorReading(pos, color) condProbs = getNewPosDist(pos, color, probs) weights = weightParticles(particles, condProbs) normWeights = normalize(weights) particles = redistributeParticles(particles, normWeights) probs = getProbs(particles) gui.getMouse()
def insert(obj): cal_in.insert(END,obj) def delete(p): cal_in.delete(p) print p,len(cal_in.get())-1,cal_in.get() from Gui import * cal=Gui() cal.title('Calculator') cal_in = cal.en(width=35) cal.row() cal.gr(cols=6) seven = cal.bu(text='7',command = Callable(insert,'7')) eight = cal.bu(text='8',command = Callable(insert,'8')) nine = cal.bu(text='9',command = Callable(insert,'9')) div = cal.bu(text='/',command = Callable(insert,'/')) #bspace = cal.bu(text='Del',command = Callable(delete,0)) bspace = cal.bu(text='Del',command = Callable(delete,len(cal_in.get())-1)) clr = cal.bu(text='Clr',command = Callable(delete,'7')) four = cal.bu(text='4',command = Callable(insert,'4')) five = cal.bu(text='5',command = Callable(insert,'5')) six = cal.bu(text='6',command = Callable(insert,'6')) mul = cal.bu(text='*',command = Callable(insert,'*'))
if os.path.isfile(filename): yield filename file_list = getfilenames('.') def next_file(): for import os from Gui import * from Tkinter import * from PIL import Image as PIL import ImageTk g=Gui() g.title('Image viewer') c=g.ca(width=500,height=500) image_viewer('.') g.bu(image=p2) """ try: image = PIL.open(filename) photo = ImageTk.PhotoImage(image) c.image([0,0],image=photo) except IOError:
def __init__(self): self.server = xmlrpclib.ServerProxy('http://localhost:8006') self.gui = Gui(self) self.currentProject = None
class Client: def __init__(self): self.server = xmlrpclib.ServerProxy('http://localhost:8006') self.gui = Gui(self) self.currentProject = None def start(self): self.gui.showMainMenu() self.gui.root.mainloop() def createNewProject(self,projectName): self.currentProject = Project(projectName) def loadProject(self,projectName): serializedProject = self.server.requestProjectLoad(projectName) if serializedProject == -1: #Project not found, create one self.createNewProject(projectName) else: self.currentProject = pickle.loads(serializedProject) def tryLoadTextFileIntoProject(self): if self.currentProject != None: self.currentProject.text = self.gui.getFileContentFromDialog("Ouvrir un fichier texte","Text file","*.txt") else: self.gui.loadProject() #self.gui.showMessage("Erreur","Vous devez charger ou créer un projet avant de charger le texte de l'analyse textuelle") def tryPerformTextAnalysis(self, howManyTry = 0): if self.currentProject != None and self.currentProject.text != None: text = self.currentProject.text sortedWords = self.currentProject.sortedWords self.currentProject.sortedWords = self.gui.getSortedWordsFromTextAnalysisForm(self.currentProject.name,text, sortedWords) elif self.currentProject != None and howManyTry == 0: self.tryLoadTextFileIntoProject() self.tryPerformTextAnalysis(1) elif self.currentProject != None and howManyTry == 1: self.gui.showMessage("Erreur","Vous devez charger le texte pour faire l'analyse textuelle") else: self.gui.loadProject() self.tryPerformTextAnalysis() #self.gui.showMessage("Erreur","Vous devez charger ou créer un projet avant de faire l'analyse textuelle") def tryEditUseCases(self): if self.currentProject != None: useCaseList = self.currentProject.useCaseList sortedWords = self.currentProject.sortedWords self.currentProject.useCaseList = self.gui.getUseCaseListFromUseCaseForm(self.currentProject.name,useCaseList,sortedWords) else: self.gui.loadProject() self.tryEditUseCases() def tryEditCrcs(self): if self.currentProject != None: crcList = self.currentProject.crcList sortedWords = self.currentProject.sortedWords self.currentProject.crcList = self.gui.getCrcListFromCrcForm(self.currentProject.name,crcList,sortedWords) pass def tryEditScrums(self): if self.currentProject != None: scrumList = self.currentProject.scrumList sortedWords = self.currentProject.sortedWords self.currentProject.scrumList = self.gui.getScrumListFromScrumForm(self.currentProject.name,scrumList,sortedWords, self.currentProject.sprintList) pass def tryEditSprints(self): if self.currentProject != None: sprintList = self.currentProject.sprintList sortedWords = self.currentProject.sortedWords self.currentProject.sprintList = self.gui.getSprintListFromSprintForm(self.currentProject.name, self.currentProject.sprintList,sortedWords) def tryShowTreeView(self): if self.currentProject == None: self.gui.showMessage("Erreur","Vous devez charger un projet") else: self.gui.showTreeView(self.currentProject, self) def saveCurrentProject(self): if self.currentProject != None: serializedProject = pickle.dumps(self.currentProject) self.server.sendProject(serializedProject) else: self.gui.showMessage("Erreur","Vous devez créer ou charger un projet pour le sauvegarder") def getProjectNameList(self): projectNameList = self.server.getProjectNameList() return pickle.loads(projectNameList)
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <codecell> from Gui import * g = Gui() g.title('Gui') g.mainloop() # <codecell> button = g.bu(text='Press me.') label = g.la(text='Press the button.') # <codecell>
from Gui import * def make_label(): g.la(text = 'Thank you.') g = Gui() g.title('Gui Title') button = g.bu(text = 'Press ME.') label = g.la(text = 'LABEL') button2 = g.bu(text = 'XYZ', command = make_label) g.mainloop()
from Gui import * g = Gui() g.title('Gui') g.mainloop()
class Panel2(Thread): def __init__(self,field): Thread.__init__(self) self.field=field self.field.panel=self self.activeCharge=None self.sel=None self.g=None def run(self): self.g=Gui() self.g.title('Control Panel') #charge self.chgla=self.g.la(text='Charge') self.g.gr(cols=3) minus=self.g.bu(text='-', command=Callable(self.addC, -1)) self.chg=self.g.en() plus=self.g.bu(text='+', command=Callable(self.addC, 1)) self.g.endgr() #position self.pos=self.g.la(text='Position') self.g.gr(cols=3) xla=self.g.la(text='x') yla=self.g.la(text='y') zla=self.g.la(text='z') self.x=self.g.en(text='') self.y=self.g.en(text='') self.z=self.g.en(text='') self.g.endgr() #menu self.men=self.g.mb(text='Change/ Add Charge') hi=self.g.mi(self.men, text='Add point charge', command=Callable(self.addPoint)) self.g.mi(self.men, text='Add line charge', command=Callable(self.addLine)) self.g.mi(self.men, text='Find voltage at point', command=self.findVolt) #add self.g.row([1,1]) self.add=self.g.bu(text='Add') self.rem=self.g.bu(text='Delete', command=self.remove) self.g.endrow() #self.g.bu(text='Quit', command=self.end) self.disp=self.g.mb(text='Voltage Field') self.g.mi(self.disp, text='Voltage Field', command=self.showv) self.g.mi(self.disp, text='Electric Field', command=self.showe) #ans self.ans=self.g.la(text='') self.field.start() for chrg in self.field.charges: chrg.makeMi() self.g.mainloop() def showv(self): self.disp.config(text='Voltage Field') self.actf=self.field.vfield self.acte=self.field.vdots self.field.change=True for p in self.field.earrows: self.field.earrows[p].visible=False for p in self.field.vdots: self.field.vdots[p].visible=True def showe(self): self.disp.config(text='Electric Field') self.field.actf=self.field.efield self.field.acte=self.field.earrows self.field.change=True for p in self.field.earrows: self.field.earrows[p].visible=True for p in self.field.vdots: self.field.vdots[p].visible=False def addPoint(self): self.men.config(text='Add Point') self.pos.config(text='Position') self.add.config(command=Callable(self.addPCharge)) def addLine(self): self.men.config(text='Add Line') self.pos.config(text='Equation in terms of t') self.add.config(command=Callable(self.addLCharge)) self.field.change=True def addPCharge(self): pos=(int(self.x.get()), int(self.y.get()), int(self.z.get())) c=float(self.chg.get()) p=Point(pos=pos, charge=c) self.addCharge(p) def addLCharge(self): eqn=(self.x.get(), self.y.get(), self.z.get()) dens=self.chg.get() p=Line(eqn=eqn, density=dens) self.addCharge(p) def addCharge(self,p): self.field.charges.append(p) self.field.change=True p.panel=self p.makeMi() def findVolt(self): self.add.config(text='Get Voltage', command=self.getVolt) def getVolt(self): p=(int(self.x.get()), int(self.y.get()), int(self.z.get())) v=vAtPoint(p, self.field.charges) self.ans.config(text='Voltage at (%d, %d, %d): %g k'%(p[0],p[1],p[2],v)) def remove(self): if not self.sel: return c=self.sel i=self.field.charges.index(c) self.men.menu.delete(i+3) self.field.charges.remove(c) c.s.visible=False del(c) self.field.change=True self.sel=None def select(self, charge): if self.sel: self.sel.revert() self.sel=charge charge.s.color=(1,1,1) self.updateLa() self.add.config(text='Update', command=Callable(self.update)) def update(self): ch=self.chg.get() x,y,z=self.x.get(), self.y.get(), self.z.get() if len(ch)>0: self.sel.updateCharge(ch) self.updatePos(x,y,z) self.sel.updateMi() self.field.change=True def updateLa(self): self.chgla.config(text='Charge: %s'%str(self.sel.charge)) p=self.sel.pos self.pos.config(text='Position: (%s, %s, %s)'%(str(p[0]), str(p[1]), str(p[2]))) def addC(self, n): if not self.sel: return if isinstance(self.sel, Point): self.sel.charge+=n elif isinstance(self.sel, Line): self.sel.charge+=str(n) self.field.change=True self.updateLa() def updatePos(self, x,y,z): if not self.sel: return self.sel.updatePos(x,y,z) def end(self): self.field.go=False