def __init__(self, WIDTH, HEIGHT, LEFT_VERT, RIGHT_VERT, TOP_HORIZ, BOTTOM_HORIZ): self.WIDTH = WIDTH self.HEIGHT = HEIGHT self.TH = TOP_HORIZ self.BH = BOTTOM_HORIZ self.LV = LEFT_VERT self.RV = RIGHT_VERT self.SPACING = 75 self.EAT_DIST = 57 # changed for pacman to eat dots on the verges # Initialize four rows of dots, based on spacing and width of the maze self.top_row = [ Dot(self.SPACING * i, self.TH) for i in range(self.WIDTH // self.SPACING + 1) ] self.bottom_row = [ Dot(self.SPACING * i, self.BH) for i in range(self.WIDTH // self.SPACING + 1) ] self.left_col = [ Dot(self.LV, self.SPACING * i) for i in range(self.HEIGHT // self.SPACING + 1) ] self.right_col = [ Dot(self.RV, self.SPACING * i) for i in range(self.HEIGHT // self.SPACING + 1) ]
def __init__(self, WIDTH, HEIGHT, LEFT_VERT, RIGHT_VERT, TOP_HORIZ, BOTTOM_HORIZ, game_controller): self.WIDTH = WIDTH self.HEIGHT = HEIGHT self.TH = TOP_HORIZ self.BH = BOTTOM_HORIZ self.LV = LEFT_VERT self.RV = RIGHT_VERT self.SPACING = 75 self.EAT_DIST = 60 self.gc = game_controller # Initialize four rows of dots, based on spacing and width of the maze self.top_row = [ Dot(self.SPACING * i, self.TH) for i in range(self.WIDTH // self.SPACING + 1) ] self.bottom_row = [ Dot(self.SPACING * i, self.BH) for i in range(self.WIDTH // self.SPACING + 1) ] self.left_col = [ Dot(self.LV, self.SPACING * i) for i in range(self.HEIGHT // self.SPACING + 1) ] self.right_col = [ Dot(self.RV, self.SPACING * i) for i in range(self.HEIGHT // self.SPACING + 1) ] self.total = self.top_row + self.bottom_row + self.left_col \ + self.right_col
def get_c_start(start_dot, new_a, e1, t): # Пересчёт координат точек-рычагов v_x = new_a.x + (e1.x - new_a.x) / (1 - t) v_y = new_a.y + (e1.y - new_a.y) / (1 - t) v = Dot(v_x, v_y, "qwe", []) control_start_x = start_dot.x + (v.x - start_dot.x) / t control_start_y = start_dot.y + (v.y - start_dot.y) / t control_start = Dot(control_start_x, control_start_y, "lever", []) return control_start
def test_with_given_non_different_dots_should_return_zero(self): #ASSER coordinates = (0, 0) dot_1 = Dot(coordinates) dot_2 = Dot(coordinates) expected_distance = 0 #ACT result_distance = dot_1.distance_to_dot(dot_2) #ASSERT self.assertEqual(result_distance, expected_distance)
def get_c_end(end_dot, new_a, e2, t): # Пересчёт координат точек-рычагов v_x = new_a.x + (e2.x - new_a.x) / t v_y = new_a.y + (e2.y - new_a.y) / t v = Dot(v_x, v_y, "qwe", []) control_end_x = end_dot.x + (v.x - end_dot.x) / (1 - t) control_end_y = end_dot.y + (v.y - end_dot.y) / (1 - t) control_end = Dot(control_end_x, control_end_y, "lever", []) return control_end
def test_with_given_different_dots_should_return_correct_distance(self): #ASSET coordinates_for_dot_1 = (0, 1) coordinates_for_dot_2 = (2, 0) dot_1 = Dot(coordinates_for_dot_1) dot_2 = Dot(coordinates_for_dot_2) expected_distance = 2.24 #ACT result_distance = dot_1.distance_to_dot(dot_2) #ASSERT self.assertEqual(result_distance, expected_distance)
def run_game(): #Initialize game and create screen object pygame.init() pygame.mixer.music.load('sounds/background.wav') pygame.mixer.music.play(-1) coin_sound = pygame.mixer.Sound("sounds/coin_collect.wav") create_sound = pygame.mixer.Sound("sounds/create.wav") delete_sound = pygame.mixer.Sound("sounds/delete.wav") # gameover_sound = pygame.mixer.Sound("sounds/gameover.wav") lin_settings = Settings() stats = GameStats(lin_settings) stats.initialize_high_score() screen = pygame.display.set_mode( (lin_settings.screen_width,lin_settings.screen_height), pygame.FULLSCREEN) pygame.display.set_caption("Lines") print(lin_settings.screen_width, lin_settings.screen_height) sb = Scoreboard(lin_settings, screen, stats) dot = Dot(screen) coin = Coin(screen, lin_settings) play_button = Button(lin_settings, screen, "Play", (screen.get_rect().centerx + 250, 40), (0, 255, 0)) # undo_button = Button(lin_settings, screen, "Undo", (screen.get_rect().centerx - 250, 40), (255, 255, 0)) #main loop of the game while True: gf.check_events(screen, dot, stats, coin, lin_settings, sb, play_button, create_sound, coin_sound, delete_sound) gf.update_screen(lin_settings, screen, dot, coin, sb, stats, play_button)
def __init__(self): self.generation = 0 self.dots = [] self.old_dots = [] for i in range(SIZE_OF_POPULATION): self.dots.append( Dot(DOT_START_X_POSITION, DOT_START_Y_POSITION, MAX_STEPS))
def main(): """ a kind of self tests""" from dot import Dot from point import Point df = FigureDecorator(Dot(Point(100, -310))) print(df) print(repr(df))
def makeFood(screen, Alldots): line = "" allLines = [] deltaX = 0 deltaY = 0 file = open("pacmanportalmaze.txt", "r") if file.mode == 'r': contents = file.read() for chars in contents: if chars != '\n': line += chars else: allLines.append(line) line = "" for line in allLines: for char in line: if char == 'd': newDot = Dot(screen) newDot.rect.x, newDot.rect.y = deltaX, deltaY Alldots.add(newDot) deltaX += 13 deltaX = 0 deltaY += 13
def get_a(B, C, ratio): # Вычисление точек А, по B, C и константному отношению a_x = B.x - (C.x - B.x) / ratio a_y = B.y - (C.y - B.y) / ratio a = Dot(a_x, a_y, "qwe", []) return a
def move(self, xDirection, yDirection, eatApple=False): # xDirection and yDirection will determine the direction of the snake # move snake for i in range(len(self.dots) - 1, 0, -1): self.dots[i].x = self.dots[i - 1].x self.dots[i].y = self.dots[i - 1].y self.dots[0].x += cfg.C_S * xDirection self.dots[0].y += cfg.C_S * yDirection if eatApple: x = self.dots[len(self.dots) - 1].x + cfg.C_S * xDirection y = self.dots[len(self.dots) - 1].y + cfg.C_S * yDirection self.len += 1 self.dots.append(Dot(self.window, x, y, self.color)) # when the snake touches the edges if self.dots[0].x >= cfg.W - cfg.RIGHT_SPACE: self.dots[0].x = 0 if self.dots[0].x < 0: self.dots[0].x = cfg.W - cfg.RIGHT_SPACE - cfg.C_S if self.dots[0].y >= cfg.H: self.dots[0].y = 0 if self.dots[0].y < 0: self.dots[0].y = cfg.H - cfg.C_S
def __init__(self): super(Arena, self).__init__(250, 255, 255, 255, definition.WIDTH, definition.HEIGHT) #起始位置 self.center = (director.get_window_size()[0] / 2, director.get_window_size()[1] / 2) #batches self.batch = cocos.batch.BatchNode() self.add(self.batch) #加入用户蛇身 self.snake = Snake() self.snake.life = 3 # 因为技术太烂,所以做了个修改版,多加了几条命 self.add(self.snake, 10000) self.snake.init_body() self.accel = Audio('assets/audio/accel.wav') self.accel.set_volume(0.6) #加入七个bot self.enemies = [] for i in range(7): self.add_enemy() #按下键集合 self.keys_pressed = set() for i in range(50): # 布置食物 self.batch.add(Dot()) #注册事件(每帧调用一次update函数) self.schedule(self.update)
def makeMap(self, blocks, dots, powerPills): size = self.settings.rectSize for row in self.lines: for chars in row: if chars == "X": newBlock = Blocks(self.screen) newBlock.rect.x, newBlock.rect.y = self.xShift, self.yShift self.xShift += size blocks.add(newBlock) elif chars == ".": newDot = Dot(self.screen, self.settings) newDot.rect.x, newDot.rect.y = self.xShift +size/4, self.yShift +size/4 self.xShift += size dots.add(newDot) elif chars ==" ": self.xShift += size elif chars == "o": newPill = PowerPill(self.screen, self.settings) newPill.rect.x, newPill.rect.y = self.xShift +size/4, self.yShift +size/4 powerPills.add(newPill) self.xShift += size elif chars == "x": newBlock = Blocks(self.screen) newBlock.rect.x, newBlock.rect.y = self.xShift, self.yShift newBlock.type = 1 self.xShift += size blocks.add(newBlock) self.xShift = 0 self.yShift += size
def game_loop(): dots = [] dots_in_cirlce = [] pi = None #draw the citcle in the center as well as the line of the bottom pygame.draw.circle(win, white, (width//2, height//2), width//2) pygame.draw.circle(win, black, (width//2, height//2), width//2-5) pygame.draw.rect(win, white, (0, height, width, 5)) run = True while run: pygame.time.delay(5) #check for user pressing x for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() #win.fill(black) #create a new dot wit uniformly random coordinates new_dot = Dot(random.uniform(-1,1), random.uniform(-1,1)) #add the dot to the list of all dots and if it is in the circle add it to the list of the dots in the circle dots.append(new_dot) if new_dot.in_circle(): dots_in_cirlce.append(new_dot) #after 100 dots the value of pi is updated if len(dots) % 100 == 0: pi = pi_update(len(dots_in_cirlce), len(dots)) #checks what color the dot should be drawn color = lambda d: green if d.in_circle() else red #cover the old vlaue of pi in black then draw the new one pi_text, pi_text_rect = make_text(str(pi), (width//2, height+ 30), (255,255,255)) pygame.draw.rect(win, black, (0, height+5, width, 45)) win.blit(pi_text, pi_text_rect) #draw the dot pygame.draw.circle(win, color(new_dot), get_drawing_coords(new_dot), 1) pygame.display.flip()
def test_with_given_route_should_return_correct_distance(self): #ASSET coordinates_for_dot_1 = (0, 2) coordinates_for_dot_2 = (2, 1) coordinates_for_dot_3 = (2, 2) dot_1 = Dot(coordinates_for_dot_1) dot_2 = Dot(coordinates_for_dot_2) dot_3 = Dot(coordinates_for_dot_3) dots = [dot_1, dot_2, dot_3] route = Route(dots) expected_distance = 3.24 #ACT result_distance = route.distance #ASSERT self.assertEqual(result_distance, expected_distance)
def get_e1(cur_dot, old_e1, B): # Пересчет точек второй итерации алгоритма де Кастельжо e1_x = old_e1.x + (cur_dot.x - B.x) e1_y = old_e1.y + (cur_dot.y - B.y) e1 = Dot(e1_x, e1_y, "qwe", []) return e1
def get_e2(cur_dot, old_e2, B): # Пересчет точек второй итерации алгоритма де Кастельжо e2_x = old_e2.x + (cur_dot.x - B.x) e2_y = old_e2.y + (cur_dot.y - B.y) e2 = Dot(e2_x, e2_y, "qwe", []) return e2
def get_new_a(cur_dot, C, ratio): # Пересчет значения A для нового положения точки кривой new_a_x = cur_dot.x - (C.x - cur_dot.x) / ratio new_a_y = cur_dot.y - (C.y - cur_dot.y) / ratio new_a = Dot(new_a_x, new_a_y, "qwe", []) return new_a
def get_l( end_dot, control_end, t ): # Вычисление точек второй итерации алгоритма де Кастельжо для визуализации l_x = control_end.x + (end_dot.x - control_end.x) * t l_y = control_end.y + (end_dot.y - control_end.y) * t l = Dot(l_x, l_y, "qwe", []) return l
def get_old_e1(start_dot, old_control_start, old_control_end, t): # Находим точки второй итерации алгоритма де Кастельжо k_x = start_dot.x + (old_control_start.x - start_dot.x) * t k_y = start_dot.y + (old_control_start.y - start_dot.y) * t k = Dot(k_x, k_y, "qwe", []) j_x = old_control_start.x + (old_control_end.x - old_control_start.x) * t j_y = old_control_start.y + (old_control_end.y - old_control_start.y) * t j = Dot(j_x, j_y, "qwe", []) old_e1_x = k.x + (j.x - k.x) * t old_e1_y = k.y + (j.y - k.y) * t old_e1 = Dot(old_e1_x, old_e1_y, "qwe", []) return old_e1
def get_old_e2(end_dot, old_control_end, old_control_start, t): # Вычисление точек второй итерации алгоритма де Кастельжо k_x = old_control_end.x + (end_dot.x - old_control_end.x) * t k_y = old_control_end.y + (end_dot.y - old_control_end.y) * t k = Dot(k_x, k_y, "qwe", []) j_x = old_control_start.x + (old_control_end.x - old_control_start.x) * t j_y = old_control_start.y + (old_control_end.y - old_control_start.y) * t j = Dot(j_x, j_y, "qwe", []) old_e2_x = j.x + (k.x - j.x) * t old_e2_y = j.y + (k.y - j.y) * t old_e2 = Dot(old_e2_x, old_e2_y, "qwe", []) return old_e2
def get_c(start_dot, end_dot, t): # Вычисление C по точкам начала кривой, конца кривой и t u = (1 - t)**3 / (t**3 + (1 - t)**3) c_x = u * start_dot.x + (1 - u) * end_dot.x c_y = u * start_dot.y + (1 - u) * end_dot.y c = Dot(c_x, c_y, "qwe", []) return c
def get_k( start_dot, control_start, t ): # Вычисление точек второй итерации алгоритма де Кастельжо для визуализации k_x = start_dot.x + (control_start.x - start_dot.x) * t k_y = start_dot.y + (control_start.y - start_dot.y) * t k = Dot(k_x, k_y, "qwe", []) return k
def get_j( control_start, control_end, t ): # Вычисление точек второй итерации алгоритма де Кастельжо для визуализации j_x = control_start.x + (control_end.x - control_start.x) * t #_! j_y = control_start.y + (control_end.y - control_start.y) * t #_! j = Dot(j_x, j_y, "qwe", []) #_! return j
def crash(self): # 碰撞处理 if not self.is_dead: self.is_dead = True # 状态设定为死亡 self.unschedule(self.update) # 在时间安排表中移除更新 self.unschedule(self.ai) # 在时间安排表中移除怪物 arena = self.parent # 传入arena for b in self.body: # 分解身体为Dot arena.batch.add(Dot(b.position, b.color)) arena.batch.add(Dot(b.position, b.color)) arena.batch.remove(b) # 从batch中移除 arena.remove(self) # 从arena中移除 arena.add_enemy() # 重新添加新的怪物 del self.path # 删除记录的路径 if self.is_enemy: # 死的是怪物 arena.enemies.remove(self) # 从enemies中移除 del self.body # 删除 del self else: arena.parent.end_game() # 死的是玩家则游戏结束
def crash(self): if not self.is_dead: self.is_dead = True self.unschedule(self.update) self.unschedule(self.ai) arena = self.parent for b in self.body: arena.batch.add(Dot(b.position, b.color)) arena.batch.add(Dot(b.position, b.color)) arena.batch.remove(b) arena.remove(self) arena.add_enemy() del self.path if self.is_enemy: arena.enemies.remove(self) del self.body del self else: arena.parent.end_game()
def parse_file(filename): f = open(filename) line = f.readline() dots=[] while line != '': # Converting the input line into a list of numbers values = [] num = '' line = line.rstrip('\n') line = line.replace(',', ' ') line = line.split() for d in line: if d == line[-1]: break values.append(float(d)) d=Dot(values) d.clas = line[-1] dots.append(d) line = f.readline() return dots
def add_dots(): global dots #clears existing dots first dots = [] for i in range(0, population, 1): r = random.randint(10, 254) g = random.randint(10, 254) b = random.randint(10, 254) dots.append( Dot(np.array([width / 2, height / 8]), np.array([0, 0]), np.array([0, 0]), NULL, [r, g, b])) dots[i].brain = Brain(brain_size)
def new_pop(self): pop = [] Theta1, Theta2 = self.get_weights(self.gen, self.Theta1, self.Theta2) for i in range(self.number): x = constants.x_dot_start y = constants.y_dot_start dot = Dot(x, y, Theta1[i], Theta2[i], self.game_matrix) pop.append(dot) self.Theta1, self.Theta2 = Theta1, Theta2 return pop
def mouse_l(event): ex = event.x ey = SCREEN_HEIGHT - event.y x.append(normalize(ex, 0, SCREEN_WIDTH)) y.append(normalize(ey, 0, SCREEN_HEIGHT)) Dot(canvas, ex, ey, DOT_SIZE_RADIUS) text = "(%d, %d)" % (ex, 500 - ey) canvas.create_text(ex, 500 - ey - 15, fill="white", text=text, font=("Purisa", 10))
from constants import * pygame.init() #screen canvas infoObject = pygame.display.Info() WIDTH = infoObject.current_w HEIGHT = infoObject.current_h x = 50 y = HEIGHT // 2 - RADIUS print "RUNNING PYGAME" dot1 = Dot(x, y) print "DOT CLASS INITALIZED" dot1.Network_startgame(data) clock = pygame.time.Clock() #fps # Event loop while True: # if data['gameid'] == 0: #user key controls for event in pygame.event.get(): #space key is pressed down if event.type == QUIT: endProgram = True
done = True if event.type == KEYDOWN: if event.key == K_SPACE: run = not run can_change = False screen.blit(bg, [0, 0]) key = pygame.key.get_pressed() mouse = pygame.mouse.get_pressed() pos_mouse = pygame.mouse.get_pos() if mouse[0] and can_change: if start_point is None: start_point = Dot( location=pos_mouse, screen=screen, type=0) else: start_point.location = pos_mouse if mouse[2] and can_change: if end_point is None: end_point = Dot( location=pos_mouse, screen=screen, type=2) else: end_point.location = pos_mouse if start_point is not None: start_point.draw() if end_point is not None:
def main(): """ Our main function :return: None """ # Color Palette and other Variables back_color = color_rgb(249,205,173) fill_color= color_rgb(252,157,154) out_color = color_rgb(254,67,101) point_color = color_rgb(131,175,155) line_color = color_rgb(200,200,169) WIN_WIDTH = 800 WIN_HEIGHT = 800 dialog = 0 userDots = [] userLines = [] defaultPoint = Dot(Circle(Point(0,0), 3), Text(Point(0,0), "0")) defaultPoint.setFill(point_color) defaultPoint.setTextColor(out_color) # GUI Objects! buttonText = ['T','C','S','L','E'] buttons = [] saveload = [] totalButtons = len(buttonText) B_WIDTH = 25 B_HEIGHT = 25 MARGIN = 10 # Window Creation win = GraphWin("Connect The Dots!", WIN_WIDTH, WIN_HEIGHT) win.setBackground(back_color) # Creating buttons, buttons consist of a text element and a rectangle element for index in range(totalButtons): # Creating button anchor point itself anchorPoint = Point(WIN_WIDTH - ((totalButtons - index) * MARGIN) - ((totalButtons - index) * B_WIDTH), MARGIN) # Add it to our button list buttons.append(createButton(anchorPoint, B_WIDTH, B_HEIGHT, buttonText[index], fill_color, out_color)) for button in buttons: button.draw(win) # Creating Save/Load Box anchorPoint = Point(WIN_WIDTH - (WIN_WIDTH / 4) - MARGIN, MARGIN * 2 + B_HEIGHT) rectSizePoint = Point(WIN_WIDTH - MARGIN, anchorPoint.getY() + MARGIN * 3 + B_HEIGHT * 2) rect = Rectangle(anchorPoint, rectSizePoint) rect.setOutline(out_color) rect.setFill(fill_color) saveload.append(rect) entryPoint = Point(anchorPoint.getX()+MARGIN, anchorPoint.getY()+2*MARGIN) entryWidth = (rectSizePoint.getX() - anchorPoint.getX() - 2 * MARGIN) / 10 entry = Entry(entryPoint, int(entryWidth)) entry.setTextColor(out_color) entry.setStyle("bold") entry.setFace("courier") entry.setSize(12) entry.setFill(line_color) entry.move(entryWidth * 5, 0) saveload.append(entry) line = Line(Point(WIN_WIDTH - 92.5, 35), Point(WIN_WIDTH - 92.5, 45)) line.setOutline(out_color) saveload.append(line) # Save/Load Button, added to our list anchorPoint = Point(rectSizePoint.getX() - (WIN_WIDTH / 4) + MARGIN, rectSizePoint.getY() - MARGIN - B_HEIGHT) buttons.append(createButton(anchorPoint, (WIN_WIDTH / 4) - MARGIN * 2, B_HEIGHT, "Save", fill_color, out_color)) # Not a button but a dialog anchorPoint = Point(WIN_WIDTH - (WIN_WIDTH / 4) - MARGIN, MARGIN*6+B_HEIGHT*3) dialog = createButton(anchorPoint, WIN_WIDTH / 4, B_HEIGHT, "DIALOG", fill_color, out_color) # Logic Loop changesFlag = False confirmFlag = False while True: try: pointClicked = win.getMouse() except GraphicsError: # Only happens when window is closed through the exit button return None if buttons[0].isClicked(pointClicked): # Tracer button pressed, toggle lines between points buttons[0].toggleButton() # Show toggle on or off and update lines if buttons[0].isToggled(): buttons[0].setFill(line_color) for line in userLines: line.draw(win) else: buttons[0].setFill(fill_color) for line in userLines: line.undraw() elif buttons[1].isClicked(pointClicked): # Clear screen pressed, remove dots / lines for dot in userDots: dot.undraw() for line in userLines: line.undraw() # Clear records userDots.clear() userLines.clear() # Remove flags confirmFlag = False changesFlag = False elif buttons[2].isClicked(pointClicked): # Open or close Save menu, close load menu if it is opened buttons[2].toggleButton() # Remove dialog is it is open if dialog.isToggled(): dialog.toggleButton().undraw() # If the load button is toggled open, "close" it if buttons[3].isToggled(): buttons[3].toggleButton() buttons[5].setText("Save") saveload[2].move(-B_WIDTH-MARGIN, 0) # If the save button is toggled closed, remove windows elif not buttons[2].isToggled(): for element in saveload: element.undraw() buttons[5].undraw() # Open the buttons else: for element in saveload: element.draw(win) buttons[5].setText("Save") buttons[5].draw(win) # Reset confirmation flag in case there are any unsaved changes confirmFlag = False elif buttons[3].isClicked(pointClicked): # Open or close load menu, close save menu if it is opened buttons[3].toggleButton() # Remove dialog is it is open if dialog.isToggled(): dialog.toggleButton().undraw() # If the save button is toggled open, "close" it if buttons[2].isToggled(): buttons[2].toggleButton() buttons[5].setText("Load") saveload[2].move(+B_WIDTH+MARGIN, 0) # If the load button is toggled closed, remove windows elif not buttons[3].isToggled(): for element in saveload: element.undraw() buttons[5].undraw() saveload[2].move(-B_WIDTH-MARGIN, 0) # Open the buttons else: for element in saveload: element.draw(win) buttons[5].setText("Load") buttons[5].draw(win) saveload[2].move(+B_WIDTH+MARGIN, 0) # Reset confirmation flag in case there are any unsaved changes confirmFlag = False elif buttons[4].isClicked(pointClicked): # Exit button pressed, closing program win.close() return None elif buttons[5].isClicked(pointClicked) and(buttons[2].isToggled() or buttons[3].isToggled()): # Save/Load Button hit fileName = saveload[1].getText() # If the save button is open, save the points after checking file name if fileName is "": fileName = "untitled.txt" # To make sure we are saving a text file if fileName.find(".txt") == -1 or fileName.find(".txt") != len(fileName) - 4: fileName += ".txt" # If save option is open if buttons[2].isToggled(): # Open file outfile = open(fileName, "w") # Write to file pointsStr = "" for dot in userDots: pointsStr += str(int(dot.getCenter().getX())) + " " + str(int(dot.getCenter().getY())) + " " outfile.write(pointsStr) # Close file outfile.close() # Save successful dialog.setText("File saved successfully!").setSize(12) if not dialog.isToggled(): dialog.draw(win).toggleButton() changesFlag = False confirmFlag = True # If save isn't open, load must be open else: # If the load button is open, load the points after checking file name # Checking if any unsaved changes are present t = None if changesFlag and not confirmFlag: confirmFlag = True dialog.setText("Unsaved changes, load anyway?").setSize(9) if not dialog.isToggled(): dialog.draw(win).toggleButton() # Checking if we confirmed, made separately to ensure load clicked twice else: # Clear changes flag changesFlag = False # Clear current points for point in userDots: point.undraw() for line in userLines: line.undraw() userDots.clear() userLines.clear() # Verify file if os.path.isfile(fileName): # Open the file infile = open(fileName, "r") # Get the points within the file try: coord = [int(x) for x in infile.readline().split()] if len(coord) % 2 == 1: coord.pop() if len(coord) > 1: for index in range(1, len(coord), 2): tmp = defaultPoint.clone() tmp.setText(len(userDots) + 1) tmp.move(coord[index-1], coord[index]) tmp.draw(win) userDots.append(tmp) except ValueError: errorfile = open("error_log.txt", "w") errorfile.write("File contained a type that could not be converted to int.") errorfile.close() dialog.setText("File load unsuccessful.").setSize(9) if not dialog.isToggled(): dialog.draw(win).toggleButton() continue # Recreate lines if len(userDots) > 0: prevPoint = None for nextPoint in userDots: if prevPoint is None: prevPoint = nextPoint else: lntmp = Line(prevPoint.getCenter(), nextPoint.getCenter()) lntmp.setFill(line_color) lntmp.setWidth(2) userLines.append(lntmp) prevPoint = nextPoint if buttons[0].isToggled(): lntmp.draw(win) # Close the file infile.close() # load successful dialog.setText("File loaded successfully!").setSize(12) if not dialog.isToggled(): dialog.draw(win).toggleButton() else: dialog.setText("No such file found.").setSize(12) if not dialog.isToggled(): dialog.draw(win).toggleButton() else: # Changes were made changesFlag = True # Draw points tmp = defaultPoint.clone() tmp.setText(len(userDots) + 1) tmp.move(pointClicked.getX(),pointClicked.getY()) tmp.draw(win) userDots.append(tmp) # Make the line, only drawn if tracer toggled if len(userDots) > 1: lntmp = Line(userDots[len(userDots)-2].getCenter(), userDots[len(userDots)-1].getCenter()) lntmp.setFill(line_color) lntmp.setWidth(2) userLines.append(lntmp) if buttons[0].isToggled(): lntmp.draw(win)