コード例 #1
0
ファイル: Interact.py プロジェクト: abishgj/MontyHall
def game_run():
	global choice
	choice = { 0:" ",1:" ",2:" " }
	global seq
	os.system('clear')
	print "Welcome to The Monty Hall Show!!"
	print "There are three blocks named 'A', 'B' and 'C'\n"
	dum = raw_input("")
	print "There are three objects behind the blocks, but only one of the object is precious!!\n"
	dum = raw_input("")
	print "First you have to choose a block, then I ( Monty Hall) am going to show you one of the block where the non-precious object is present leaving you another chance of whether to switch or stick\n"
	dum = raw_input("")
	print "You have all freedom to either switch or stick to your first choice\n"
	dum = raw_input("")
	print "Shall we start the game then\n"
	dum = raw_input("")
	seq = init()
	key = read_in()
	dum = raw_input("Well.. You have made a choice.. Now you'll see a sheep block among the other two which you did not choose.. Again you will be given a chance of choice between the rest.. Lets see it")
	choice = MontyH.to_show(choice,seq,key)
	Draw.display(choice)
	x = raw_input("Do you want to switch your choice ?( Y for yes and any other key to continue with the same choice )")
	if ( x == 'Y' ):
		key = read_in()
		disclose(key)
	else:
		disclose(key)
コード例 #2
0
def first_fit():
    for each in Processes_Objects:
        allocator(Holes_Objects, each, 'f')
    fix_holes()
    if Graph:
        Draw.draw_graph(Holes_Objects, Processes_Objects, Block_List)
    show_progress(Holes_Objects)
コード例 #3
0
ファイル: Play.py プロジェクト: abishgj/TicTacToe
def init_game():
	global matrix
	u1c = 'X'; u2c = 'O'
	os.system('clear')
	print "Tic Tac Toe is a two player game. A borad will be shown to you. You need to choose a box where you want to put your sign. You can choose a box as 1,1 for the first box and 1,2 for the second box in first row.\n"
        print "Program will ask for input from the user specifically.\n"
        x = raw_input("Shall we start ??")
	os.system('clear')
	user1 = raw_input("Player 1: Enter your name:\t")
	x = raw_input("REMEMBER:\tYour sign is %c\n\n"%(u1c))
	os.system('clear')
	user2 = raw_input("Player 2: Enter your name:\t")
	x = raw_input("REMEMBER:\tYour sign is %c\n\n"%(u2c))
	os.system('clear')
	x = raw_input("Good Luck %s and %s..\n"%(user1,user2))
	os.system('clear')
	n = 3
	Draw.write_board(n)
	matrix = Draw.init_mat()
	if ( game_proc(user1,user2,n) == True ):
		choice = { 1:user1, 2:user2 } 
		print "Nice moves by both %s and %s, let's see the result\n"%(user1,user2)
		x = raw_input("Shall We ??\n")
		wval = Winner.find_winner(matrix)
		if ( wval in choice ):
			print "Player %s wins!!"%(choice.get(wval))
		else:
			print "It's a TIE!!"
コード例 #4
0
def deallocate(pid):
    """
    :param pid:   Integer -> PID of process to be de-allocated
    """
    global Processes_Objects

    to_be_deleted = None
    for each in Processes_Objects:
        # Found the process
        if pid is each.pid:
            # Get the hole the process is currently allocated to
            hole_pid = each.allocated_to.pid
            # Deallocate the process
            each.deallocate()
            to_be_deleted = each
            # Merge the hole
            if hole_pid + 1 <= Hole.Hole.count:
                merge(hole_pid, hole_pid + 1)

    if to_be_deleted is not None:
        Processes_Objects.remove(to_be_deleted)

    fix_holes()
    if Graph:
        Draw.draw_graph(Holes_Objects, Processes_Objects, Block_List)
    show_progress(Holes_Objects)
コード例 #5
0
ファイル: Core.py プロジェクト: quantum0813/Loltris
 def removeJob(self, removed_job_str):
     removed_job = getattr(self.jobs, removed_job_str)
     ## For now this is the solution, fill the entire screen. When the todo below is finished,
     ## I'll just fill  the job instead.
     Draw.fillJob(self.screen, self.bgcolor, removed_job)
     for job in self.getJobsIn(removed_job_str):
         job.force_draw = True
     delattr(self.jobs, removed_job_str)
コード例 #6
0
ファイル: Interact.py プロジェクト: abishgj/MontyHall
def disclose(key):
	global choice
	choice = MontyH.show_final(choice,seq)
	Draw.display(choice)
	if ( seq[key] == "GOLD" ):
		print "Woohoooo!! Congrats"
	else:
		print "Thank you for playing"
コード例 #7
0
def main():

    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()         # treniranje KNN-a

    if blnKNNTrainingSuccessful == False:                               # Ukoliko nije uspesno izvrseno treniranje vraca se poruka o tome
        print ("\nerror: KNN traning was not successful\n")
        return


    imgOriginalScene  = cv2.imread("6.png")               # otvaranje slike

    if imgOriginalScene is None:                            # ukoliko slika nije uspesno otvorena vraca se poruka o tome
        print("\nerror: image not read from file \n\n")
        os.system("pause")
        return


    possiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene)           # detektovanje samih tablica

    possiblePlates = DetectChars.detectCharsInPlates(possiblePlates)        # detektovanje karaktera na tablicama

    cv2.imshow("Original image", imgOriginalScene)

    if len(possiblePlates) == 0:
        print("\nno license plates were detected\n")
    else:
        possiblePlates.sort(key = lambda possiblePlate: len(possiblePlate.strChars), reverse = True)


        licPlate = possiblePlates[0]

        if len(licPlate.strChars) == 0:
            print("\nno characters were detected\n\n")
            return
        # end if

        Draw.drawRedRectangleAroundPlate(imgOriginalScene, licPlate)

        print("\nlicense plate read from image = " + licPlate.strChars + "\n")
        print("----------------------------------------")

        Draw.writeLicensePlateCharsOnImage(imgOriginalScene, licPlate)

        cv2.imshow("Result", imgOriginalScene)

        cv2.imwrite("result.png", imgOriginalScene)

    cv2.waitKey(0)

    return
