Ejemplo n.º 1
0
class MavenExecutor:	
	
	COMMAND = 'mvn'

	def __init__(self, phase, parameters):
		
		self.phase = phase	
	  	self.parameters = parameters
		self.painter = Painter()
  
	def execute(self, execution_targets):
		self.print_build_order(execution_targets)

		for target in execution_targets:
			self.painter.print_bright_purple( '[INFO] executing %s ' % (self.execute_command(target)) )
			return_code = system(self.execute_command(target))
			if return_code != 0:
				self.painter.print_red('[ERROR] on %s' % target)
				self.notify('maven build error')
				sys.exit

		self.painter.print_green('[SUCCESS]')
		self.notify('maven build successful')

	def print_build_order(self, execution_targets):
		self.painter.print_bright_purple('Will execute %s %s in :' % (MavenExecutor.COMMAND, self.phase))
		for target in execution_targets:
			self.painter.print_bright_purple('\t%s' % target)

	def execute_command(self, target):
		return '%s %s %s -f %s/pom.xml' % (MavenExecutor.COMMAND, self.phase, self.parameters, target)

	def notify(self, message):
		system('notify-send --urgency=critical "%s"' % message)
Ejemplo n.º 2
0
class Visualizer(QWidget):
    def __init__(self, json_dict, images_folder, window_width, window_height):
        super(Visualizer, self).__init__()
        self.threshold_selector = ThresholdSelector(show_delay=True)
        self.image_selector = ImageSelector(
            json_dict,
            images_folder,
            self.threshold_selector.get_current_threshold(),
            show_delay=True)
        self.viewer = Viewer(window_width, window_height)
        self.painter = Painter(json_dict, images_folder,
                               self.image_selector.get_current_image_idx(),
                               self.threshold_selector.get_current_threshold())
        self.image_selector.imageChanged.connect(self.painter.new_image)
        self.threshold_selector.thresholdChanged.connect(
            self.image_selector.new_threshold)
        self.threshold_selector.thresholdChanged.connect(
            self.painter.new_threshold)
        self.painter.boxesDrawn.connect(self.viewer.set_scene)
        self.init_UI()
        self.painter.draw(reset_scale=True)

    def init_UI(self):
        vbox = QVBoxLayout()
        vbox.addWidget(self.image_selector)
        vbox.addWidget(self.viewer)
        hbox = QHBoxLayout()
        hbox.addLayout(vbox)
        hbox.addWidget(self.threshold_selector)
        self.setLayout(hbox)
Ejemplo n.º 3
0
 def allLocationInitial(self):
     self.locationOfBase = self.baseLocationInitial()  # 基站位置初始化
     self.locationOfUser = self.userLocationInitial(
         radius=500,
         radius2=100,
     )  # 用户位置初始化 为了测试注解掉这个初始化
     paint = Painter()
     paint.paintBasesAndUsers(self.locationOfBase, self.locationOfUser)
Ejemplo n.º 4
0
 def __init__(self):
     self.painter = Painter()
     self.store = Store()
     self.selection_store = SelectionStore()
     self.object_factory = ObjectFactory(self.store)
     self.scene = Scene(self.store, self.painter, self.selection_store)
     self.object_state = False
     self.move_state = False
     self.curr_object = None
     self.last_object = False
Ejemplo n.º 5
0
def main():
    logger.info('Start')

    isShowMatrix = False
    isSaveMatrix = False

    dim = 1
    if dim == 1:
        f = lambda x: x*x
        q = lambda x: (5-abs(x-5)*1)*2
        domains = [[0,10,1]]
        elements = [2]
    elif dim == 2:
        f = lambda x,y: x*x
        q = lambda x,y: 0
        domains = [[0,1,0.1],[0,1,0.1]]
        elements = [1,1]
    elif dim == 3:
        f = lambda x,y,z: (x*x+y*y)*z
        q = lambda x,y,z: ((x*x+y*y)*z)*np.random.rand(1)*0.01 + (100 if abs(x-2.5) < 1 and abs(y-2.5) < 1 else 0)
        domains = [[0,5,0.5],[0,5,0.5],[-1,1,0.2]]
        elements = [2,2,1]

    K = 10

    f = PointsFabric(dim, f, q, domains)
    clear, noise = f.generate()

    s = Spline('input.txt', elements, K)
    s.MakeMatrix()

    if isSaveMatrix:
        np.savetxt('data/before_solveA.txt', s.A, fmt='%1.2e')
        np.savetxt('data/before_solveF.txt', s.F, fmt='%1.2f')
    if isShowMatrix:
        plt.matshow(s.A)
    ans = s.Solve()

    i = 0
    for a in ans:
        try:
            if len(a) == s.nNodes * (2**dim):
                np.savetxt(f'data/answer_{i}.txt', a, fmt='%1.2f')
                i += 1
        except Exception:
            pass

    p = Painter('data/answer_0.txt', dim, True, s._Spline__psi, K, s.elements, s.mx, s.kElem, s.h, clearPoints=noise)

    testFunc = lambda x,y,z: x+z
    p.Paint(True)
Ejemplo n.º 6
0
    def draw(self):
        painter = Painter(self.manager.drawing_surface())
        painter.clear(Colors.black)

        scorestr = "Score: " + str(self.score)
        highstr = "Highscore: " + str(self.high)
        newstr = "*** New highscore ***" if self.newhigh else ""

        painter.text((300, 280), scorestr, Colors.white)
        painter.text((300, 305), highstr, Colors.white)
        painter.text((300, 330), newstr, Colors.white)
Ejemplo n.º 7
0
 def test_MakeRightChessHorseJumpLMove(self):
     painter = Painter()
     painter.moveOneForward()
     painter.turnRight()
     painter.moveOneForward()
     painter.moveOneForward()
     self.assertEqual(2, painter.currentPositionObject.x)
     self.assertEqual(1, painter.currentPositionObject.y)
Ejemplo n.º 8
0
class CreateUI(QtGui.QDialog, Ui_Dialog):
    Brush = True
    DrawingShapes = Shapes()
    IsPainting = False
    IsEraseing = False

    CurrentColour = Colour3(0,0,0)
    CurrentWidth = 10
    ShapeNum = 0
    IsMouseing = False
    PaintPanel = 0
    #Constructor
    def __init__(self):
        super(QtGui.QDialog,self).__init__()
        self.setupUi(self)
        self.setObjectName('Rig Helper')
        self.PaintPanel = Painter(self)
        self.PaintPanel.close()
        self.DrawingFrame.insertWidget(0,self.PaintPanel)
        self.DrawingFrame.setCurrentWidget(self.PaintPanel)
        self.Establish_Connections()
    
    def SwitchBrush(self):
        if(self.Brush == True):
            self.Brush = False
        else:
            self.Brush = True
    
    def ChangeColour(self):
        col = QtGui.QColorDialog.getColor()
        if col.isValid():
            self.CurrentColour = Colour3(col.red(),col.green(),col.blue())
   
    def ChangeThickness(self,num):
        self.CurrentWidth = num
            
    def ClearSlate(self):
        self.DrawingShapes = Shapes()
        self.PaintPanel.repaint()  
        
              
    def Establish_Connections(self):
        QtCore.QObject.connect(self.BrushErase_Button, QtCore.SIGNAL("clicked()"),self.SwitchBrush)
        QtCore.QObject.connect(self.ChangeColour_Button, QtCore.SIGNAL("clicked()"),self.ChangeColour)
        QtCore.QObject.connect(self.Clear_Button, QtCore.SIGNAL("clicked()"),self.ClearSlate)
        QtCore.QObject.connect(self.Thickness_Spinner, QtCore.SIGNAL("valueChanged(int)"),self.ChangeThickness)
