コード例 #1
0
    def updateDistributions(self, distributions):
        "Draws an agent's belief distributions"
        # copy all distributions so we don't change their state
        distributions = [x.copy() for x in distributions]
        if self.distributionImages is None:
            self.drawDistributions(self.previousState)
        for x in range(len(self.distributionImages)):
            for y in range(len(self.distributionImages[0])):
                image = self.distributionImages[x][y]
                weights = [dist[(x, y)] for dist in distributions]

                if sum(weights) != 0:
                    pass
                # Fog of war
                color = [0.0, 0.0, 0.0]
                colors = GHOST_VEC_COLORS[1:]  # With Pacman
                if self.capture:
                    colors = GHOST_VEC_COLORS
                for weight, gcolor in zip(weights, colors):
                    color = [
                        min(1.0, c + 0.95 * g * weight**0.3)
                        for c, g in zip(color, gcolor)
                    ]
                changeColor(image, formatColor(*color))
        refresh()
コード例 #2
0
 def _getBeliefSquareColor(color, value):
     value = min(1.0, value * 15)
     saturation = value
     hue = Display.COLOR_HUES[color]
     r, g, b = colorsys.hsv_to_rgb(hue, saturation, 1.0)
     color = graphicsUtils.formatColor(r, g, b)
     return color        
コード例 #3
0
    def drawGhost(self, ghost, agentIndex):
        pos = self.getPosition(ghost)
        dir = self.getDirection(ghost)
        (screen_x, screen_y) = (self.to_screen(pos))
        coords = []
        for (x, y) in GHOST_SHAPE:
            coords.append((x * self.gridSize * GHOST_SIZE + screen_x,
                           y * self.gridSize * GHOST_SIZE + screen_y))

        colour = self.getGhostColor(ghost, agentIndex)
        body = gU.polygon(coords, colour, filled=1)
        WHITE = gU.formatColor(1.0, 1.0, 1.0)
        BLACK = gU.formatColor(0.0, 0.0, 0.0)

        dx = 0
        dy = 0
        if dir == 'North':
            dy = -0.2
        if dir == 'South':
            dy = 0.2
        if dir == 'East':
            dx = 0.2
        if dir == 'West':
            dx = -0.2
        leftEye = gU.circle((screen_x + self.gridSize * GHOST_SIZE * (-0.3 + dx / 1.5),
                             screen_y - self.gridSize * GHOST_SIZE * (0.3 - dy / 1.5)),
                            self.gridSize * GHOST_SIZE * 0.2, WHITE, WHITE)
        rightEye = gU.circle((screen_x + self.gridSize * GHOST_SIZE * (0.3 + dx / 1.5),
                              screen_y - self.gridSize * GHOST_SIZE * (0.3 - dy / 1.5)),
                             self.gridSize * GHOST_SIZE * 0.2, WHITE, WHITE)
        leftPupil = gU.circle((screen_x + self.gridSize * GHOST_SIZE * (-0.3 + dx),
                               screen_y - self.gridSize * GHOST_SIZE * (0.3 - dy)),
                              self.gridSize * GHOST_SIZE * 0.08, BLACK, BLACK)
        rightPupil = gU.circle((screen_x + self.gridSize * GHOST_SIZE * (0.3 + dx),
                                screen_y - self.gridSize * GHOST_SIZE * (0.3 - dy)),
                               self.gridSize * GHOST_SIZE * 0.08, BLACK, BLACK)
        ghostImageParts = []
        ghostImageParts.append(body)
        ghostImageParts.append(leftEye)
        ghostImageParts.append(rightEye)
        ghostImageParts.append(leftPupil)
        ghostImageParts.append(rightPupil)

        return ghostImageParts
コード例 #4
0
 def drawExpandedCells(self, cells):
     """
     Draws an overlay of expanded grid positions for search agents
     """
     n = float(len(cells))
     baseColor = [1.0, 0.0, 0.0]
     self.clearExpandedCells()
     self.expandedCells = []
     for k, cell in enumerate(cells):
         screenPos = self.to_screen(cell)
         cellColor = gU.formatColor(*[(n - k) * c * .5 / n + .25
                                      for c in baseColor])
         block = gU.square(screenPos,
                           0.5 * self.gridSize,
                           color=cellColor,
                           filled=1, behind=2)
         self.expandedCells.append(block)
         if self.frameTime < 0:
             gU.refresh()