コード例 #8
0
ファイル: LinSys.py プロジェクト: edwardsCam/Python-Scripts
    def do(self, action, step, rainbow):
        if len(action) > 1:
            p = action[1]
        else:
            p = 1.0

        self.timebuff += step
        cmd = action[0].lower()
        if cmd == "draw":
            if rainbow:
                self.incColor()
                if self.incThickYN:
                    self.incThick(self.reverseThick, False)
            elif self.incThickYN:
                self.incThick(self.reverseThick, True)
            if self.timebuff > 1.0:
                truncate = int(self.timebuff)
                self.after(truncate, self.draw(float(p), True))
                self.timebuff -= truncate
            else:
                self.draw(float(p))
        elif cmd == "turn":
            Draw.turn(float(p))
        elif cmd == "skip":
            Draw.skip(float(p))
        elif cmd == "back":
            Draw.back(float(p))
        elif cmd == "color":
            if not rainbow:
                self.color = Color.getHexString(p)
        elif cmd == "thick":
            self.thick = int(p)
        else:
            print("Unknown command " + cmd)
コード例 #9
0
ファイル: LinSys.py プロジェクト: edwardsCam/Python-Scripts
 def drawAll(self, newWindow= True):
     if self.generated == True:
         self.butt_print.config(state= 'disabled')
         self.timebuff = 0.0
         self.color = Color.white()
         self.thick = 2
         l = float(self.slid_linesize.get())
         a = float(self.slid_angle.get())
         Draw.init(self.startingPoint, l, a)
         if self.fullScreen.get() == 1:
             if newWindow:
                 self.curr_canvas = dc.BigCanvas(self).canvas
             self.canvas.delete("all")
         else:
             self.curr_canvas = self.canvas
         self.curr_canvas.delete("all")
         self.curr_canvas.config(bg= Color.getHexString(self.bgColor.get()))
         rainbow = self.rainbowCheck.get() == 1
         if rainbow or self.incThickYN:
             self.incStep = 1.0/float(self.getDrawCount(self.output))
             self.percent = 0.0
         for c in self.output:
             if c == '[':
                 Draw.push()
             elif c == ']':
                 Draw.pop()
             else:
                 for r in Rule.getDrawings():
                     if c == r[0]:
                         if len(r) > 2:
                             params = (r[1], r[2])
                         else:
                             params = (r[1],)
                         s = float(self.slid_timer.get())
                         self.do(params, s, rainbow)
                         break
         self.butt_print.config(state= 'normal')
コード例 #10
0
ファイル: Scripts.py プロジェクト: EthanGlasserman/Brainbow
def twelveBitVolumeRender():
    histogram = DataParse.loadStack(300, 200, 3000, mode="12bit")
    Draw.volumeRender(histogram, mode="greyscale", prune=0)
コード例 #11
0
from ResetDeck import * # Imports the Reset function for Deck.txt
from Draw import * # Imports the Draw class which allows us to draw cards from Deck.txt

ResetDeck() # Resets Deck.txt to default

Card=Draw() # Draws a card using the class Draw
Card1=Card.Card # Turns the card drawn over to Card1
Card=Draw()
Card2=Card.Card
Card=Draw()
Card3=Card.Card
Card=Draw()
Card4=Card.Card
Card=Draw()
Card5=Card.Card

print([Card1,Card2,Card3,Card4,Card5]) # Prints the 5 cards drawn
コード例 #12
0
ファイル: Play.py プロジェクト: abishgj/TicTacToe
def update_display(matrix,x,y,char):
	os.system('clear')
	Draw.update_mat(matrix,x,y,char)
	Draw.update_board(matrix)
コード例 #13
0
ファイル: HexMain.py プロジェクト: tomprice719/Hex
def draw_weights(player, row, filename):
    weights = model.params[(player, "weights")].get_value()
    Draw.draw(weights[row], board_size, board_size, filename)
コード例 #14
0
ファイル: main.py プロジェクト: tx-chariot-utc-p19/itinerary
if not debug:

    inputData = True
    while inputData:
        print("Entrez les dimensions de la grille:")
        m = int(input("lignes: "))
        n = int(input("colonnes : "))
        if n > 0 and m > 0:
            inputData = False
        else:
            print(
                "Veuillez entrer des dimensions entières strictement positives."
            )

    print("Soit " + str(n * m) + " intersections entre couloirs")
    d.drawGrid(n, m)

    corridorWidth = 0
    while corridorWidth <= 0:
        corridorWidth = float(input("Largeur de couloir en mètres:"))

    print(
        "Entrez les coordonnées des points par lesquels le chariot doit passer. (0,0) représente l'intersection en bas à gauche, (0,"
        + str(n - 1) + ") représente l'intersection en bas à droite.")
    print("Le premier point saisi sera le point de départ.")

    inputData = True
    breakPoints = []

    while inputData:
        x = int(input("Abscisse: "))
コード例 #15
0
 def reset(self):  #moves cars back to starting positions
     Draw.moveTo(self.__draw, self.__x, self.__y)
コード例 #16
0
ファイル: Scripts.py プロジェクト: EthanGlasserman/Brainbow
def fourChannelDraw():
    histogram = DataParse.fourChannelTest()
    Draw.fourChannelDraw(histogram)
コード例 #17
0
def showQuestionBox(
        question, y
):  #this function shows the lie/fact in the right location to the client
    Draw.setColor(Draw.WHITE)
    Draw.filledRect(0, y, 6000, 100)
    Draw.setColor(Draw.BLACK)
    Draw.setFontSize(15)
    Draw.setFontBold(True)
    Draw.string(question, 10, y + 45)