Ejemplo n.º 9
0
 def test_StartPositionPainter(self):
     painter = Painter()
     self.assertEqual(1, len(painter.map.knownCoordinatesObjects))
     self.assertEqual(['0x0y'], painter.map.knownCoordinatesNames)
     self.assertEqual(0, painter.currentPositionObject.x)
     self.assertEqual(0, painter.currentPositionObject.y)
     self.assertEqual(0, painter.currentPositionObject.value)
     self.assertEqual(12, painter.currentDirectionAsOnClock)
Ejemplo n.º 10
0
 def __init__(self):
     super(QtGui.QDialog,self).__init__()
     self.setupUi(self)
     self.setObjectName('Rig Helper')
     self.PaintPanel = Painter(self)
     self.PaintPanel.close()
     self.DrawingFrame.insertWidget(0,self.PaintPanel)
     self.DrawingFrame.setCurrentWidget(self.PaintPanel)
     self.Establish_Connections()
Ejemplo n.º 11
0
 def __init__(self, json_dict, images_folder, window_width, window_height):
     super(Visualizer, self).__init__()
     self.threshold_selector = ThresholdSelector(show_delay=True)
     self.image_selector = ImageSelector(
         json_dict,
         images_folder,
         self.threshold_selector.get_current_threshold(),
         show_delay=True)
     self.viewer = Viewer(window_width, window_height)
     self.painter = Painter(json_dict, images_folder,
                            self.image_selector.get_current_image_idx(),
                            self.threshold_selector.get_current_threshold())
     self.image_selector.imageChanged.connect(self.painter.new_image)
     self.threshold_selector.thresholdChanged.connect(
         self.image_selector.new_threshold)
     self.threshold_selector.thresholdChanged.connect(
         self.painter.new_threshold)
     self.painter.boxesDrawn.connect(self.viewer.set_scene)
     self.init_UI()
     self.painter.draw(reset_scale=True)
Ejemplo n.º 12
0
    def paintEvent(self, event=""):
        qp = Painter(self)
        qp.translate(self.height, 0)
        qp.rotate(90)

        # Enable antialiasing
        qp.setRenderHints(
            QPainter.Antialiasing | QPainter.SmoothPixmapTransform, True)

        self.drawField(qp)

        for enemy in self.enemies:
            enemy.draw(qp)

        for robot in self.robots:
            robot.draw(qp)

        self.ball.draw(qp)

        self.drawGoal(qp)
        qp.end()
Ejemplo n.º 13
0
    def redrawLevelCanvas(self):
	
	name = self.levelFilename + str(self.currLevel)
	f = open(name, 'r')
	levelMap = []
	while True:
	    line = f.readline()
	    if line == '':
		break
	    levelMap.append(line)
	f.close()
	
	self.painter = Painter(self.canvas, levelMap)
Ejemplo n.º 14
0
    def initLevelCanvas(self):
	
	# create the canvas
	name = self.levelFilename + str(self.currLevel)
	self.tilemap = TileMap(name)
	
	f = open(name, 'r')
	levelMap = []
	while True:
	    line = f.readline()
	    if line == '':
		break
	    levelMap.append(line)
	f.close()
	
	self.painter = Painter(self.canvas, levelMap)
Ejemplo n.º 15
0
 def test_turnPlus533FromNorth(self):
     #12*44+5 = 533
     painter = Painter()
     painter.turnSome(533)
     curDir = painter.currentDirectionAsOnClock
     self.assertEqual(5, curDir)
Ejemplo n.º 16
0
 def test_StartPositionPaintWhiteBlackWhite(self):
     painter = Painter()
     initialColor = painter.getValueAtCurrentPosition()
     self.assertEqual(0, initialColor, 'intial color is black')
     painter.paintCurrentWhite()
     whiteCoat = painter.getValueAtCurrentPosition()
     self.assertEqual(1, whiteCoat, 'white coat')
     painter.paintCurrentBlack()
     blackCoat = painter.getValueAtCurrentPosition()
     self.assertEqual(0, blackCoat, 'black coat')
     painter.paintCurrentWhite()
     whiteFinish = painter.getValueAtCurrentPosition()
     self.assertEqual(1, whiteFinish, 'white finish')
Ejemplo n.º 17
0
 def test_turnRightFromNorth(self):
     painter = Painter()
     painter.turnRight()
     curDir = painter.currentDirectionAsOnClock
     self.assertEqual(3, curDir)
Ejemplo n.º 18
0
    def draw(self):
        p = Painter(self.manager.drawing_surface())
        p.clear(Colors.black)

        for obj in self.objects:
            obj.draw()
Ejemplo n.º 19
0
 def test_StartPositionReadColor(self):
     painter = Painter()
     retrievedValue = painter.getValueAtCurrentPosition()
     self.assertEqual(0, retrievedValue)