コード例 #5
0
    def shadeCost(self, layout, constraints, costVector, feasiblePoints, xmin,
                  ymin, xmax, ymax):
        baseColor = [1.0, 0.0, 0.0]

        costs = [self.pointCost(costVector, point) for point in feasiblePoints]
        minCost = min(costs)
        maxCost = max(costs)
        costSpan = maxCost - minCost

        allFeasiblePoints = self.getFeasibleLayoutPoints(
            layout, constraints, xmin, ymin, xmax, ymax)

        # The feasible points themselves may have been gridded to infeasible grid points,
        # but we want to make sure they are shaded too.
        #cornerPoints = [self.cartesianToLayout(xmin, ymin, xmax, ymax, point) for point in feasiblePoints]
        cornerPoints = self.getLayoutPointsWithSymbol(layout, ('o', 'P'))

        gridPointsToShade = cornerPoints + allFeasiblePoints

        for gridPoint in gridPointsToShade:
            point = self.layoutToCartesian(xmin, ymin, xmax, ymax, gridPoint)

            relativeCost = (self.pointCost(costVector, point) -
                            minCost) * 1.0 / costSpan

            # Whoops our grid points are flipped top-bottom from what to_screen expects
            screenPos = self.to_screen(
                (gridPoint[0], len(layout) - gridPoint[1] - 1))

            cellColor = [
                0.25 + 0.5 * relativeCost * channel for channel in baseColor
            ]

            graphicsUtils.square(screenPos,
                                 0.5 * self.gridSize,
                                 color=graphicsUtils.formatColor(*cellColor),
                                 filled=1,
                                 behind=2)

        graphicsUtils.refresh()
        graphicsUtils.sleep(1)
コード例 #6
0
    def updateDistributions(self, distributions):
        "Draws an agent's belief distributions"
        if self.distributionImages is None:
            self.drawDistributions(self.previousState)
        for x in range(len(self.distributionImages)):
            for y in range(len(self.distributionImages[0])):
                image = self.distributionImages[x][y]
                weights = [dist[(x, y)] for dist in distributions]

                if sum(weights) != 0:
                    pass
                # Fog of war
                color = [0.0, 0.0, 0.0]
                colors = GHOST_VEC_COLORS[1:]  # With Pacman
                if self.capture:
                    colors = GHOST_VEC_COLORS
                for weight, gcolor in zip(weights, colors):
                    color = [min(1.0, c + 0.95 * g * weight ** .3)
                             for c, g in zip(color, gcolor)]
                gU.changeColor(image, gU.formatColor(*color))
        gU.refresh()
コード例 #7
0
from graphicsDisplay import PacmanGraphics
from graphicsDisplay import InfoPane
import graphicsDisplay
import graphicsUtils
from game import GameStateData
from game import AgentState
from game import Configuration
from game import Directions
from layout import Layout
from Tkinter import mainloop
import math
import numpy as np
import time
import plotUtil

LINE_COLOR = graphicsUtils.formatColor(0, 1, 0)


def plotPoints(x, y):
    """
    Create a Pacman display, plotting the points (x[i],y[i]) for all i in len(x).
    This method will block control and hand it to the displayed window.

    x: array or list of N scalar values.
    y: array or list of N scalar values.

    >>> x = range(-3,4)
    >>> squared = lambda x : x**2
    >>> y = map(squared, x)
    >>> pacmanPlot.plotPoints(x,y)
   """
コード例 #8
0
import math
from game import Directions
import os

###########################
#  GRAPHICS DISPLAY CODE  #
###########################

# Most code by Dan Klein and John Denero written
# or rewritten for cs188, UC Berkeley.
# Some code from a Pacman implementation by LiveWires,
# and used / modified with permission.

DEFAULT_GRID_SIZE = 30.0
INFO_PANE_HEIGHT = 35
BACKGROUND_COLOR = gU.formatColor(0, 0, 0)
WALL_COLOR = gU.formatColor(0.0 / 255.0, 51.0 / 255.0, 255.0 / 255.0)
INFO_PANE_COLOR = gU.formatColor(.4, .4, 0)
SCORE_COLOR = gU.formatColor(.9, .9, .9)
PACMAN_OUTLINE_WIDTH = 2
PACMAN_CAPTURE_OUTLINE_WIDTH = 4

GHOST_COLORS = []
GHOST_COLORS.append(gU.formatColor(.9, 0, 0))  # Red
GHOST_COLORS.append(gU.formatColor(0, .3, .9))  # Blue
GHOST_COLORS.append(gU.formatColor(.98, .41, .07))  # Orange
GHOST_COLORS.append(gU.formatColor(.1, .75, .7))  # Green
GHOST_COLORS.append(gU.formatColor(1.0, 0.6, 0.0))  # Yellow
GHOST_COLORS.append(gU.formatColor(.4, 0.13, 0.91))  # Purple

