Пример #1
0
    def setupWindow(self) :
        # Define the frame that holds all of the world views.
        self.worldView = Frame(self.frame)
        self.worldView.pack(side=TOP,expand=YES)

        # Define the label that displays the current time step.
        self.timeLabel = Label(self.worldView,text="t=0")
        self.timeLabel.pack(side=TOP,expand=YES)

        # Define the view for the world as seen by the "world" object.
        self.realView = WorldView(self.worldView,self,"Real")
        self.realView.pack(side=LEFT,expand=YES,fill=BOTH)

        # Define the view of the world as seen by the sensor.
        self.sensorView = WorldView(self.worldView,self,"Sensor")
        self.sensorView.pack(side=LEFT,expand=YES,fill=BOTH)

        # Define the view of the world as seen by the planner.
        self.plannerView = WorldView(self.worldView,self,"Planner")
        self.plannerView.pack(side=LEFT,expand=YES,fill=BOTH)

        # Define the legend which displays the values with respect to
        # the color coding.
        legendFrame = Frame(self.worldView)
        legendFrame.pack(side=LEFT,expand=YES)
        Label(legendFrame,text="Legend").pack(side=TOP)
        self.legend = Canvas(legendFrame,width=80,height=200)
        self.legend.pack(side=TOP,expand=YES)
        self.makeLegend(0.0,1.0);
Пример #2
0
 def __init__(self):
     mapFile = 'images/world.tif'
     #self.view = WorldView(controller=self, mapFile=mapFile, mapSize=self.mapSize)
     self.view = WorldView(controller=self)
     self.map = Map(mapFile, screenSize=self.view.screenSize)
     self.view.map = self.map
     self.landmark = None
     self.landmarks = None
     self.score = 0
     self.maximumDistance = 1000
     self.timer = None
     self.worstGuess = None
     self.client = GameClient()
     self.deferred = defer.Deferred()
     self.setRounds()
     self.crops = {'world':(-180.0, 90.0, 180.0, -90.0),
                   'us':(-125, 52, -65, 22),
                   'europe':(-25, 72, 51, 34)
               }