コード例 #18
0
def oneRoundOfQuestions(listFacts, listLies, list_QuestionsAskedAlready):
    Draw.clear()
    Draw.setColor(Draw.BLACK)
    Draw.setFontSize(28)
    Draw.string("Choose the fact that you think is false", 180,
                20)  #instructions
    #No fact or lie should be repeated throughout one game
    fact1 = choosingAQuestion(listFacts, list_QuestionsAskedAlready)  #fact 1
    fact2 = choosingAQuestion(listFacts, list_QuestionsAskedAlready)  #fact 2
    lie = choosingAQuestion(listLies, list_QuestionsAskedAlready)  #lie
    combined = [fact1, fact2, lie]
    random.shuffle(
        combined
    )  #shuffles the options so the lie isn't in the same place each time
    showQuestionBox(combined[0], 100)  #shows client first choice
    showQuestionBox(combined[1], 300)  #shows client second choice
    showQuestionBox(combined[2], 500)  #shows client third choice

    validClick = False
    while validClick == False:
        while not Draw.mousePressed():  #wait until client clicks
            pass

        y = Draw.mouseY(
        )  #find the y location of the mouse click. depending on where it is choose that box or do nothing until they click on a box

        if y >= 100 and y <= 200:  #this means the client chose the first choice
            result = choosingAnAnswer(
                combined[0], lie
            )  #result equals the return of 0 or 1 depending if their choice was the right answer
            while not Draw.mousePressed():  #wait until they click
                pass
            validClick = True

        elif y >= 300 and y <= 400:  #this means the client chose the second choice
            result = choosingAnAnswer(
                combined[1], lie
            )  #result equals the return of 0 or 1 depending if their choice was the right answer
            while not Draw.mousePressed():  #wait until they click
                pass
            validClick = True

        elif y >= 500 and y <= 600:  #this means the client chose the third choice
            result = choosingAnAnswer(
                combined[2], lie
            )  #result equals the return of 0 or 1 depending if their choice was the right answer
            while not Draw.mousePressed():  #wait until they click
                pass
            validClick = True
    return result  #if client got the answer right returns a 1 if not a 0. this then gets incremented to total right
コード例 #19
0
def showBoxFirstPage(y, string, sizeTrue,
                     sizeFalse):  #creates the boxes that are on the first page
    Draw.setColor(Draw.DARK_GRAY)
    Draw.filledRect(0, y + 25, 900, 50)
    Draw.setColor(Draw.WHITE)
    Draw.setFontSize(20)
    Draw.setFontBold(True)
    Draw.string(
        string + "              " + "(" + str(sizeTrue + sizeFalse) + " " +
        'Questions' + ")", 410, y +
        40)  #shows the category and how many questions there are in each topic
コード例 #20
0
def firstPage(
):  #title page showcasing the three categories: nature, history,sports
    Draw.clear()
    Draw.setBackground(Draw.ORANGE)
    Draw.setColor(Draw.WHITE)  #This shows the game title
    Draw.filledRect(300, 25, 300, 50)
    Draw.setColor(Draw.BLACK)
    Draw.setFontSize(20)
    Draw.setFontBold(True)
    Draw.string("Fun Facts Quiz", 380, 40)
    Draw.string("Choose a Category of Questions", 295, 125)  #instructions
    Draw.setFontSize(10)
    Draw.string("Created by Deborah Coopersmith", 10, 10)
    showBoxFirstPage(200, "Nature", len(list_natureTrue),
                     len(list_natureFalse))  #nature category
    showBoxFirstPage(400, "History", len(list_humanTrue),
                     len(list_humanFalse))  #history category
    showBoxFirstPage(600, "Sports", len(list_sportsTrue),
                     len(list_sportsFalse))  #sports category
    Draw.show()

    #client clicks the category they want

    while not Draw.mousePressed():  #wait for user to click
        pass  #get click

    y = Draw.mouseY()
    #depending on which area they click open up the category they want
    if y >= 225 and y <= (225 + 50):
        secondPage(list_natureTrue, list_natureFalse)  #open nature category

    elif y >= 425 and y <= (425 + 50):
        secondPage(list_humanTrue, list_humanFalse)  #open history category

    elif y >= 625 and y <= (625 + 50):
        secondPage(list_sportsTrue, list_sportsFalse)  #open sports category