Ejemplo n.º 20
0
class EditorModel:
    """
    Класс модель редактора
    """
    def __init__(self):
        self.painter = Painter()
        self.store = Store()
        self.selection_store = SelectionStore()
        self.object_factory = ObjectFactory(self.store)
        self.scene = Scene(self.store, self.painter, self.selection_store)
        self.object_state = False
        self.move_state = False
        self.curr_object = None
        self.last_object = False

    def try_select(self, x, y):
        """
        Попытка выделения объекта при нажатии на граф сцену
        :param x: координата х при нажатии мышки
        :param y: координата y при нажатии мышки
        """
        self.object_state = False
        for object in self.store.list:
            if object.in_body(x, y):
                self.selection_store.list.append(object.create_selection())
                object.select = True
                self.scene.repaint()
                return True
        return False

    def try_grab(self, x, y):
        """
        Попытка потащить за маркер выделенной фигуры
        :param x: координата х при нажатии мышки
        :param y: координата y при нажатии мышки
        """
        return self.selection_store.try_grab(x, y)

    def try_drag_to(self, x, y):
        """
        Перерисовка при перетаскивании маркера
        :param x: координата х при нажатии мышки
        :param y: координата y при нажатии мышки
        """
        self.selection_store.try_drag_to(x, y)
        if self.selection_store.drag_state:
            self.scene.repaint()

    def clear_selection(self):
        """
        Очистка селекторов объектов
        """

        self.selection_store.list = []
        self.curr_object = None
        for object in self.store.list:
            object.select = False
        self.scene.repaint()

    def set_port(self, x1, y1, x2, y2, painter):
        """
        Установка средства рисования
        :param painter: средство рисования
        """
        self.painter.set_port(x1, y1, x2, y2, painter)

    def create_object(self, x, y):
        """
        Создание объекта фигуры (метод делегат)
        :param x: координата х при нажатии мышки
        :param y: координата y при нажатии мышки
        :return:
        """
        self.object_factory.create_object(x, y)
        self.selection_store.list.append(self.store.list[len(self.store.list) -
                                                         1].create_selection())
        self.scene.repaint()

    def set_pen_props(self, pen_color, pen_width):
        """
        установка свойств ручки (метод делегат)
        :param pen_color: цвет ручки
        :param pen_width: толщина ручки
        """
        self.object_factory.set_pen_props(pen_color, pen_width)

    def set_brush_prop(self, brush_prop):
        """
        установка свойства заливки (метод делегат)
        :param brush_prop: заливка фигуры
        :return:
        """
        self.object_factory.set_brush_prop(brush_prop)

    def set_object_type(self, object):
        """
        Установка типа объекта (метод делегат)
        :param object: тип объекта
        """
        self.object_factory.set_object_type(object)

    def clear(self):
        """
        Очистка хранилища редактора
        :return:
        """
        self.store.clear()
        self.selection_store.list = []
        self.scene.repaint()

    def clear_obj(self):
        def delete_multiple_element(list_object, indices):
            indices = sorted(indices, reverse=True)
            for idx in indices:
                if idx < len(list_object):
                    list_object.pop(idx)

        index = []
        for i in range(len(self.store.list)):
            if self.store.list[i].select == True:
                index.append(i)
        delete_multiple_element(self.store.list, index)
        self.selection_store.list = []
        self.scene.repaint()

    def repaint(self):
        """
        Метод перерисовки сцены
        """
        self.scene.repaint()

    def group(self):
        """
        Метод группировки фигур
        """
        list_object = []
        for object in self.store.list:
            if object.select:
                object.gr_state = True
                list_object.append(object)

        group = Group(list_object)
        self.store.list.append(group)

        list = []
        self.selection_store.clear_selection()
        for object in self.store.list:
            if object not in list_object:
                list.append(object)

        self.store.list.clear()
        self.store.list = list
        self.selection_store.list.append(group.create_selection())

        self.scene.repaint()

    def ungroup(self):
        """
        Метод разгруппировки фигур
        """
        obj = None
        for object in self.store.list:
            if isinstance(object, Group) and object.select:
                obj = object
        if obj != None:
            self.selection_store.clear_selection()
            self.repaint()
            for object in obj.gr_list:
                self.store.list.append(object)
            self.store.list.remove(obj)
Ejemplo n.º 21
0
if __name__ == "__main__":

    K.clear_session()

    input_shape = (1024,1024, 3)
    output_shape = (256, 256, 3)

    Dis = Discriminator(input_shape=output_shape)
    Dis.input()
    Dis.conv_pool_block(n_filter=16, filter_size=(5,5))
    Dis.conv_pool_block(n_filter=8, filter_size=(7,7))
    Dis.fully_connected(4)
    Dis.fully_connected(1) # for W-Loss
    Dis.build()

    Gen = Painter(Dis, input_shape, output_shape)
    Gen.input()
    Gen.conv_block(16, filter_size=(5,5), padding="same")
    Gen.conv_block(16, filter_size=(7,7), padding="same")
    Gen.pooling_block((2,2))
    Gen.conv_block(32, filter_size=(9,9), padding="same")
    Gen.conv_block(32, filter_size=(11,11), padding="same")
    Gen.pooling_block((2,2))
    Gen.top_block()
    #Gen.build_monitored([2,5],[0.5,0.5])
    Gen.build()



    painter_optimizer = Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-07)
    disc_optimizer = Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-07)
Ejemplo n.º 22
0
fon = pygame.sprite.Group()
background = pygame.sprite.Sprite()
background.image = load_image("background.jpg")
background.rect = background.image.get_rect()
background.rect.x = 0
background.rect.y = 0
fon.add(background)

x = (gameParams.getWidth() * 0.45)
y = (gameParams.getHeight() * 0.8)
player = SpaceShip(x, y, pygame, gameDisplay, gameParams)
running = True
firstStage = FirstStage(pygame, gameDisplay, gameParams)
contentManager = ContentManager()
contentManager.setContents(firstStage.loadStageContent())
painter = Painter(time.time(), contentManager.getContent())
start_screen()


def getShootContent(player):
    strike = EnergyStrike(pygame, gameDisplay, gameParams)
    shootContent = Content(
        strike,
        firstStage.getShootConduct((player.get_x() + 20, player.get_y() - 5)),
        1)
    return [shootContent]


while running:
    for event in pygame.event.get():
        gameDisplay.fill(colour_white)
Ejemplo n.º 23
0
from initGame import *
from Painter import Painter

# 定义地图
painter = Painter(global_map, global_mapIndex, global_STEP, global_gateCount)
painter.setDataByMap()
painter.paintMap()

# 启动游戏
painter.startPlay()
Ejemplo n.º 24
0
	def __init__(self, phase, parameters):
		
		self.phase = phase	
	  	self.parameters = parameters
		self.painter = Painter()
Ejemplo n.º 25
0
 def __init__(self, w, h, col, name):
     super().__init__()
     self.painter = Painter(w, h, col, name)
     self.painter.setGeometry(0, 0, 3200, 1600)
     self.painter.show()
Ejemplo n.º 26
0
from Engine import Engine
from Screen import Screen
from Painter import Painter
from DJ import DJ

screen = Screen()
dj = DJ()
painter = Painter(dj)
e = Engine(screen, painter, dj)
e.run()
Ejemplo n.º 27
0
Archivo: GA.py Proyecto: XZZMemory/GA
 def ga(self, population, gaFilePath):
     population.creatPopulation()  # 生成种群
     points = []
     painter = Painter()
     painter.paintNetworkTopology(population.baseRadius,
                                  population.locationOfBase,
                                  population.locationOfUser,
                                  population.basevisitedUE, gaFilePath)
     '''存储结果,用于绘图,文件操作'''
     f = open(gaFilePath, 'w')
     iterations = 1  # 当前迭代次数
     while (iterations <= population.iterations):
         fitness = population.getAllFitnessIntegral()
         maxFitnessInCurrentPopulation = max(fitness)
         print("代数:" + str(iterations) + "  最好值:" +
               str(maxFitnessInCurrentPopulation))
         f.write("iterations: " + str(iterations) + " fitness: " +
                 str(maxFitnessInCurrentPopulation) + '\n')
         if iterations == 1:
             maxFitness = maxFitnessInCurrentPopulation
         else:
             maxFitness = maxFitness if maxFitness > maxFitnessInCurrentPopulation else maxFitnessInCurrentPopulation
         points.append([iterations, maxFitnessInCurrentPopulation])
         tempIndividulalList = []
         while (len(tempIndividulalList) < population.sizeOfPopulation):
             individualForCrossover = population.select()  # 选择--锦标赛选择法
             if len(individualForCrossover) != 2:
                 print("select error! " + str(len(individualForCrossover)))
                 exit(1)
             individualForMutate = population.crossover(
                 individualForCrossover)  # 交叉随机点位的交叉操作,交叉完毕之后判断是否满足约束
             if (len(individualForMutate) == 2):
                 population.mutate(individualForCrossover)
                 for i in range(len(individualForCrossover)):
                     tempIndividulalList.append(individualForCrossover[i])
         tempFitness = []
         for i in range(len(tempIndividulalList)):
             fit = tempIndividulalList[i].getFitnessOfMatching()
             tempFitness.append(fit)
         for i in range(population.sizeOfPopulation):
             if tempIndividulalList == None:
                 print(str(i) + "个体是空!")
                 exit(1)
             if (tempFitness[i] > fitness[i]):
                 population.individualList[i] = copy.deepcopy(
                     tempIndividulalList[i])
         iterations += 1
     fitness = population.getAllFitnessIntegral()
     index = Utils.getImportant(fitness)
     print(
         "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%9090909090"
     )
     print(population.individualList[index].getFitnessOfMatching())
     print("asm_array: " + str(population.individualList[index].asm_array))
     print("ansArray: " + str(population.individualList[index].ansArray))
     print("VN: " + str(population.VN))
     print("C: " + str(population.individualList[index].C))
     print("P: " + str(population.individualList[index].P))
     f.write("end" + '\n' + "C: " +
             str(population.individualList[index].C) + '\n' + "P: " +
             str(population.individualList[index].P))
     return [
         population.individualList[index].C,
         population.individualList[index].P, fitness[index],
         population.individualList[index].ansArray
     ]