Пример #3
0
class  GraphicalWorld (World,Tk) :

    def __init__(self,r=1.0,s=1.0,v=1.0,cloudsize=1.0) :
        World.__init__(self,r,s,v,cloudsize)
        Tk.__init__(self)
        self.title("World")
        self.iconname("World")
        self.frame = Frame(self)
        self.frame.pack(side=TOP,expand=YES,fill=BOTH)
        self.setupMenu()
        self.setupWindow()
        self.setupOptionsEntry()




    def setupMenu(self) :
        # Add a menu bar that gives the user some basic options.
        self.menuBar = Menu(self)
        self.config(menu=self.menuBar)

        # Add a "file" submenu.
        self.fileMenu = Menu(self.menuBar)
        self.fileMenu.add_command(label="Start",command=self.start)
        self.fileMenu.add_command(label="Quit",command=self.quit)
        self.menuBar.add_cascade(label="File",menu=self.fileMenu)
	self.protocol("WM_DELETE_WINDOW", self.quit)



    def start(self) :
	# Get the parameters from the inputs in the window.
        N = int(self.NValue.get())
        self.r = float(self.rValue.get())
        self.s = float(self.sValue.get())
        self.v = float(self.vValue.get())
        self.cloudSize = float(self.cloudSizeValue.get())

        self.intializeVariables(self.r,self.s,self.v,self.cloudsize)

	from XML.XMLMessageExternalCommand import XMLMessageExternalCommand
	parameter = XMLMessageExternalCommand()
	parameter.setParameterValue(XMLMessageExternalCommand.RESTART)
	parameter.createRootNode()
        for vacuum in self.vacuumArray:
	    # Turn on each of the vacuums - i.e. reset the vacuum.
	    # print("GraphicalWorld.start - Vacuum: {0}".format(vacuum))
            #vacuum.setWorking(True)
            #vacuum.setStatus(3)
            #vacuum.initializeTime(0.0)
	    self.channel.getRouter().sendString(
		Router.VACUUM,parameter.xml2Char(False),vacuum.getID())

        H = []
        R = []
        self.draw()
        skip = 10;
        for i in range(N) :
            #import time # DEBUG
            #time.sleep(1) # DEBUG
            self.inc()
            #if(i%skip==0) :
	    self.draw()

            H.append(sum(sum(self.A)))
            R.append(sum(self.Moisture>0))

	    #self.printVacuumInfo(i)
	    
        print("Mean of H: {0}".format(mean(H)))




    def setupWindow(self) :
        # Define the frame that holds all of the world views.
        self.worldView = Frame(self.frame)
        self.worldView.pack(side=TOP,expand=YES)

        # Define the label that displays the current time step.
        self.timeLabel = Label(self.worldView,text="t=0")
        self.timeLabel.pack(side=TOP,expand=YES)

        # Define the view for the world as seen by the "world" object.
        self.realView = WorldView(self.worldView,self,"Real")
        self.realView.pack(side=LEFT,expand=YES,fill=BOTH)

        # Define the view of the world as seen by the sensor.
        self.sensorView = WorldView(self.worldView,self,"Sensor")
        self.sensorView.pack(side=LEFT,expand=YES,fill=BOTH)

        # Define the view of the world as seen by the planner.
        self.plannerView = WorldView(self.worldView,self,"Planner")
        self.plannerView.pack(side=LEFT,expand=YES,fill=BOTH)

        # Define the legend which displays the values with respect to
        # the color coding.
        legendFrame = Frame(self.worldView)
        legendFrame.pack(side=LEFT,expand=YES)
        Label(legendFrame,text="Legend").pack(side=TOP)
        self.legend = Canvas(legendFrame,width=80,height=200)
        self.legend.pack(side=TOP,expand=YES)
        self.makeLegend(0.0,1.0);


    def setupOptionsEntry(self) :
        # Create the frame that holds the options that can be changed
        # in the graphical view.
        self.entryFrame = Frame(self)
        self.entryFrame.pack(side=TOP,expand=YES)

        # Define the entry for the number of time steps.
        self.NValue = StringVar()
        self.NValue.set("30")
        Label(self.entryFrame,text="N=").pack(side=LEFT,padx=5)
        self.NValueEntry = Entry(self.entryFrame,textvariable=self.NValue,width=7)
        self.NValueEntry.pack(side=LEFT,expand=NO)

        # Define the entry for the value of r
        self.rValue = StringVar()
        self.rValue.set(str(self.r))
        Label(self.entryFrame,text="r=").pack(side=LEFT,padx=5)
        self.rValueEntry = Entry(self.entryFrame,textvariable=self.rValue,width=7)
        self.rValueEntry.pack(side=LEFT,expand=NO)

        # Define the entry for the value of s.
        self.sValue = StringVar()
        self.sValue.set(str(self.s))
        Label(self.entryFrame,text="s=").pack(side=LEFT,padx=5)
        self.sValueEntry = Entry(self.entryFrame,textvariable=self.sValue,width=7)
        self.sValueEntry.pack(side=LEFT,expand=NO)

        # Define the entry for the value of v.
        self.vValue = StringVar()
        self.vValue.set(str(self.v))
        Label(self.entryFrame,text="v=").pack(side=LEFT,padx=5)
        self.vValueEntry = Entry(self.entryFrame,textvariable=self.vValue,width=7)
        self.vValueEntry.pack(side=LEFT,expand=NO)

        # Define the entry for the value of the cloud size.
        self.cloudSizeValue = StringVar()
        self.cloudSizeValue.set(str(self.cloudsize))
        Label(self.entryFrame,text="cloud size=").pack(side=LEFT,padx=5)
        self.cloudSizeValueEntry = Entry(self.entryFrame,textvariable=self.cloudSizeValue,width=7)
        self.cloudSizeValueEntry.pack(side=LEFT,expand=NO)

        # Define the button that will start the simulation when clicked.
        Button(self,text="Start",command=self.start).pack(side=TOP)



    def makeLegend(self,lower,upper) :
        # Routine to show the color scale and associated values that
        # are displayed in the world views.

        # Delete the current view and define the colors to be displayed.
        self.legend.delete(ALL)
        color = FalseColor(lower,upper)
        for scale in range(255) :
            # For each color go through and create a sliver of a
            # rectangle with the given color.
            self.legend.create_rectangle(65,200*scale/255,
                                         80,200*(scale+1)/255.0,
                                         fill=color.calcColor(upper-float(scale)/255.0*(upper-lower)),
                                         outline="")

        # Display the values for the min, max, and middle values.
        self.legend.create_text(30,190,text="{0:8.1E}".format(lower),justify=LEFT)
        self.legend.create_text(30,100,text="{0:8.1E}".format((upper+lower)*0.5),justify=LEFT)
        self.legend.create_text(30, 10,text="{0:8.1E}".format(upper),justify=LEFT)


    def draw(self) :
        # Get the arrays that need to be plotted
	sensor = self.getSensor()
	if(sensor):
	    sensorArray = self.getSensor().getArray()

	planner = self.getPlanner()
	if(planner) :
	    plannerArray = self.getPlanner().getArray()
	
        # Figure out the bounds for the color scale.
	if(planner and sensor) :
	    low  = amin([amin(self.A),amin(sensorArray),amin(plannerArray)])
	    high = amax([amax(self.A),amax(sensorArray),amax(plannerArray)])

	else:
	    low = amin(self.A)
	    high = amax(self.A)

        # Draw each depiction of the world
        self.realView.draw(self.vacuumArray,self.A,[low,high])
	if(sensor):
	    self.sensorView.draw(self.vacuumArray,sensor.getArray(),[low,high])

	if(planner):
	    self.plannerView.draw(self.vacuumArray,plannerArray,[low,high])

        # Update the view of the time and the legend
        self.timeLabel.config(text="t= {0}".format(self.time))
        self.makeLegend(low,high)

        self.update()
        #time.sleep(1.0)


    @staticmethod
    def spawnWorld(r=1.0,s=1.0,v=1.0,cloudsize=1.0) :
	world = GraphicalWorld(r,s,v,cloudsize)
	channel = Channel(world)
	world.setChannel(channel)
	return(world)