TEAM_COLORS = GHOST_COLORS[:2]
コード例 #9
0
ファイル: pacmanPlot.py プロジェクト: Roboball/Pacman
from graphicsDisplay import PacmanGraphics
from graphicsDisplay import InfoPane
import graphicsDisplay
import graphicsUtils
from game import GameStateData
from game import AgentState
from game import Configuration
from game import Directions
from layout import Layout
from Tkinter import mainloop
import math
import numpy as np
import time
import plotUtil

LINE_COLOR = graphicsUtils.formatColor(0, 1, 0)

def plotPoints(x,y):
    """
    Create a Pacman display, plotting the points (x[i],y[i]) for all i in len(x).
    This method will block control and hand it to the displayed window.
           
    x: array or list of N scalar values.
    y: array or list of N scalar values.
    
    >>> x = range(-3,4)
    >>> squared = lambda x : x**2
    >>> y = map(squared, x)
    >>> pacmanPlot.plotPoints(x,y)
   """
    display = PacmanPlot(x,y)
コード例 #10
0
class Display(object):
    
    WHITE = graphicsUtils.formatColor(1.0, 1.0, 1.0)
    RED = graphicsUtils.formatColor(1.0, 0.0, 0.0)
    GREEN = graphicsUtils.formatColor(0.16, 0.49, 0.31)
    BLUE = graphicsUtils.formatColor(0.0, 0.0, 1.0)
    BLACK = graphicsUtils.formatColor(0.0, 0.0, 0.0)
    GREY = graphicsUtils.formatColor(0.5, .5, 0.5)
    
    VISIBLE_CUTTOFF = 0.001
    
    
    partDict = {}
    beliefParts = []
    beliefValue = []
    beliefColor = []
    observations = []
    
    graphicsLock = threading.Lock()
    
    COLORS = [
        'purple',
        'green',
        'teal',
        'red',
        'orange',
        'yellow'
    ]
    COLOR_HUES = {
        'purple' : 0.8,
        'green' : 0.3,
        'teal' : 0.49,
        'red' : 0.0,
        'orange' : 0.125,
        'yellow' : 0.21
    }
    
    @staticmethod
    def initGraphics(layout):
        graphicsUtils.begin_graphics(
            width=layout.getWidth(), 
            height=layout.getHeight(), 
            color = Display.WHITE,
            title = Const.TITLE
        );
        
    @staticmethod
    def endGraphics():
        graphicsUtils.end_graphics()

    @staticmethod
    def raiseEndGraphics():
        graphicsUtils.raiseEndGraphics()
    
    @staticmethod
    def drawCar(car):
        if car in Display.partDict:
            Display._remove(car)
        color = Display.GREY
        if car.isJunior():
            color = Display.BLACK
        parts = graphicsUtils.rectangle(
            car.pos, Car.LENGTH, 
            Car.WIDTH, 
            color, 
            car.dir
        )
        Display.partDict[car] = parts
        
    @staticmethod
    def drawObservation(obs):
        parts = Display.drawCircle(obs.pos, Observation.RADIUS)
        Display.partDict[obs] = parts
    
    @staticmethod
    def drawSquare(pos, size, color):
        return graphicsUtils.square(pos, size, color)
    
    @staticmethod
    def drawFinish(block):
        graphicsUtils.rectangle(
                block.getCenter(), 
                block.getHeight(), 
                block.getWidth(), 
                Display.GREEN, 
                None,
                1.0
            )
    
    @staticmethod
    def drawBlocks(blocks):
        for block in blocks:
            graphicsUtils.rectangle(
                block.getCenter(), 
                block.getHeight(), 
                block.getWidth(), 
                Display.BLUE, 
                None,
                1.0
            )
        
    @staticmethod
    def drawCircle(pos, radius):
        return graphicsUtils.circle(pos, radius, Display.RED, Display.RED)
    
    @staticmethod
    def drawBelief(model):
        Display.beliefVisible = []
        for r in range(model.getBeliefRows()):
            beliefValueRow = []
            beliefPartRow = []
            beliefColorRow = []
            for c in range(model.getBeliefCols()):
                square = Display.drawBeliefSquare(r, c, 'purple', 0.0, model)
                beliefPartRow.append(square)
                beliefValueRow.append(0.0)
                beliefColorRow.append(None)
            Display.beliefParts.append(beliefPartRow)
            Display.beliefValue.append(beliefValueRow)
            Display.beliefColor.append(beliefColorRow)
                
    @staticmethod
    def drawBeliefSquare(row, col, color, value, model):
        tileSize = Const.BELIEF_TILE_SIZE
        x = col * tileSize + tileSize / 2.0
        y = row * tileSize + tileSize / 2.0
        if not model.inBounds(x, y): return None
        color = Display._getBeliefSquareColor(color, value)
        return Display.drawSquare(Vec2d(x, y), tileSize, color)
         
    # make thread safe
    @staticmethod
    def getKeys():
        #print 'attempt get keys'
        Display._acquireLock()
        #print 'get keys'
        keys = graphicsUtils.keys_waiting() + graphicsUtils.keys_pressed()
        Display._releaseLock()
        return keys
    
    # make thread safe
    @staticmethod
    def graphicsSleep(timeToSleep):
        graphicsUtils.sleep(timeToSleep)
        #time.sleep(timeToSleep)
        '''for _ in range(int(timeToSleep / 0.005)):
            #print 'attempt sleep'
            Display._acquireLock()
            #print 'sleep'
            graphicsUtils.sleep(0.001)
            Display._releaseLock()
            time.sleep(0.004)'''
        
        #graphicsUtils.sleep(timeToSleep)
        #time.sleep(timeToSleep)
        '''startWait = time.time()
        Display._acquireLock()
        timeToSleep -= time.time() - startWait
        graphicsUtils.refresh()
        if timeToSleep > 0:
            graphicsUtils.sleep(timeToSleep)
        Display._releaseLock()'''
             
    # make thread safe
    @staticmethod
    def updateBelief(color, belief):
        Display._acquireLock()
        total = belief.getSum()
        if abs(total - 1.0) > 0.001:
            raise Exception('belief does not sum to 1 ('+str(total)+'). Use the normalize method.')
        for r in range(belief.getNumRows()):
            for c in range(belief.getNumCols()):
                value = belief.getProb(r, c)
                Display._updateBeliefSquare(r, c, value, color)
        Display._releaseLock()
    
    # make thread safe
    @staticmethod
    def move(obj, delta):
        #print 'attempt move'
        Display._acquireLock()
        #print 'move'
        parts = Display.partDict[obj]
        #assert(parts)
        graphicsUtils.move_by(parts, delta.x, delta.y)
        #print 'end move'
        Display._releaseLock()
        
    # make thread safe
    @staticmethod
    def rotate(obj, angle):
        if angle == 0: return
        #print 'attempt rotate'
        Display._acquireLock()
        #print 'rotate'
        parts = Display.partDict[obj]
        #assert(parts)
        graphicsUtils.rotate_by(parts, angle)
        Display._releaseLock()
                
    @staticmethod
    def _getBeliefSquareColor(color, value):
        value = min(1.0, value * 15)
        saturation = value
        hue = Display.COLOR_HUES[color]
        r, g, b = colorsys.hsv_to_rgb(hue, saturation, 1.0)
        color = graphicsUtils.formatColor(r, g, b)
        return color        
    
    @staticmethod
    def _isVisible(value):
        return value >= Display.VISIBLE_CUTTOFF
    
    @staticmethod
    def _updateBeliefSquare(r, c, value, colorName):
        part = Display.beliefParts[r][c]
        if part == None: return
        oldValue = Display.beliefValue[r][c]
        oldColor = Display.beliefColor[r][c]
        wasVisible = Display._isVisible(oldValue)
        isVisible = Display._isVisible(value) 
        if not isVisible: value = 0.0
        if oldColor != colorName and oldValue >= value: return
        if not isVisible and not wasVisible: return
        color = Display._getBeliefSquareColor(colorName, value)
        graphicsUtils.changeColor(part, color)
        Display.beliefValue[r][c] = value
        Display.beliefColor[r][c] = colorName
        
    @staticmethod
    def _acquireLock():
        return
        #print 'acquire'
        return Display.graphicsLock.acquire()
    
    @staticmethod
    def _releaseLock():
        return
        #print 'release'
        return Display.graphicsLock.release()
     
    ####################################
    # Depreicated
    ####################################
        
    @staticmethod
    def _remove(obj):
        parts = Display.partDict[obj]
        graphicsUtils.remove_from_screen(parts);
        
    @staticmethod
    def redrawObservations(observations):
        raise Exception('depreicated')
        for obs in Display.observations:
            Display._remove(obs)
        for obs in observations:
            Display.drawObservation(obs)
        Display.observations = observations