Ejemplo n.º 28
0
class Environment(Frame):

    def __init__(self, root, mw, username):
        Frame.__init__(self, root, background="MediumTurquoise")
        self.parent = root
        self.mw = mw
        self.username = username

        self.levelFilename = "../support/levels/level"
        self.stencilFilename = "../support/stencil/level"
        self.helpFilename = "../support/help/level"
        self.canRun = False
        self.endStatus = False

        # change font size depending on screen dimension
        screen_width = self.parent.winfo_screenwidth()
        screen_height = self.parent.winfo_screenheight()

        # projector setting
        if screen_width == 1280:
	    self.customFont1 = tkFont.Font(family="Pupcat", size=18, weight=tkFont.BOLD)
	    self.customFont2 = tkFont.Font(family="LMMono10", size=17)
	    self.boldFont = tkFont.Font(family="LMMono10", size=17, weight=tkFont.BOLD)
	    self.italFont = tkFont.Font(family="LMMono10", size=17, slant=tkFont.ITALIC)

	# single screen setting
	elif screen_width == 1920:
	    self.customFont1 = tkFont.Font(family="Pupcat", size=14, weight=tkFont.BOLD)
	    self.customFont2 = tkFont.Font(family="LMMono10", size=14)
	    self.boldFont = tkFont.Font(family="LMMono10", size=14, weight=tkFont.BOLD)
	    self.italFont = tkFont.Font(family="LMMono10", size=14, slant=tkFont.ITALIC)

	# double screen setting
	else:
	    self.customFont1 = tkFont.Font(family="Pupcat", size=14, weight=tkFont.BOLD)
            self.customFont2 = tkFont.Font(family="LMMono10", size=15)
            self.boldFont = tkFont.Font(family="LMMono10", size=14, weight=tkFont.BOLD)
	    self.italFont = tkFont.Font(family="LMMono10", size=14, slant=tkFont.ITALIC)


        self.initToolbar()
        self.initCanvas()
        self.initTextBoxes()
        self.initUI()

        self.currLevel = 1

        self.beatenLevels = []
        self.initLevelCanvas()
        self.initLevelText()
        maze.create_maze()


    def initUI(self):
        self.parent.title("GLIDE")
        self.pack(fill=BOTH, expand=1)
        x = (self.parent.winfo_screenwidth() - DIM_X)/2
        y = (self.parent.winfo_screenheight() - DIM_Y)/2
        self.parent.geometry('%dx%d+%d+%d' % (DIM_X, DIM_Y, x, y))


    def initLevelCanvas(self):
	
	# create the canvas
	name = self.levelFilename + str(self.currLevel)
	self.tilemap = TileMap(name)
	
	f = open(name, 'r')
	levelMap = []
	while True:
	    line = f.readline()
	    if line == '':
		break
	    levelMap.append(line)
	f.close()
	
	self.painter = Painter(self.canvas, levelMap)

    # Redraw the canvas, but do not create a new tilemap. Used so that the levels
    # with randomized maps can be redrawn without creating a new tilemap.
    def redrawLevelCanvas(self):
	
	name = self.levelFilename + str(self.currLevel)
	f = open(name, 'r')
	levelMap = []
	while True:
	    line = f.readline()
	    if line == '':
		break
	    levelMap.append(line)
	f.close()
	
	self.painter = Painter(self.canvas, levelMap)


    def initLevelText(self):
	# clear the text editor
	self.textEditor.delete(1.0, END)
	
	# put stencil code into the text editor
	name = self.stencilFilename + str(self.currLevel)
        f = open(name, 'r')
        lineNum = 0
	while True:
	    line = f.readline()
	    if line == "":
		break
	    else:
		self.textEditor.insert(END, line)
	f.close()
	
	# allow editing for the help box and clear it
	self.helpBox.config(state=NORMAL)
	self.helpBox.delete(1.0, END)   # clear text boxes
	
	# put help files into the help box - what we want to show on each screen
        # is in its own string inside the "screens"
        name = self.helpFilename + str(self.currLevel)
        f = open(name, 'r')
        self.screens = []
        self.screens.append("")
        numScreen = 0

	while True:
	    line = f.readline()
	    if line == "":
		break
	    elif line == "*****\n":
		self.screens.append("")
		numScreen += 1
	    else:
		self.screens[numScreen] += line
	f.close()
	
	# insert the first screen's text into the help box and set a variable saying so
	self.putHelpboxText(0)
	self.shownScreen = 0
	
	# disable editing again
        self.helpBox.config(state=DISABLED)


    def loadUserCode(self):
	# clear the text editor
	self.textEditor.delete(1.0, END)
	
	# put user's code into the text editor
	name = "code" + str(self.currLevel) + self.username
        f = open(name, 'r')
        lineNum = 0
	while True:
	    line = f.readline()
	    if line == "":
		break
	    else:
		self.textEditor.insert(END, line)
	f.close()


    def putHelpboxText(self, screenNum):
        self.helpBox.insert(END, self.screens[screenNum])
        self.shownScreen = screenNum
	
	# do tag parsing
	
	codeStart = self.helpBox.search("<code>", 1.0)
	while codeStart != '':
	    l = re.split('\.', codeStart)
	    line, col = int(l[0]), int(l[1])
	    self.helpBox.delete(codeStart, "%d.%d" % (line, col+6))  # remove the "<code>" tag from the line

	    codeEnd = self.helpBox.search("</code>", 1.0)
	    if codeEnd == '':
		print "Missing </code> tag in level ", self.currLevel, " help file."
	    l = re.split('\.', codeEnd)
	    line, col = int(l[0]), int(l[1])
	    self.helpBox.delete(codeEnd, "%d.%d" % (line, col+7))  # remove the "</code>" tag from the line

	    # apply tag
	    self.helpBox.tag_add("code", codeStart, codeEnd)

	    # check for other code tags
	    codeStart = self.helpBox.search("<code>", 1.0)

        boldStart = self.helpBox.search("<b>", 1.0)
	while boldStart != '':
	    l = re.split('\.', boldStart)
	    line, col = int(l[0]), int(l[1])
	    self.helpBox.delete(boldStart, "%d.%d" % (line, col+3))  # remove the "<b>" tag from the line

	    boldEnd = self.helpBox.search("</b>", 1.0)
	    if boldEnd == '':
		print "Missing </b> tag in level ", self.currLevel, " help file."
	    l = re.split('\.', boldEnd)
	    line, col = int(l[0]), int(l[1])
	    self.helpBox.delete(boldEnd, "%d.%d" % (line, col+4))  # remove the "</b>" tag from the line

	    # apply tag
	    self.helpBox.tag_add("bold", boldStart, boldEnd)

	    # check for other code tags
	    boldStart = self.helpBox.search("<b>", 1.0)

        italStart = self.helpBox.search("<i>", 1.0)
	while italStart != '':
	    l = re.split('\.', italStart)
	    line, col = int(l[0]), int(l[1])
	    self.helpBox.delete(italStart, "%d.%d" % (line, col+3))  # remove the "<i>" tag from the line

	    italEnd = self.helpBox.search("</i>", 1.0)
	    if italEnd == '':
		print "Missing </i> tag in level ", self.currLevel, " help file."
	    l = re.split('\.', italEnd)
	    line, col = int(l[0]), int(l[1])
	    self.helpBox.delete(italEnd, "%d.%d" % (line, col+4))  # remove the "</i>" tag from the line

	    # apply tag
	    self.helpBox.tag_add("ital", italStart, italEnd)

	    # check for other code tags
	    italStart = self.helpBox.search("<i>", 1.0)

        underStart = self.helpBox.search("<u>", 1.0)
	while underStart != '':
	    l = re.split('\.', underStart)
	    line, col = int(l[0]), int(l[1])
	    self.helpBox.delete(underStart, "%d.%d" % (line, col+3))  # remove the "<u>" tag from the line

	    underEnd = self.helpBox.search("</u>", 1.0)
	    if underEnd == '':
		print "Missing </u> tag in level ", self.currLevel, " help file."
	    l = re.split('\.', underEnd)
	    line, col = int(l[0]), int(l[1])
	    self.helpBox.delete(underEnd, "%d.%d" % (line, col+4))  # remove the "</u>" tag from the line

	    # apply tag
	    self.helpBox.tag_add("underline", underStart, underEnd)

	    # check for other code tags
	    underStart = self.helpBox.search("<u>", 1.0)

    def initToolbar(self):
        toolbar = Frame(self.parent, relief=FLAT, background="MediumTurquoise")

        img = Image.open("Graphics/Icons/saveIcon.png")
        saveImg1 = ImageTk.PhotoImage(img)  
        self.saveLevelButton = Button(toolbar, image=saveImg1, relief=FLAT, background="Turquoise",
                                      activebackground="yellow", width=BUTTON_X, height=BUTTON_Y, command=self.save)
        self.saveLevelButton.image = saveImg1
        self.saveLevelButton.grid(row=0, column=0)

        img = Image.open("Graphics/Icons/loadIcon.png")
        loadImg = ImageTk.PhotoImage(img)  
        self.loadButton = Button(toolbar, image=loadImg, relief=FLAT, background="Turquoise",
                                 activebackground="yellow", width=BUTTON_X, height=BUTTON_Y, command=self.load)
        self.loadButton.image = loadImg
        self.loadButton.grid(row=0, column=1)

        img = Image.open("Graphics/Icons/checkIcon.png")
        checkImg = ImageTk.PhotoImage(img)  
        self.checkButton = Button(toolbar, image=checkImg, relief=FLAT, background="Turquoise",
                                  activebackground="yellow", width=BUTTON_X, height=BUTTON_Y, command=self.checkCode)
        self.checkButton.image = checkImg
        self.checkButton.grid(row=0, column=2)

        img = Image.open("Graphics/Icons/runIcon.png")
        runImg = ImageTk.PhotoImage(img)  
        self.runButton = Button(toolbar, image=runImg, relief=FLAT, background="Turquoise", state=DISABLED,
                                activebackground="yellow", width=BUTTON_X, height=BUTTON_Y, command=self.run)
        self.runButton.image = runImg
        self.runButton.grid(row=0, column=3)

        img = Image.open("Graphics/Icons/prevLevelIcon.png")
        prevLevelImg = ImageTk.PhotoImage(img)  
        self.prevLevelButton = Button(toolbar, image=prevLevelImg, relief=FLAT, background="Turquoise", state=DISABLED,
                                 activebackground="yellow", width=BUTTON_X, height=BUTTON_Y, command=self.prevLevel)
        self.prevLevelButton.image = prevLevelImg
        self.prevLevelButton.grid(row=0, column=4)

        img = Image.open("Graphics/Icons/nextLevelIcon.png")
        nextLevelImg = ImageTk.PhotoImage(img)  
        self.nextLevelButton = Button(toolbar, image=nextLevelImg, relief=FLAT, background="Turquoise", state=DISABLED,
                                 activebackground="yellow", width=BUTTON_X, height=BUTTON_Y, command=self.nextLevel)
        self.nextLevelButton.image = nextLevelImg
        self.nextLevelButton.grid(row=0, column=5)

        img = Image.open("Graphics/Icons/quitIcon.png")
        quitImg = ImageTk.PhotoImage(img)  
        quitButton = Button(toolbar, image=quitImg, relief=FLAT, background="Turquoise",
                            activebackground="yellow", width=BUTTON_X, height=BUTTON_Y, command=self.exit)
        quitButton.image = quitImg
        quitButton.grid(row=0, column=7, sticky=E)

        toolbar.pack(side=TOP, fill=X)


    def disableButtons(self):
	currStates = [self.saveLevelButton.config().get('state')[4],
	              self.loadButton.config().get('state')[4],
	              self.checkButton.config().get('state')[4],
	              self.runButton.config().get('state')[4],
	              self.prevLevelButton.config().get('state')[4],
	              self.nextLevelButton.config().get('state')[4]]
	
	# set all to disabled
	self.saveLevelButton.config(state=DISABLED)
	self.loadButton.config(state=DISABLED)
	self.checkButton.config(state=DISABLED)
	self.runButton.config(state=DISABLED)
	self.prevLevelButton.config(state=DISABLED)
	self.nextLevelButton.config(state=DISABLED)
	
	return currStates
	
    def returnButtonsToStates(self, states):
	self.saveLevelButton.config(state=states[0])
	self.loadButton.config(state=states[1])
	self.checkButton.config(state=states[2])
	self.runButton.config(state=states[3])
	self.prevLevelButton.config(state=states[4])
	self.nextLevelButton.config(state=states[5])
	

    def initCanvas(self):
        self.canvas = Canvas(self.parent, width=DIM_X, height=CANVAS_HEIGHT, background="white", relief=FLAT)
        self.canvas.pack()


    def initTextBoxes(self):
        panedWindow = PanedWindow(self.parent, width=DIM_X, height=(DIM_Y - TOOLBAR_Y)/2+5, relief=FLAT)


	# left-hand side: text box for the user to type into, plus a scrollbar
        leftPanel = Frame(panedWindow)
        scrollbar = Scrollbar(leftPanel, orient=VERTICAL)
        self.textEditor = Text(leftPanel, background="PaleTurquoise", width=MAX_CHARS, font=self.customFont2,
                               wrap=WORD, height=(DIM_Y - TOOLBAR_Y)/2, yscrollcommand=scrollbar.set,
                               selectbackground="Turquoise")
        self.textEditor.bind("<<Modified>>", self.textEditorModified)
        self.resettingModifiedFlag = False
	
	# add a scrollbar to the left-hand box
	scrollbar.config(command=self.textEditor.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.textEditor.pack(side=LEFT, fill=BOTH, expand=1)
        panedWindow.add(leftPanel)

	# right hand side: help box, plus buttons to see different help screens
	
	rightPanel = Frame(panedWindow)
	scrollbar1 = Scrollbar(rightPanel, orient=VERTICAL)
	boxPanel = Frame(rightPanel, width=DIM_Y/2, height=DIM_X - 2*TOOLBAR_Y)
        self.helpBox = Text(boxPanel, background="LemonChiffon", font=self.customFont2, selectbackground="Gold",
                            wrap=WORD, height=15, yscrollcommand=scrollbar1.set)
        
        # add a scrollbar to the right-hand box
	scrollbar1.config(command=self.helpBox.yview)
        scrollbar1.pack(side=RIGHT, fill=Y)
        self.helpBox.pack(expand=1)
        boxPanel.pack()

        # add buttons to help box
	helpboxWidth = self.helpBox.winfo_reqwidth()
        buttonBar = Frame(rightPanel, relief=FLAT, background="LemonChiffon", height=BUTTON_Y, width=helpboxWidth)

        img = Image.open("Graphics/backArrow.png")
        self.backImg = ImageTk.PhotoImage(img)
        prevButton =     Button(buttonBar, relief=RAISED, background="LemonChiffon", image=self.backImg, borderwidth=1,
                                activebackground="Turquoise", height=BUTTON_Y, command=self.prevScreen)
        prevButton.image = self.backImg
        
        img = Image.open("Graphics/yourCode.png")
        self.codeImg = ImageTk.PhotoImage(img)
        yourCodeButton = Button(buttonBar, relief=RAISED, background="LemonChiffon", image=self.codeImg, borderwidth=1,
                                activebackground="Turquoise", height=BUTTON_Y, command=self.lastScreen)
        yourCodeButton.image = self.codeImg

        img = Image.open("Graphics/nextArrow.png")
        self.nextImg = ImageTk.PhotoImage(img)
        nextButton =     Button(buttonBar, relief=RAISED, background="LemonChiffon", image=self.nextImg, borderwidth=1,
                                activebackground="Turquoise", height=BUTTON_Y, command=self.nextScreen)
        nextButton.image = self.nextImg

	prevButton.pack(side=LEFT)
	nextButton.pack(side=RIGHT)
	yourCodeButton.pack(padx=103)

	buttonBar.pack(fill=X)
	
	# set up tags to highlight errors in the text editor and do syntax highlighting
	self.textEditor.tag_config("error", background="OrangeRed", foreground="White")
	
	self.helpBox.tag_config("bold", font=self.boldFont)
	self.helpBox.tag_config("ital", font=self.italFont)
	self.helpBox.tag_config("underline", underline=1)
	self.helpBox.tag_config("code", font=self.boldFont, foreground="DarkViolet")
	
        panedWindow.add(rightPanel)
        panedWindow.pack(fill=BOTH, expand=1)


    # deals with making the "run code" button appear grayed-out when the user modifies the
    # input box, so that you have to re-compile before running
    def clearModifiedFlag(self):
	self.resettingModifiedFlag = True
	self.textEditor.edit_modified(False)
	self.resettingModifiedFlag = False


    # same as above comment
    def textEditorModified(self, selfCall=False, event=None):
	if self.resettingModifiedFlag == True:
	    return
	self.canRun = False
	self.runButton.config(state=DISABLED)
	self.clearModifiedFlag()


    # Show the previous screen in the help box
    def prevScreen(self):
	if self.shownScreen == 0:
	    pass
	else:
	    self.helpBox.config(state=NORMAL)   # first, turn on editing
	    #self.shownScreen -= 1
	    self.helpBox.delete(1.0, END)   # clear the text box first
	    #self.helpBox.insert(END, self.screens[self.shownScreen])   # add the prev screen's text
	    self.putHelpboxText(self.shownScreen-1)
	    self.helpBox.config(state=DISABLED)  # turn off editing again


    # Show the last ("Your Code") screen in the help box
    def lastScreen(self):
	if self.shownScreen == (len(self.screens)-1):
	    pass
	else:
	    self.helpBox.config(state=NORMAL)   # turn on editing
	    #self.shownScreen = len(self.screens)-1
	    self.helpBox.delete(1.0, END)   # clear text box
	    #self.helpBox.insert(END, self.screens[self.shownScreen])
	    self.putHelpboxText(len(self.screens)-1)
            self.helpBox.config(state=DISABLED)   # turn off editing


    # Show the next screen in the help box
    def nextScreen(self):
	if self.shownScreen == (len(self.screens)-1):
	    pass
	else:
	    self.helpBox.config(state=NORMAL)   # first, turn on editing
	    #self.shownScreen += 1
	    self.helpBox.delete(1.0, END)   # clear text box
	    #self.helpBox.insert(END, self.screens[self.shownScreen])
	    self.putHelpboxText(self.shownScreen+1)
            self.helpBox.config(state=DISABLED)   # turn off editing


    # Return to the main window
    def exit(self):
	self.cleanUp()
	self.painter = None
	
	for widget in self.parent.pack_slaves():
	    widget.pack_forget()
	
        from MainWindow import MainWindow
	mw = MainWindow(self.parent)
	mw.pack()
	
        self.destroy()


    def save(self):
        pass

    def load(self):
        # clear the text editor
	self.textEditor.delete(1.0, END)
	
	# put user's code into the text editor
	name = "../support/levels/sol" + str(self.currLevel)
        f = open(name, 'r')
        lineNum = 0
	while True:
	    line = f.readline()
	    if line == "":
		break
	    else:
		self.textEditor.insert(END, line)
	f.close()

    # Save the user's code in the text editor into a file and tell the tilemap to check the code.
    def checkCode(self):
	filename = "code" + str(self.currLevel) + self.username
        f = open(filename, 'w')
        text = self.textEditor.get(1.0, END)
        f.write(text)
        f.close()

        # disable buttons & show "checking" dialog while we run the level dummy
        currStates = self.disableButtons()
        self.painter.showCheckingText()
        self.update()

        # run the level dummy to see if the code compiles
        noError = self.tilemap.runLevelDummy(self.username)

        # return buttons to their states once the method has returned & hide "checking" dialog
        self.returnButtonsToStates(currStates)
        self.painter.hideCheckingText()

        if not noError:
	    self.handleError()

        else:
	    # redraw the level - if we're in one of the randomized levels, the map/maze will change with
	    # each compilation
	    self.redrawLevelCanvas()
	    # reset plane
	    
	    # make sure no lines are highlighted as error lines
	    self.textEditor.tag_remove("error", 1.0, END)
	    
	    self.screens[-1] = "Yay! No compile or runtime errors!"
	    self.runButton.config(state=NORMAL)
	    self.canRun = True

	# show the new text in the "your code" part of the help box
	self.helpBox.config(state=NORMAL)   # turn on editing
	self.shownScreen = len(self.screens)-1
	self.helpBox.delete(1.0, END)   # clear text box
	self.helpBox.insert(END, self.screens[self.shownScreen])
	self.helpBox.config(state=DISABLED)   # turn off editing


    def handleError(self):
	# the error line to highlight in the code
	errorLine = 0

	# read in the error file
	errText = ""
	f = open("output.py", 'r')
	while True:
	    line = f.readline()
	    if line == "":
		break
	    elif line.startswith("code"):
	        errText += line
	        continue

            m = re.search("line (\d+)", line)
	    if m != None:
		val = m.group(1)
		errorLine = int(val) - 5
		line = re.sub(val, str(errorLine), line)

		# highlight line in textEditor
		self.textEditor.tag_add("error", "%d.%d" % (errorLine, 0), "%d.%s" % (errorLine, END))
		errText += line
	    else:
		errText += line
	f.close()

	# set the error text in the self.screens variable
	self.screens[-1] = errText
	self.runButton.config(state=DISABLED)


    def setEndStatus(self, b):
	self.endStatus = b


    # Get the list of commands to execute from the tilemap and tell the painter to do them. This
    # allows us to look ahead for turns so we can animate them nicely.
    def run(self):
	
	if self.canRun:
	    
	    # disable buttons while we run the level dummy
            currStates = self.disableButtons()

	    # reset plane
	    self.painter.initPlane()
	    
	    # get name list if in binary search level (None if not this level)
	    nameList = self.tilemap.getNameList()

	    cmdList = self.tilemap.getLevel()
	    
	    if self.currLevel == 6:
		self.painter.setSpeeds(.004, .0015)
            elif self.currLevel == 3:
		self.painter.setSpeeds(.010, .005)
	    else:
		self.painter.setSpeeds(.015, .008)

	    cmdList = re.sub('04350', 'i', cmdList) # i = s-bend east south
	    cmdList = re.sub('05140', 'j', cmdList) # j = s-bend east north
	    cmdList = re.sub('14051', 'k', cmdList) # k = s-bend north east
	    cmdList = re.sub('15241', 'l', cmdList) # l = s-bend north west
	    cmdList = re.sub('24152', 'm', cmdList) # m = s-bend west north
	    cmdList = re.sub('25342', 'n', cmdList) # n = s-bend west south
	    cmdList = re.sub('34253', 'o', cmdList) # o = s-bend south west
	    cmdList = re.sub('35043', 'p', cmdList) # p = s-bend south east

	    cmdList = re.sub('043', 'a', cmdList)   # a = right turn south
	    cmdList = re.sub('051', 'b', cmdList)   # b = left turn north
	    cmdList = re.sub('342', 'c', cmdList)   # c = right turn west
	    cmdList = re.sub('350', 'd', cmdList)   # d = left turn east
	    cmdList = re.sub('253', 'e', cmdList)   # e = left turn south
	    cmdList = re.sub('241', 'f', cmdList)   # f = right turn north
	    cmdList = re.sub('152', 'g', cmdList)   # g = left turn west
	    cmdList = re.sub('140', 'h', cmdList)   # h = right turn east

	    desks = re.findall('8(\d+?)8', cmdList)
	    cmdList = re.sub('8\d+?8', '8x', cmdList)  # x = desk
	    nextDesk = -1

	    for i in range(len(cmdList)):
		if self.endStatus:
		    self.painter.destroy()
		    self.destroy()
		    return

		cmd = cmdList[i]
		if cmd == '0':
		    self.painter.movePlaneEast()
		elif cmd == '1':
		    self.painter.movePlaneNorth()
		elif cmd == '2':
		    self.painter.movePlaneWest()
		elif cmd == '3':
		    self.painter.movePlaneSouth()
		elif cmd == '4':
		    self.painter.rotatePlaneClockwise(90)
		elif cmd == '5':
		    self.painter.rotatePlaneCounterclockwise(90)
		elif cmd == '6':     # crash
		    self.painter.crash()
		    if self.currLevel == 5:
		        self.screens[-1] = "You asked too many students and your teacher woke up! Yikes!\nTry to find Sally in fewer guesses."
		    else:
			self.screens[-1] = "Oh no - your plane crashed!"
		    self.helpBox.config(state=NORMAL)   # turn on editing
	            self.shownScreen = len(self.screens)-1
	            self.helpBox.delete(1.0, END)   # clear text box
	            self.helpBox.insert(END, self.screens[self.shownScreen])
	            self.helpBox.config(state=DISABLED)   # turn off editing
	            self.returnButtonsToStates(currStates)
	            self.update()
	            time.sleep(.8)
	            self.painter.initPlane()
	            self.painter.clearNames()
	            return
		elif cmd == '7':
		    pass
		elif cmd == '8':
		    nextDesk += 1
		elif cmd == 'x':
		    currDesk = int(desks[nextDesk])
		    self.painter.askName(nameList[currDesk], currDesk+1)
		elif cmd == 'y':
		    self.painter.dropWaterBalloon()
		elif cmd == 'z':
		    self.painter.dropWaterBalloon(True)
		elif cmd == 'a':
		    self.painter.takeRightTurnSouth()
		elif cmd == 'b':
		    self.painter.takeLeftTurnNorth()
		elif cmd == 'c':
		    self.painter.takeRightTurnWest()
		elif cmd == 'd':
		    self.painter.takeLeftTurnEast()
		elif cmd == 'e':
		    self.painter.takeLeftTurnSouth()
		elif cmd == 'f':
		    self.painter.takeRightTurnNorth()
		elif cmd == 'g':
		    self.painter.takeLeftTurnWest()
		elif cmd == 'h':
		    self.painter.takeRightTurnEast()
		elif cmd == 'i':
		    self.painter.sBendEastSouth()
		elif cmd == 'j':
		    self.painter.sBendEastNorth()
		elif cmd == 'k':
		    self.painter.sBendNorthEast()
		elif cmd == 'l':
		    self.painter.sBendNorthWest()
		elif cmd == 'm':
		    self.painter.sBendWestNorth()
		elif cmd == 'n':
		    self.painter.sBendWestSouth()
		elif cmd == 'o':
		    self.painter.sBendSouthWest()
		elif cmd == 'p':
		    self.painter.sBendSouthEast()
		else:
		    print ("Unknown movement command %i; not executing." % cmd)


	    # check for a win, or an "inefficient" win - reached goal but had extra cmds at end
	    match = re.search('7', cmdList)
	    if match != None and match.start() == len(cmdList)-1:    # actual win
		if self.currLevel == 6:
		    self.screens[-1] = "CONGRATULATIONS! You've reached the end of GLIDE 1.0! Stay tuned " \
		                       "for more levels in future versions of GLIDE."
		else:
		    self.screens[-1] = "Congrats! You beat the level!\n\nYou can hit the Next Level button to " \
				        "move on, or try out other cool stuff with your plane here."
		self.beatenLevels.append(self.currLevel)
		
		# if not at last level, make the next level button un-grayed
		if self.currLevel < 6:
		     currStates[5] = "normal"
		self.painter.animateWin()
		# show the new text in the "your code" part of the help box
		self.helpBox.config(state=NORMAL)   # turn on editing
		self.shownScreen = len(self.screens)-1
		self.helpBox.delete(1.0, END)   # clear text box
		self.helpBox.insert(END, self.screens[self.shownScreen])
		self.helpBox.config(state=DISABLED)   # turn off editing
		self.returnButtonsToStates(currStates)
		self.update()
		time.sleep(.7)
		self.painter.clearNames()
		return

            # inefficient win
	    elif match != None:
		if self.currLevel == 5:
		    self.screens[-1] = "You found Sally but kept asking students, and your teacher noticed. Uh oh! " \
		                       "Try making your plane find Sally by asking as few students as possible."
		else:
		    self.screens[-1] = "You passed the goal - looks your code contained some extra stuff. " \
				       "Try making your plane reach the goal in as few moves as possible."

            # didn't hit goal at all
            else:
		if self.currLevel == 5:
		    self.screens[-1] = "Looks like Sally's still sleeping. Try again to wake her up."
		else:
		    self.screens[-1] = "Oops! Your plane didn't make it to the goal."

	    # show the new text in the "your code" part of the help box
	    self.helpBox.config(state=NORMAL)   # turn on editing
	    self.shownScreen = len(self.screens)-1
	    self.helpBox.delete(1.0, END)   # clear text box
	    self.helpBox.insert(END, self.screens[self.shownScreen])
	    self.helpBox.config(state=DISABLED)   # turn off editing

	    # make the run button clickable again
	    self.returnButtonsToStates(currStates)

	    # reset the plane
	    self.update()
	    time.sleep(1.2)
	    self.painter.initPlane()

	    self.painter.clearNames()


    def prevLevel(self):
	self.painter.killAnimation()  # stop fireworks, if going
	self.currLevel -= 1
	self.initLevelCanvas()
	self.initLevelText()
	
	# when going to previous level, always reload user's saved code
	self.loadUserCode()
	
	# do the appropriate graying-out of buttons
	if self.currLevel == 1:
	    self.prevLevelButton.config(state=DISABLED)
	else:
	    self.prevLevelButton.config(state=NORMAL)
	self.nextLevelButton.config(state=NORMAL)
	self.runButton.config(state=DISABLED)


    def nextLevel(self):
	self.painter.killAnimation()   # stop fireworks, if going
	self.currLevel += 1
	self.initLevelCanvas()
	self.initLevelText()
	
	# if the next level (now currLevel) has already been beaten, then reload the user's 
	# saved code
	if self.currLevel in self.beatenLevels:
	    self.loadUserCode()
	
	# do the appropriate graying-out of buttons
	if self.currLevel in self.beatenLevels and self.currLevel < 6:
	    self.nextLevelButton.config(state=NORMAL)
	else:
	    self.nextLevelButton.config(state=DISABLED)
	self.prevLevelButton.config(state=NORMAL)
	self.runButton.config(state=DISABLED)


    def cleanUp(self):
	f = open("runLevel.py", "w")
	f.close()
Ejemplo n.º 29
0
 def test_turnMinus332FromNorth(self):
     #12*27+8 = 332
     painter = Painter()
     painter.turnSome(-332)
     curDir = painter.currentDirectionAsOnClock
     self.assertEqual(8, curDir)
Ejemplo n.º 30
0
from Painter import Painter
painter = Painter()
painter.paint9()
Ejemplo n.º 31
0
 def test_goforwardNorth(self):
     painter = Painter()
     painter.moveOneForward()
     self.assertEqual(0, painter.currentPositionObject.x)
     self.assertEqual(1, painter.currentPositionObject.y)
Ejemplo n.º 32
0
 def test_makeRightChessHorseJumpLMoveMapPrint(self):
     painter = Painter()
     painter.paintCurrentWhite()
     painter.moveOneForward()
     painter.paintCurrentWhite()
     painter.turnRight()
     painter.moveOneForward()
     painter.paintCurrentWhite()
     painter.moveOneForward()
     painter.paintCurrentWhite()
     with patch('builtins.print') as p:
         painter.map.printMap()
     p.assert_called_with([['#', '.', '.'], ['#', '#', '#']])
Ejemplo n.º 33
0
def ga(population, fileName, maxFitnessFile, typeOfVQD):
    population.initializationOfVQD(typeOfVQD)
    population.creatPopulation()  # 生成种群
    print(str(fileName) + " VQD: " + str(population.VQD))
    print("typeOfVQD: " + str(typeOfVQD))
    # 存储结果,用于绘图
    points = []
    maxFitness = -100
    minFitness = -100
    f = open(fileName, 'w')
    f.write(fileName + '\n')
    m = open(maxFitnessFile, 'w')
    m.write(maxFitnessFile + '\n')
    painter = Painter()
    painter.paintNetworkTopology(population.baseRadius,
                                 population.locationOfBase,
                                 population.locationOfUser,
                                 population.basevisitedUE, maxFitnessFile)
    '''存储结果,用于绘图,文件操作'''
    iterations = 1  # 当前迭代次数
    while (iterations <= population.iterations):
        fitness = population.getAllFitnessIntegral()
        maxFitness = max(maxFitness, max(fitness))
        minFitness = min(minFitness, min(fitness))
        print("代数:" + str(iterations) + "  最好值:" +
              str(maxFitness / population.VNTimes))
        m.write("iterations " + str(iterations) + ": " +
                str(maxFitness / population.VNTimes) + '\n')
        f.write("iterations " + str(iterations + 1) + '\n')
        f.write(str(fitness) + '\n')
        points.append([iterations, maxFitness])
        tempIndividulalList = []
        while (len(tempIndividulalList) < population.sizeOfPopulation):
            individualForCrossover = population.select()  # 选择--锦标赛选择法
            if len(individualForCrossover) != 2:
                print("select error! " + str(len(individualForCrossover)))
                exit(1)
            individualForMutate = population.crossover(
                individualForCrossover)  # 交叉随机点位的交叉操作,交叉完毕之后判断是否满足约束
            if (len(individualForMutate) == 2):
                population.mutate(individualForCrossover)
                for i in range(len(individualForCrossover)):
                    tempIndividulalList.append(individualForCrossover[i])
        tempFitness = []
        for i in range(len(tempIndividulalList)):
            fit = tempIndividulalList[i].getFitnessWithIntegral()
            tempFitness.append(fit)
        for i in range(population.sizeOfPopulation):
            if tempIndividulalList == None:
                print(str(i) + "个体是空!")
                exit(1)
            if (tempFitness[i] > fitness[i]):
                population.individualList[i] = copy.deepcopy(
                    tempIndividulalList[i])
        iterations += 1
    m.write(str(points) + '\n')
    f.close()
    m.close()
    # 返回画图所需的数据
    result = Result(fileName, minFitness, points, maxFitness)
    return result
Ejemplo n.º 34
0
import sys
from Painter import Painter

painter = Painter(sys.argv[1:-1], sys.argv[-1])
painter.print_figure()