Пример #4
0
class Geography:
    def __init__(self):
        mapFile = 'images/world.tif'
        #self.view = WorldView(controller=self, mapFile=mapFile, mapSize=self.mapSize)
        self.view = WorldView(controller=self)
        self.map = Map(mapFile, screenSize=self.view.screenSize)
        self.view.map = self.map
        self.landmark = None
        self.landmarks = None
        self.score = 0
        self.maximumDistance = 1000
        self.timer = None
        self.worstGuess = None
        self.client = GameClient()
        self.deferred = defer.Deferred()
        self.setRounds()
        self.crops = {'world':(-180.0, 90.0, 180.0, -90.0),
                      'us':(-125, 52, -65, 22),
                      'europe':(-25, 72, 51, 34)
                  }
        
    def setRounds(self):
        self.gameOver = False
        self.rounds = ['africa', 'world capitals', 'world', 'us', 'europe']
        self.roundNumber = 0
        
        
    def start(self):
        self.nextRound("Choose the position of the given city.  If you miss by more than %i km, the round is over" % self.maximumDistance)
        reactor.run()
        
    def quit(self):
        reactor.stop()
    
    
    def mouseEvent(self, event):
        if self.landmarks == None or len(self.landmarks) == 0 or self.landmark == None:
            print 'do nothing'
        elif not self.timeLoop.running:
            self.nextRound("Sorry, you didn't guess in time")
        elif self.timeLoop.running:
            print 'running'
            self.timeLoop.stop()
            answer = (event.x, event.y)
            distance = self.map.getDistance(answer, self.landmark)
            if self.worstGuess is None:
                self.worstGuess = distance
            elif distance > self.worstGuess:
                self.worstGuess = distance
            self.view.deleteLines()
            self.view.drawLines('blue', (event.x, event.y))
            x, y = self.map.mapToScreen(self.landmark['lat'], self.landmark['long'])
            self.view.drawLines('red', (x, y))
            self.view.drawCircle('red', (x, y), 25)
            self.view.answer.set("Distance: %d km" % int(distance))
            if distance > self.maximumDistance:
                self.nextRound("Sorry, you missed by more than %i km" % self.maximumDistance)
            else:
                self.view.nextRound.set('%i questions left' % len(self.landmarks))       
                time = self.time
                # calculate score
                score = self.calculateScore(time, distance)
                self.score += score
                self.view.scoreText.set("Total Score: %i" % int(self.score))
                self.view.showMessage("Score: %i Total: %i" % (int(score),  int(self.score)))
                self.getQuestion()
                              
                
    def nextRound(self, message):
        if len(self.rounds) > 0:
            self.landmarks = None
            round = self.rounds.pop()
            crop = self.crops[round]
            self.map.crop(crop)
            self.view.makeImage()
            self.roundNumber += 1
            message = message + "\n\nRound %i\n%s: The 50 most populus cities" % (self.roundNumber, round.capitalize())
            try:
                self.getLandmarks(round)
            except ConnectionError:
                self.view.showMessage("Sorry, the stupid game server is not running.  Quitting game NOW!")
                self.quit()
            self.view.showMessage(message)
            self.getQuestion()
        else:
            self.gameOver = True
            self.view.showMessage("Game over, now attempting to post your score to the server")
            try:
                self.postScore()
            except ConnectionError:
                self.view.showMessage("Sorry, the stupid game server is not running.  Quitting game NOW!")
                self.quit()
        
    def getQuestion(self):
        if self.landmarks == None:
            pass
            #self.landmarks = self.getLandmarks('world')
            #self.getQuestion()
        elif len(self.landmarks) > 0:
            self.view.deleteLines()
            self.getLandmark()
            self.view.question.set("%s, %s" % (self.landmark['name'], self.landmark['country']))
            self.view.answer.set("")
            self.time = 5
            self.timeLoop = task.LoopingCall(self.updateTime)
            self.timeLoop.start(0.1)
        else:
            self.nextRound("Good job, you got all 50!")
        
    def updateTime(self):
        if self.time <= 0:
            self.timeLoop.stop()
        else:
            self.time -= 0.1
            self.view.updateProgressbar(self.time)
            
    def restart(self):
        """ """
        if self.gameOver:
            self.numQuestions = 20
            self.score = 0
            self.view.deleteLines()
            self.view.answer.set("")
            self.view.scoreText.set('')
            self.view.question.set('')
            self.gameOver = False
            
    def postScore(self):
        name = self.view.nameInput.get()
        if name == '':
            name = 'anonymous'
        data = "%s %i %.1f" % (name, int(self.score), float(self.worstGuess))
        listOfScores = self.client.addScore(data)
        scores = "High Scores: \n"
        scores += listOfScores
        self.view.scoresText.set(scores)
        self.view.showScores(scores)
        
    def getLandmarks(self, difficulty):
        try:
            self.landmarks = self.client.getLandmarks(difficulty)
        except ConnectionError:
            self.view.showMessage("Sorry, the stupid game server is not running.  Quitting game NOW!")
            self.quit()
        return self.deferred
        
        
    def getLandmark(self):
        self.landmark = self.landmarks.pop()
            
    def calculateScore(self, time, distance):
        if distance > 2500:
            return 0.0
        score = 1000 - pow(distance, 1.2)
        timeBonus = 100 * (5 - time)
        if score < 0:
            score = 0
        score = score + timeBonus
        #self.view.updateNextRoundBar(score)
        return score