コード例 #21
0
    def draw(self, array):

        # Initialize the arrays to hold the numbers and the bars
        self.__array = array
        if self.__bars:
            for i in self.__bars:
                Draw.delete(i)
        self.__bars = []

        # Set values for the color spectrum
        freq = 0.2
        phase = 2 * math.pi / 3
        center = 128
        width = 127

        # Draw a bordering box
        Draw.setColor(Draw.BLACK)
        Draw.rect(self.__xOrigin - 1, self.__yOrigin - 1, BOX + 2,
                  BOX // 3 + 2)

        # Loop through each bar in the array
        for i in range(len(array)):

            # Set the three color components and height of that bar.
            red = int(math.sin(freq * array[i]) * width + center)
            green = int(math.sin(freq * array[i] + phase) * width + center)
            blue = int(math.sin(freq * array[i] + 2 * phase) * width + center)

            height = int(BOX // 3 / BARS * (array[i] + 1))

            # Set the color, draw the bar, and add it to the array.
            Draw.setColor(Draw.color(red, green, blue))
            bar = Draw.filledRect(i*int(BOX/BARS) +self.__xOrigin, \
                                  self.__yOrigin+ BOX//3-height,\
                         int(BOX/BARS), height)

            self.__bars += [bar]

        # If you haven't yet made the bottom display, draw it
        if self.__comp == None:

            # Draw a display below the graph indicating the type of sort and
            # number of comparisons done.
            font = min(Y, BOX // 11)

            Draw.setColor(Draw.BLACK)
            Draw.setFontSize(font)

            Draw.string(self.__name + " Sort", self.__xOrigin, \
                        self.__yOrigin + BOX//3 + ARROW + Y)
            Draw.string("Comparisons:", self.__xOrigin, \
                        self.__yOrigin + BOX//3 + ARROW + Y*3)

            # Save as attributes the item used for drawing the string and
            # the x and y coordinates of that element
            self.__compX = self.__xOrigin + int(font * 9)
            self.__compY = self.__yOrigin + BOX // 3 + ARROW + Y * 3
            self.__comp = Draw.string(0, self.__compX, self.__compY)
コード例 #22
0
ファイル: GUI.py プロジェクト: Felix-Thiele/TreeTheoree
 def draw_tree(self):
     self.view.Canvas.delete("all")
     self.nodes = self.tree.get_all_children()
     Draw.draw_tree(self, self.tree, 600, 130)
コード例 #23
0
ファイル: Scripts.py プロジェクト: EthanGlasserman/Brainbow
def axonColorComparison():
    axons = DataParse.readExcelColorSamples()
    Draw.axonComparison(axons, 2)
コード例 #24
0
ファイル: Scripts.py プロジェクト: EthanGlasserman/Brainbow
def kMeans():
    histogram = DataParse.loadStack()
    data, centroidList, distance = Cluster.kMeans(histogram, main.CLUSTERS)
    Draw.clusterDraw(data, centroidList, histogram)
コード例 #25
0
def questionResults(remark, saying):  #whether the client got it right or wrong
    Draw.clear()
    Draw.setColor(Draw.BLACK)
    Draw.setFontSize(35)
    Draw.setFontBold(True)
    Draw.string(remark, 50, 160)  #says whether they succeeded or got it wrong
    Draw.setFontSize(20)
    Draw.string(
        random.choice(saying), 50, 210
    )  #give a saying from the global variable sorry if they were wrong or congrats if they were right
    Draw.setFontSize(15)
    Draw.string(
        "Click anywhere to move on to the next question", 50, 310
    )  #notify the client to move on to the next question or if this was their last question code moves on to endGame function
    Draw.show()
コード例 #26
0
            # draw.put_objectID_into_object(image_np, centroid, objectID)
            if objectID not in location_object:
                location_object[objectID] = [centroid]
            else:
                if len(location_object[objectID]) >= 10:
                    del location_object[objectID][0]
                else:
                    location_object[objectID].append(centroid)
            
        # Kiểm tra nếu độ dịch chuyển của xe đó < 2 thì là đang dừng 
        for (objectID, data) in objects.items():
            data = location_object[objectID]
            if len(data) > 5:
                distance = calculateDistance(data)
                if distance > 1 and distance < 4:
                    draw.put_objectID_into_object_slow(image_np, data[-1], message_SL)
                    send_data()
                # print(distance)
                elif distance <= 1:
                    #print(objectID)
                    draw.put_objectID_into_object_stop(image_np, data[-1], message_ST)        
                    send_data()
					
        cv2.imshow("image", image_np)
        out.write(image_np)
        
        # Press 'q' to quit
        if cv2.waitKey(1) == ord('q'):
            break
cap.release()
out.release()
コード例 #27
0
def endGameScore(string, integer):
    Draw.clear()
    Draw.setColor(Draw.BLACK)
    Draw.setFontSize(20)
    Draw.setFontBold(True)
    Draw.string(string, 60, 180)  #shows how many they go tight
    Draw.string("Click to move on to the next page", 60, 210)

    if integer == 0:  #if integer is 0 shows red screen
        Draw.setBackground(Draw.RED)
    else:  #if integer 1 show green screen
        Draw.setBackground(Draw.GREEN)
    Draw.show()
    while not Draw.mousePressed():  #wait until client clicks
        pass
    Draw.clear()
    Draw.setFontSize(30)  #allow the client to play again
    Draw.string("Want to play again? If so, click on the screen", 60,
                180)  #client needs to click to restart game
    Draw.show()
    while not Draw.mousePressed():  #wait until the client clicks
        pass
コード例 #28
0
 def move(self, message,
          totalInversions):  #moves car based on inversions removed
     step = 480 / totalInversions  #total distance/total inversions=
     #one "step" per inversion removed
     Draw.moveTo(self.__draw,\
                 self.__x+(totalInversions-message[2])*step,self.__y)
コード例 #29
0
def main():
    Draw.setCanvasSize(900, 900)  #makes the canvas size 900 by 900
    while True:
        firstPage()  #client can play as many times as they like
コード例 #30
0
def offsetPolyline(_polylineGUID, _offsetDistance):
    
    # works for CONVEX
    # offset direction is inwards
    
    # parameters:
    #               _polylineGUID
    #               _offsetDistance 
    #
    
    # version: 2012/07/05A
    
    
    name = "offsetPolyline"
    debug = False
    
    # EVALUATION
    
    doc = scriptcontext.doc    
    obj = doc.Objects.Find(_polylineGUID)
    
    if obj == None:
        
        print(name + ": No Object")
    
    crv = obj.CurveGeometry
    if not crv.IsPolyline():
        
        print(name + ": Curve is not polyline")
        return None
    
    if not crv.IsClosed:
        
        print(name + ": Curve is not closed")
        d = crv.PointAtEnd.DistanceTo(crv.PointAtStart)
        
        return None
    
    L = []
    
    pts= rs.CurvePoints(_polylineGUID)
    
    for i in range((len(pts)-1)):

        #print("")
        
        iP =  (i-1) % (len(pts)-1)
        iC =  (i+1) % (len(pts)-1)
        iN =  (i+2) % (len(pts)-1)
        
        #print(str(iP) + " " + str(i) + " " + str(iC)+ " " + str(iN))
        
        v1 = rs.VectorCreate(pts[iP], pts[i])
        v2 = rs.VectorCreate(pts[iN], pts[iC])

        
        a1 = rs.VectorAngle(v1,v2)
        a2 = rs.VectorAngle(rs.VectorReverse(v1),v2)
        
        if a1 < a2:
            if debug:
                print(str(a1) + " < " +  str(a2))
            # use first
            
        else:
            
            v1 = rs.VectorReverse(v1)
            if debug:
                print(str(a2) + " < " +  str(a1))
            # use second
        
        v = ((v1[0] + v2[0])/2, (v1[1] + v2[1])/2,(v1[2] + v2[2])/2)
        
        vY =  rs.VectorUnitize(v)
        vX = rs.VectorCreate(pts[i], pts[iC])
        vZ=  rs.VectorCrossProduct(vX, vY)
        
        ptMid =  ((pts[i][0] + pts[iC][0])/2, (pts[i][1] + pts[iC][1])/2, (pts[i][2] + pts[iC][2])/2)  
        
        p = rs.PlaneFromNormal(ptMid, vZ, vX)
        
        
        #DEBUG
        if debug:
            Draw.drawPalneAxeAndArrows(p, _offsetDistance)
            # make sure green arrawsa are pointing inwards
        
    
        ptA = movePoint(pts[i], rs.VectorScale( rs.VectorUnitize( p[2] ), _offsetDistance))
        ptB = movePoint(pts[iC], rs.VectorScale( rs.VectorUnitize( p[2] ), _offsetDistance))
        
        ln =  rs.AddLine(ptA, ptB)
        
        L.append(ln)
            
    
    P = []
    
    for i in range(len(L)):
        
        lineAPts =  lineEndPoints(L[i])
        lineBPts =  lineEndPoints(L[(i+1) % len(L)])
        
        intersection = rs.LineLineIntersection((lineAPts[0], lineAPts[1]), (lineBPts[0],lineBPts[1]))
        
        ptI = intersection[0]
        
        P.append(ptI)
        
    rs.DeleteObjects(L)
    
    P.append(P[0])
    
    return rs.AddPolyline(P)
コード例 #31
0
rawpath = planner.path()

from Draw import *
###################         SMOOTHING
spath = smooth(grid=grid, path=rawpath[:])

###################         WAYPOINTING
waypoints = waypointing(path=spath, speed=0.5)

###################         FORCE FIELD
waypoints = forceField(planner=planner, waypoints=waypoints, neighborhood=2)

###################         WAYPOINTING AGAIN
waypoints = waypointing(path=waypoints, speed=0.5)

###################         DRAWING

d = Draw(rows=grid.rows, cols=grid.cols, cellSize=20)
d.drawGrid()

d.fillCells(grid=grid.obstacleGrid, color='green')
d.fillCells(grid=grid.closedGrid, color='grey')

d.drawLine(path=rawpath, color='red')
d.drawLine(path=spath, color='orange')
d.drawLine(path=waypoints, color='blue')

# d.drawPoints(pointset=waypoints, color='blue')

d.loop()
コード例 #32
0
def runTest(Train=True):
    step = 0  ##跨越episode的总步数计数
    t_all = []  ##agent,baseline,baseline_f,random,random2
    r_all = []
    x_all = [[], [], [], [], []]
    profit_all = [[], [], [], [], []]
    pay_all = [[], [], [], [], []]

    volume_episode = [[], [], [], [], []]
    profit_episode = [[], [], [], [], []]
    pay_episode = [[], [], [], [], []]
    income_episode = [[], [], [], [], []]
    profit_p_episode = [[], [], [], [], []]
    value_episode = [[], [], [], [], []]
    value_p_episode = [[], [], [], [], []]

    for episode in range(episode_cnt_test):
        # initial observation
        observation = env.reset(test=True)  ##feature数组
        volume_episode_cnt = [0, 0, 0, 0, 0]
        pay_episode_cnt = [0, 0, 0, 0, 0]
        income_episode_cnt = [0, 0, 0, 0, 0]
        profit_episode_cnt = [0, 0, 0, 0, 0]
        profit_p_episode_cnt = [0, 0, 0, 0, 0]
        value_episode_cnt = [0, 0, 0, 0, 0]
        value_p_episode_cnt = [0, 0, 0, 0, 0]
        var = 3  # control exploration
        actions = []

        while True:
            # RL choose action based on observation
            if insurance:
                arr = ddpg.choose_action(observation)
                arr = np.clip(np.random.normal(arr, var), -1, 1)
                action_value = np.clip(
                    int((float(arr[0]) + 1) / 2 * 10) / 10, 0, 0.9)
                action = arr
            else:
                action = ddpg.choose_action(observation)
                action = np.clip(np.random.normal(action, var), 0, 1)

            r = observation[0]
            r_all.append(r)
            t_all.append(env.getT())
            x_all[0].append(env.getAction_Income(
                action_value, isFloat=True))  ##x 仅仅是定价 ,后面的profit才是真是收益
            x_all[1].append(env.getAction_Income(env.getBaseAction()))
            x_all[2].append(env.getAction_Income(env.getBaseAction_f()))

            pf_cmp0, i_cmp0, py_cmp0, v_cmp0, pf_p0, v_p0 = env.getAction_Profit(
                action_value, isFloat=True)
            pf_cmp1, i_cmp1, py_cmp1, v_cmp1, pf_p1, v_p1 = env.getAction_Profit(
                env.getBaseAction())
            pf_cmp2, i_cmp2, py_cmp2, v_cmp2, pf_p2, v_p2 = env.getAction_Profit(
                env.getBaseAction_f())
            #
            if is_Theory:
                pf_cmp3, i_cmp3, py_cmp3, v_cmp3, pf_p3, v_p3 = env.getAction_Profit(
                    env.getTheoryPrice(), isFloat=True)
                x_all[3].append(
                    env.getAction_Income(env.getTheoryPrice(), isFloat=True))
            else:
                pf_cmp3, i_cmp3, py_cmp3, v_cmp3, pf_p3, v_p3 = 0, 0, 0, 0, 0, 0

            i_cmp_list = [i_cmp0, i_cmp1, i_cmp2, i_cmp3]
            py_cmp_list = [py_cmp0, py_cmp1, py_cmp2, py_cmp3]
            pf_cmp_list = [pf_cmp0, pf_cmp1, pf_cmp2, pf_cmp3]
            v_cmp_list = [v_cmp0, v_cmp1, v_cmp2, v_cmp3]
            pf_p_list = [pf_p0, pf_p1, pf_p2, pf_p3]
            v_p_list = [v_p0, v_p1, v_p2, v_p3]
            volume_list = list(map(lambda x: env.getVolume(x), pf_cmp_list))

            income_episode_cnt = addToList(income_episode_cnt, i_cmp_list, n)
            pay_episode_cnt = addToList(pay_episode_cnt, py_cmp_list, n)
            profit_episode_cnt = addToList(profit_episode_cnt, pf_cmp_list, n)
            volume_episode_cnt = addToList(volume_episode_cnt, volume_list, n)
            profit_p_episode_cnt = addToList(profit_p_episode_cnt, pf_p_list,
                                             n)
            value_episode_cnt = addToList(value_episode_cnt, v_cmp_list, n)
            value_p_episode_cnt = addToList(value_p_episode_cnt, v_p_list, n)

            pay_all = appendToList(pay_all,
                                   [py_cmp0, py_cmp1, py_cmp2, py_cmp3], n)
            profit_all = appendToList(profit_all,
                                      [pf_cmp0, pf_cmp1, pf_cmp2, pf_cmp3], n)

            # RL take action and get next observation and reward
            ##reward int , done boolean
            observation_, r, done = env.step(action_value, isFloat=True)
            if Train:
                ddpg.store_transition(observation, action, r / 10,
                                      observation_)

                # 总共学了200步以上后,每隔5步进行一次学习
                if ddpg.pointer > MEMORY_CAPACITY:
                    var *= .9995  # decay the action randomness
                    ddpg.learn()

            observation = observation_

            # break while loop when end of this episode
            if done:
                # if (episode == episode_cnt-1):
                # Draw.drawHist(actions, "actions", ranges=(0, 16))
                for i in range(len(LEGEND)):
                    profit_episode[i].append(profit_episode_cnt[i])
                    volume_episode[i].append(volume_episode_cnt[i])
                    pay_episode[i].append(pay_episode_cnt[i])
                    income_episode[i].append(income_episode_cnt[i])
                    profit_p_episode[i].append(profit_p_episode_cnt[i])
                    value_episode[i].append(value_episode_cnt[i])
                    value_p_episode[i].append(value_p_episode_cnt[i])

                break
            step += 1

    # end of game
    print('game over')
    text = ("" if not Train else "_train")
    drawXT([r_all], t_all, LEGEND, "r", "t" + text, avg=False)
    Draw.plotMulti(profit_episode[:n],
                   "rewards_episode" + text,
                   legend=LEGEND[:n])
    if not Train:
        drawXT(x_all, r_all, LEGEND, "r", "x", avg=True)
        drawXT(profit_all, r_all, LEGEND, "r", "profit", avg=True)
        drawXT(x_all, t_all, LEGEND, "t", "x", avg=True)
        drawXT(profit_all, t_all, LEGEND, "t", "profit", avg=True)

        Draw.plotMulti(volume_episode[:n],
                       "volume_episode_test",
                       legend=LEGEND[:n])
        Draw.plotMulti(pay_episode[:n], "pay_episode_test", legend=LEGEND[:n])
        Draw.plotMulti(income_episode[:n],
                       "income_episode_test",
                       legend=LEGEND[:n])

    print_list = list(
        map(
            lambda i: list(
                map(lambda x: np.mean(x), [
                    profit_episode[i], pay_episode[i], income_episode[i],
                    volume_episode[i], value_episode[i], profit_p_episode[
                        i], value_p_episode[i]
                ])), np.arange(0, len(LEGEND[:n]), 1)))
    print_df = pd.DataFrame(print_list,
                            columns=[
                                "profit", "pay", "income", "volume", "value",
                                "profit_p", "value_p"
                            ],
                            index=LEGEND[:n])
    print_df.to_csv("results/print-list" + text + ".csv", index=True, sep=',')
コード例 #33
0
ファイル: main.py プロジェクト: Miguel-EpicJS/PaintV2
    if btnBluePlus.getPressedButton(50, 540, 50, 50) and blue < 255:
        blue += alter

    if btnBlueMinus.getPressedButton(1200, 540, 50, 50) and blue > 1:
        blue -= alter

def AlterAllColors():
    AlterRedColor()
    AlterGreenColor()
    AlterBlueColor()

#Objects
events = Event.Events()
colors = Colors.Colors()
keyboard = Keyboard.KeyBoard()
draw = Draw.Draw()
text = Text.Text()

btnPlus = Button.Button()
btnMinus = Button.Button()
btnPlusWidth = Button.Button()
btnPlusHeight = Button.Button()
btnMinusWidth = Button.Button()
btnMinusHeight = Button.Button()

btnRedPlus = Button.Button()
btnRedMinus = Button.Button()

btnBluePlus = Button.Button()
btnBlueMinus = Button.Button()
コード例 #34
0
ファイル: Row5.py プロジェクト: AmbBAI/JunkCode
def initgame(game_info):
    global game, draw
    game = Game.game(game_info)
    draw = Draw.draw(game_info)
    game.initcore()
    draw.initdraw(game)
コード例 #35
0
ファイル: test.py プロジェクト: tjwjy/Model_python
#     temp=powerlaw.rvs(4)
#     rvs.append(temp)
# rvs2=[1/i for i in rvs]
# hist=np.arange(0,10,.5)
# fit=plw.Fit(rvs2,xmin=1)
# print (fit.alpha)
# print (fit.sigma)
# plt.hist(rvs2,bins=hist)
# plt.show()
import Model5
import Environment
import Individual
import Cal_para
import Draw
args_model=[0.6,-0.21]
args_time=[2,1,10000]
args_steps=[-1.80,5]
args_grid=[[20,20],[10,2,10,2],200]
time=100
temp_routeList=[]
Envir=Environment.normal_network_Environment( 0,100,.1)
#model=Model5.HomeOrWork_Model(args_model=args_model,args_t=args_time,args_steps=args_steps,environment=Envir,visited_Place=[],homeposition=random.choice(Envir.locations),workposition=random.choice(Envir.locations))
model=Individual.Nomal_Individual(args_model=args_model,args_t=args_time,args_step=args_steps,simulate_time=time,Environment=Envir)
model.simulate()
print (9)
cal=Cal_para.Cal_para(model.data_mid.route,Envir)
dis=cal.get_visit_location_number_disput()
draw=Draw.Draw(cal,[model.home_loc,model.work_loc])
draw.draw_visit_location_number_disput()
draw.draw_location_disput(model.data_mid)
print (1)
コード例 #36
0
ファイル: Scripts.py プロジェクト: EthanGlasserman/Brainbow
def volumeRender():
    histogram = DataParse.loadStack(300, 200, 3000, mode="8bit", segmented=False)
    Draw.volumeRender(histogram, mode="fullcolor", prune=0)
コード例 #37
0
def introScreen():
    Draw.setColor(Draw.BLUE)
    Draw.filledRect(150, 250, 600, 200)
    Draw.setColor(Draw.RED)
    Draw.setFontSize(100)
    Draw.string("PLAY", 250, 300)
コード例 #38
0
ファイル: Scripts.py プロジェクト: EthanGlasserman/Brainbow
def volumeRenderLowerCorner():
    histogram = DataParse.loadStack()
    histogram = Utils.magnifyLowerLeft(histogram, .25)
    Draw.volumeRender(histogram, mode="greyscale", prune=0)
コード例 #39
0
def board():
    #initialize the variables that will calculate each col, row,
    #and the size of each cell/piece on the game board
    pixelBegFirstRow = 1
    pixelBegFirstCol = 20

    numPixelsRows = 500 + pixelBegFirstRow
    numPixelsCols = 700 + pixelBegFirstCol

    # Mathematical calculations for rows
    sizeRow = numPixelsRows // len(gameBoard)
    pixelBegLastRow = numPixelsRows - sizeRow + pixelBegFirstRow

    # Mathematical calculations for columns
    sizeCol = numPixelsCols // len(gameBoard[0])
    pixelBegLastCol = numPixelsCols - sizeCol + pixelBegFirstCol

    sizeOval = 50

    #graphic representation of the gameboard
    Draw.clear()
    Draw.setColor(Draw.BLUE)
    Draw.filledRect(80, 80, numPixelsCols, numPixelsRows)
    for row in range(pixelBegFirstRow, pixelBegLastRow, sizeRow):
        for col in range(pixelBegFirstCol, pixelBegLastCol, sizeCol):
            #setting the color for the circles
            if gameBoard[row // sizeRow][col // sizeCol] == Draw.RED:
                Draw.setColor(Draw.RED)
            elif gameBoard[row // sizeRow][col // sizeCol] == Draw.YELLOW:
                Draw.setColor(Draw.YELLOW)
            else:
                Draw.setColor(Draw.WHITE)
            Draw.filledOval(sizeCol + col, sizeRow + row, sizeOval, sizeOval)
コード例 #40
0
ファイル: Scripts.py プロジェクト: EthanGlasserman/Brainbow
def histogram():
    histogram = DataParse.loadStack()
    Draw.draw(histogram)
コード例 #41
0
def gameOver(totalRedBestRun, totalYellowBestRun):
    #If someone won, draw the gameOver plaque
    if totalRedBestRun[0] == 4 or totalYellowBestRun[0] == 4:
        Draw.setColor(Draw.WHITE)
        Draw.filledRect(150, 250, 600, 200)
        Draw.setColor(Draw.RED)
        Draw.setFontSize(70)
        if totalRedBestRun[0] == 4:
            #player won, make exciting sign!
            Draw.string("YOU WON!!", 165, 300)
            Draw.show()
            time.sleep(3)
            introScreen()
            return True
        elif totalYellowBestRun[0] == 4:
            #comp won, write "you lost"
            Draw.string("You lost", 165, 300)
            Draw.show()
            time.sleep(3)
            introScreen()
            return True
    return False
コード例 #42
0
ファイル: Scripts.py プロジェクト: EthanGlasserman/Brainbow
def sliceDraw():
    histogram = DataParse.loadStack()
    data, centroidList, distance = Cluster.kMeans(histogram, main.CLUSTERS)
    Draw.drawSlice(data, centroidList)
コード例 #43
0
ファイル: LinSys.py プロジェクト: edwardsCam/Python-Scripts
 def draw(self, n, step=False):
     p1, p2 = Draw.move(n)
     self.curr_canvas.create_line(p1[0], p1[1], p2[0], p2[1], fill= self.color, width= self.thick)
     if step:
         self.curr_canvas.update_idletasks()
コード例 #44
0
ファイル: Core.py プロジェクト: quantum0813/Loltris
    def run(self):
        if not hasattr(self, "running") or not hasattr(self, "eventHandler"):
            raise GameError("Game has not been properly initialized")

        timers = Struct(
                print_framerate = 0,
                )

        while self.running:

            for timer in timers:
                timers[timer] += 1

            self.clock.tick(self.ticktime)
            self.events = Pygame.event.get()
            self.interrupts = []

            if timers.print_framerate == TETRIS_FRAMERATE * DISPLAY_TETRIS_FRAMERATE_INTERVAL:
                timers.print_framerate = 0
                Log.notice("Framerate: {}".format(int(round(self.clock.get_fps()))))

            ## The events and updates should be handled in reverse order (the things on top go first)
            queue = sorted(self.jobs, key=lambda obj: getattr(self.jobs, obj).queue, reverse=True)
            for objname in queue:
                if objname not in self.jobs:
                    ## In case a Job modifies self.jobs, removing this job.
                    continue

                obj = self.getJob(objname)
                if obj.handling_events:
                    for event in self.events:
                        if event.type not in self.lock:
                            obj.eventHandler(event)

                ## XXX: This second check of update_required is necessarry because the eventHandler may either modify
                ##      or call methods that modify parameters in obj.
                if obj.update_required:
                    obj.update()

            queue = sorted(self.jobs, key=lambda obj: getattr(self.jobs, obj).queue)
            ## Handle resizing (redraw everything underneath the resized job)
            for objname in queue:
                obj = self.getJob(objname)
                if obj.__dict__.get("resize"):
                    for job in self.getJobsIn(objname):
                        job.force_draw = True
                    obj.resize = False

            ## Unlike the events and updates, drawing is handled so that the lowest go first
            for objname in queue:

                if objname not in self.jobs:
                    ## In case a Job modifies self.jobs, removing this job.
                    continue

                obj = self.getJob(objname)

                if objname not in self.jobs:
                    ## In case a Job modifies self.jobs, removing itself during update.
                    continue

                if obj.draw_required:
                    if obj.fill:
                        Draw.fillJob(self.screen, obj.fill, obj)
                    obj.draw()


            Pygame.display.flip()

            for event in self.events:
                if event.type not in self.lock:
                    self.eventHandler(event)

            if self.running:
                self.running()

            ## Remove locks
            self.lock = {}

            self.handleInterrupts()

        return self.ret
コード例 #45
0
def main():
    Draw.setCanvasSize(750, 605)

    #draw finish line
    Draw.setColor(Draw.BLACK)
    Draw.rect(580, 75, 70, 455)
    for i in range(7):
        Draw.filledRect(580, 75 + 70 * i, 35, 35)
    for i in range(6):
        Draw.filledRect(615, 110 + 70 * i, 35, 35)

    #draw racetrack
    Draw.setColor(Draw.DARK_GRAY)
    Draw.filledRect(100, 75, 480, 455)
    Draw.setColor(Draw.WHITE)
    for i in range(4):
        for j in range(0, 470, 20):
            Draw.filledRect(110 + j, 157 + 92 * i, 10, 5)

    #create cars
    bubbleCar = Car(100, 83, Draw.RED, "B")
    selectionCar = Car(100, 175, Draw.YELLOW, "S")
    insertionCar = Car(100, 267, Draw.GREEN, " I")
    mergeCar = Car(100, 359, Draw.BLUE, "M")
    quickCar = Car(100, 451, Draw.VIOLET, "Q")

    cars = {"bubble":bubbleCar, "selection":selectionCar, \
            "insertion":insertionCar,"merge":mergeCar, "quick":quickCar}

    #Race 1: random array of 10
    #create array
    a = [0] * 10
    for i in range(len(a)):
        a[i] = random.randint(0, 99)
    print("Random array 10:", a)
    #draw title
    title = drawTitle("Round 1: Random Array", a)
    #start race
    race(a, cars)
    time.sleep(3)

    #reset board
    Draw.delete(title)
    for k in cars:
        cars[k].reset()

    #Race 2: random array of 100
    #create array
    b = [0] * 100
    for i in range(len(b)):
        b[i] = random.randint(0, 99)
    print("Random array 100:", b)
    #draw title
    title = drawTitle("Round 2: Random Array", b)
    #start race
    race(b, cars)
    time.sleep(3)

    #reset board
    Draw.delete(title)
    for k in cars:
        cars[k].reset()

    #Race 3: almost sorted 100
    #create sorted array
    c = [0] * 100
    for i in range(len(c) - 1):  #leave last element unsorted
        c[i] = i
    #swap 10 random pairs
    for i in range(10):
        n = random.randint(0, len(c) - 2)
        temp = c[n]
        c[n] = c[n + 1]
        c[n + 1] = temp
    print("Almost sorted:", c)
    #draw title
    title = drawTitle("Round 3: Almost Sorted Array", c)
    #start race
    race(c, cars)
コード例 #46
0
    'splitter': ('random', 'best'),
    'min_samples_leaf': range(1, 30),
    'max_leaf_nodes': range(2, 30)
}]
clf = GridSearchCV(DecisionTreeClassifier(),
                   parameters,
                   cv=5,
                   scoring='f1',
                   verbose=0,
                   n_jobs=-1)
y_pred = clf.fit(x_train.loc[:, best_features],
                 y_train).predict(x_test.loc[:, best_features])
print(clf.cv_results_['mean_test_score'])
print(clf.best_params_)

Draw.plot_confusion_matrix(y_test, y_pred, title='Decision Tree')
plt.show()


#%% parameter tuning - K-nearest neighbour
def KNN():
    start_num = 1
    end_num = 100
    temp_list = []

    for step in range(start_num, end_num):
        knn_model = KNeighborsClassifier(n_neighbors=step)
        y_pred = knn_model.fit(x_train, y_train).predict(x_test)
        score = f1_score(y_test, y_pred, average='binary')
        temp_list.append(((score, step), step))
コード例 #47
0
def createPromptArea(t, x, y, wide, promptHeight):
    Draw.setFontSize(20)
    Draw.setColor(Draw.GRAY)
    Draw.setFontBold(False)
    Draw.string("Press Enter to proceed", 0, y - 30)
    Draw.setColor(Draw.GRAY)
    Draw.filledRect(x, y, wide, promptHeight)
    Draw.setColor(Draw.WHITE)
    Draw.setFontBold(True)
    centerAlignedStr(t, y + 50)

    Draw.show()
コード例 #48
0
ファイル: Interact.py プロジェクト: abishgj/MontyHall
def init():
	Draw.display(choice)
	seq_list = MontyH.arrange()
	return seq_list
コード例 #49
0
def getStringWidth(s):
    box = Draw.bbox(Draw.string(s, -100, -100))
    width = box[2] - box[0]
    return width
コード例 #50
0
def getClick():
    x = Draw.mouseX()
    y = Draw.mouseY()
    return x, y
コード例 #51
0
ファイル: Interact.py プロジェクト: abishgj/MontyHall
def init():
    Draw.display(choice)
    seq_list = MontyH.arrange()
    return seq_list
コード例 #52
0
def homePage():
    Draw.clear()
    display = True

    #until the user clicks on the button area, display the home page
    while display:
        #draw the home page
        Draw.setFontSize(35)
        Draw.setFontBold(False)
        Draw.setColor(Draw.DARK_BLUE)
        centerAlignedStr("Welcome to:", 50)
        centerAlignedStr("Create Your Own Income Statement", 90)
        #draw the button to get to the "next page" --> prompt areas
        Draw.filledRect(375, 450, 250, 100)
        Draw.setColor(Draw.WHITE)
        Draw.setFontBold(True)
        Draw.setFontSize(20)
        Draw.string("Click here to get started", 387, 490)

        #when the user clicks on the button, stop displaying the home page
        if Draw.mousePressed():
            if Draw.mouseX() >375 and Draw.mouseX() < 375 + 250 and\
               Draw.mouseY() >450 and Draw.mouseY() < 450 + 100:
                display = False

        Draw.show()
コード例 #53
0
def checkDate(m, d):
    Draw.clear()
    months30 = ["November", "April", "June", "September"]
    if m in months30 and int(d) == 31 or m == "February" and int(d) > 29:
        return False
    return True
コード例 #54
0
import Draw
Draw.initializeGraphics(['test'])
Draw.runGraphics()
コード例 #55
0
def race(a, cars):
    #count inversions and assign initial number to each sort
    totalInversions = bubbleInversions = selectionInversions \
       = insertionInversions = mergeInversions = quickInversions = \
       countInversions(a)
    print("total inversions=", totalInversions)

    #create queue
    q = multiprocessing.Queue()
    prioritized = PriorityQueue(q)
    jobs = [
       multiprocessing.Process(target=bubbleSort, args=(a,q,bubbleInversions)),\
       multiprocessing.Process(target=selectionSort, args=(a,q,selectionInversions)),\
       multiprocessing.Process(target=insertionSort, args=(a,q,insertionInversions)),\
       multiprocessing.Process(target=mergeSort, args=(a,q,mergeInversions)),\
       multiprocessing.Process(target=quickSort, args=(a,q,quickInversions))
    ]

    #starting message
    time.sleep(1)
    flash("On your marks", 260)
    flash("get set", 300)
    flash("SORT!", 300)

    #initialize comparisons string
    Draw.setFontSize(20)
    comps = 0
    compstr = Draw.string(str(comps), 232, 50)
    Draw.show()

    #initialize start and end time
    startTime = 0
    endTime = 0

    #start the processes
    for p in jobs:
        p.start()
    time.sleep(3)  #give time for messages to get to priority queue

    # stop when all processes are done running or 10 secs after winner wins
    numDone = 0

    while numDone < len(jobs) and endTime - startTime < 10:

        if startTime > 0:
            endTime = time.time()  #keeps track of time since winner

        # Get the next message that one of the processes has sent
        message = prioritized.get()
        print(message)

        #update number of comparisons
        Draw.delete(compstr)
        comps = message[0]
        compstr = Draw.string(str(comps), 232, 50)
        Draw.show()

        #see which sort the message is from, and move its car to the number
        #of steps corresponding to its inversions removed
        if message[1] != "done":
            cars[message[1]].move(message, totalInversions)

        # if the process has announced that it is done, increment "done"s by 1
        else:
            numDone += 1
            #the first one done is the winner
            if numDone == 1:
                winner = message[2]
                startTime = time.time()  #start 10 sec timer

    #display winner
    Draw.setFontSize(30)
    result = Draw.string("Winner: " + winner, 210, 540)
    Draw.show()
    time.sleep(2)
    #clear comparison and winner strings
    Draw.delete([compstr, result])