Example #1
0
def newSprintPost(handler, p_project, p_name, p_start, p_end, p_members = None, p_private = False, p_hidden = False):
	def die(msg):
		print msg
		done()

	handler.wrappers = False
	p_project = int(p_project)
	if not handler.session['user']:
		die("You must be logged in to create a new sprint")

	project = Project.load(p_project)
	if not project:
		die("Unknown project ID: %d" % p_project)

	if p_name == '':
		die("The sprint name cannot be empty")

	try:
		start = re.match("^(\d{1,2})/(\d{1,2})/(\d{4})$", p_start)
		if not start:
			raise ValueError
		month, day, year = map(int, start.groups())
		start = datetime(year, month, day)
	except ValueError:
		die("Malformed start date: %s" % stripTags(p_start))

	try:
		end = re.match("^(\d{1,2})/(\d{1,2})/(\d{4})$", p_end)
		if not end:
			raise ValueError
		month, day, year = map(int, end.groups())
		end = datetime(year, month, day, 23, 59, 59)
	except ValueError:
		die("Malformed end date: %s" % stripTags(p_end))

	msg = Sprint.validateDates(start, end)
	if msg:
		die(msg)

	members = set(User.load(int(memberid)) for memberid in p_members)
	if None in members:
		die("Unknown username")
	if handler.session['user'] not in members:
		die("The scrummaster (%s) must be a sprint member" % handler.session['user'])

	sprint = Sprint(project.id, p_name, handler.session['user'].id, dateToTs(start), dateToTs(end))
	sprint.members |= members
	if p_private or p_hidden:
		sprint.flags.add('private')
	if p_hidden:
		sprint.flags.add('hidden')
	sprint.save()
	# Make a default 'Miscellaneous' group so there's something to add tasks to
	Group(sprint.id, 'Miscellaneous', 1, False).save()
	# Make the standard set of sprint goals
	Goal.newSet(sprint)

	handler.responseCode = 299
	print "/sprints/%d" % sprint.id
	Event.newSprint(handler, sprint)
Example #2
0
    def __init__(self):
        goal1 = Goal("Eat", 4)
        goal2 = Goal("Sleep", 3)
        self.goals = [goal1, goal2]
        self.action_index = -1

        game_state = self

        # actions
        action1 = Action("Get raw food", [{
            "goal": goal1,
            "insistance_change": -4
        }], -3)
        action2 = Action("Sleep in bed", [{
            "goal": goal2,
            "insistance_change": -2
        }], -3)
        action3 = Action("Get snack", [{
            "goal": goal1,
            "insistance_change": -2
        }], -2)
        self.base_action = Action("No action", [], 0)

        self.actions = [action1, action2, action3]
        self.strength = 5
Example #3
0
    def __init__(self):
        goal1 = Goal("Health", 4)
        goal2 = Goal("Have fun!", 3)
        self.goals = [goal1, goal2]
        self.action_index = -1

        game_state = self

        # actions
        action1 = Action("Go out for dinner", [{
            "goal": goal1,
            "insistance_change": -4
        }], -3)
        action2 = Action("Party!!", [{
            "goal": goal2,
            "insistance_change": -2
        }], -3)
        action3 = Action("Eat at home", [{
            "goal": goal1,
            "insistance_change": -2
        }], -2)
        self.base_action = Action("No action", [], 0)

        self.actions = [action1, action2, action3]
        self.money = 5
Example #4
0
    def add(self,
            idx=-1,
            goalName="",
            envName="",
            newDefinition="",
            newCategory="Maintain",
            newPriority="Low",
            newFitCriterion="None",
            newIssue="None",
            newOriginator=""):
        envName = self.envCombo.GetValue()
        parentGoalName = self.goalCombo.GetValue()

        ep = GoalEnvironmentProperties(
            envName, '', newDefinition, newCategory, newPriority,
            newFitCriterion, newIssue,
            [(parentGoalName, 'goal', 'and', 'No', 'None')])
        g = Goal(-1, goalName, newOriginator, [], [ep])
        gp = GoalParameters(goalName, newOriginator, [], [ep])
        g.setId(self.dbProxy.addGoal(gp))
        if (idx != -1):
            self.goals.insert(idx, g)
        else:
            self.goals.append(g)
        return g
Example #5
0
    def __init__(self):
        pygame.init()

        self.screen = pygame.display.set_mode((self.screen_w, self.screen_h))
        self.fps_clock = pygame.time.Clock()

        # 2D array containing arrays, to store object in the secotrs and optimise collisions
        self.sectors = [[[]
                         for j in range(ceil(self.screen_h / self.sector_size))
                         ]
                        for i in range(ceil(self.screen_w / self.sector_size))]

        # create goals
        screen_margin = (self.screen_h - self.pitch_h) / 2
        self.goal_left = Goal(self, self.pitch_color_1,
                              (self.screen_w - self.pitch_w) / 2,
                              screen_margin + self.pitch_h * 6 / 16,
                              screen_margin + self.pitch_h * 10 / 16, 50, -1)
        self.goal_right = Goal(
            self, self.pitch_color_2,
            self.pitch_w + (self.screen_w - self.pitch_w) / 2,
            screen_margin + self.pitch_h * 6 / 16,
            screen_margin + self.pitch_h * 10 / 16, 50, 0)

        self.team_right = Team(self, self.team1_color, self.goal_right, 1)
        self.team_left = Team(self, self.team2_color, self.goal_left, -1)

        self.start_time = pygame.time.get_ticks()
Example #6
0
	def getTrophies(self) :

		goalsCompleted = []

		if self.error == True :
			return jsonify(error="Run not found")

		# Retrieve all uncompleted user goals
		params = urllib.parse.urlencode({"where":json.dumps({
			"completed" : False,
			"userObjectID" : self.userId
		})})
		try :
			connection.request('GET', '/1/classes/TrophyInformation?%s' % params, '', {
		       "X-Parse-Application-Id": os.environ['RUNMATE_CONST_APPID'],
		       "X-Parse-REST-API-Key": os.environ['RUNMATE_CONST_APIKEY']
		     })
			trophyList = json.loads(connection.getresponse().read().decode('utf-8'))['results']
		except http.client.RemoteDisconnected :
			return self.getTrophies()

		# Filter goals that shouldn't be considered
		for t in trophyList :
			goal = Goal(str(t['objectId']))
			if self.checkTrophy(goal) :
				goalsCompleted.append(goal.setCompleted())
		
		if goalsCompleted == [] :
			return jsonify(error="No goals completed")
		else :
			return jsonify(goals=goalsCompleted)
Example #7
0
    def setElements(self):

        self.goal = Goal((int(self.width / 2), int(self.height * 0.05)))
        self.goal.show(self.background)

        # self.obstacles.append(Obstacle((0, 0, 255), (100, 300, 600, 30)))
        #
        # self.obstacles[0].show(self.background)

        self.population = Population(
            (int(self.width / 2), int(self.height * 0.95)), 1000,
            self.goal.getPosition())
Example #8
0
  def add(self,idx=-1,goalName="",envName="",newDefinition="",newCategory="Maintain", newPriority="Low", newFitCriterion="None", newIssue="None", newOriginator=""):
    envName = self.envCombo.GetValue()
    parentGoalName = self.goalCombo.GetValue()

    ep = GoalEnvironmentProperties(envName,'',newDefinition,newCategory,newPriority,newFitCriterion,newIssue,[(parentGoalName,'goal','and','No','None')])
    g = Goal(-1,goalName,newOriginator,[ep])
    gp = GoalParameters(goalName,newOriginator,[],[ep])
    g.setId(self.dbProxy.addGoal(gp))
    if (idx != -1):
      self.goals.insert(idx,g)
    else:
      self.goals.append(g)
    return g
Example #9
0
    def __init__(self, random_start = True, step_limit = None, ball_idle_limit = None, state_output_mode = 'pixels', rendering = True, frame_skip=4):
        self.action_space = ActionSpace([Action.up, Action.down, Action.forward, Action.backward, Action.nomoveshoot, Action.nomove])
        self.step_limit = step_limit
        self.ball_idle_limit = ball_idle_limit
        self.state_output_mode = state_output_mode
        self.rendering = rendering
        self.ball_idle = 0
        self.step_limit = step_limit
        if state_output_mode == 'pixels': self.rendering = True
        self.step_count = 0
        self.random_start = random_start
        self.frame_skip = frame_skip
    
    
        self.scene =  Scene(c_width, c_height)
        self.scene.add_object(Box(5, c_width - 5, 5, c_height - 5, 0))
        self.scene.add_object(Disc(c_width / 2, c_height / 2, middle_field_radius, 10, 1, 1, Color.white).make_ghost().make_hollow().set_outer_color(Color.border))
        self.scene.add_object(VerticalBorder(c_width / 2, c_height / 2, c_height - 2 * topbottom_margin, None).make_ghost())


        self.scene.add_object(HorizontalBorder(c_width / 2, topbottom_margin, c_width - 2 * leftright_margin, border_restitution).extend_to(Way.up).set_collision_mask([Ball]))
        self.scene.add_object(HorizontalBorder(c_width / 2, c_height - topbottom_margin, c_width - 2 * leftright_margin, border_restitution).extend_to(Way.down).set_collision_mask([Ball]))
        self.scene.add_object(VerticalBorder(leftright_margin, (c_height / 2 - goal_length / 2 + topbottom_margin) / 2, c_height / 2 - topbottom_margin - goal_length / 2, border_restitution).extend_to(Way.left).set_collision_mask([Ball]))
        self.scene.add_object(VerticalBorder(leftright_margin, c_height - (c_height / 2 - goal_length / 2 + topbottom_margin) / 2, c_height / 2 - topbottom_margin - goal_length / 2, border_restitution).extend_to(Way.left).set_collision_mask([Ball]))
        self.scene.add_object(VerticalBorder(c_width - leftright_margin, (c_height / 2 - goal_length / 2 + topbottom_margin) / 2, c_height / 2 - topbottom_margin - goal_length / 2, border_restitution).extend_to(Way.right).set_collision_mask([Ball]))
        self.scene.add_object(VerticalBorder(c_width - leftright_margin, c_height - (c_height / 2 - goal_length / 2 + topbottom_margin) / 2, c_height / 2 - topbottom_margin - goal_length / 2, border_restitution).extend_to(Way.right).set_collision_mask([Ball]))
        
       
        self.goal1 = Goal(leftright_margin, c_height / 2, Way.left, goal_length)
        self.goal2 = Goal(c_width - leftright_margin, c_height / 2, Way.right, goal_length)
        
        self.player1 = Player(120, c_height / 2, player_radius, player_mass, \
                                     player_restitution, player_damping, player_kick_damping, player_kick_power, Side.red)
       
        self.player2 = Player(c_width - 120, c_height / 2, player_radius, player_mass, \
                                     player_restitution, player_damping, player_kick_damping, player_kick_power, Side.blue)
       
        self.ball = Ball(c_width / 2, c_height / 2, ball_radius, ball_mass, ball_restitution, ball_damping)
        
        self.scene.add_object(self.goal1)
        self.scene.add_object(self.goal2)
        self.scene.add_object(self.player1)
        self.scene.add_object(self.player2)
        self.scene.add_object(self.ball)
        
        
        self.sequence1 = StateSequence([84, 84, 4])
        self.sequence2 = StateSequence([84, 84, 4])
Example #10
0
def retrieve(name, todayMonth):
    rList = []
    r_file = open('file/addgoals.txt', 'r')
    for rlist in r_file:
        list = rlist.split(',')
        savedate = list[6]
        savedateStr = savedate.split('-')
        dd = int(savedateStr[0])
        mm = int(savedateStr[1])
        yy = int(savedateStr[2])
        print(mm)

        if list[0] == name and mm == todayMonth:
            goal = float(list[4])

            saveTotal = retrieveHistory(list[0], list[5])
            howmuchMore = goal - saveTotal
            howmuchMore = '%.2f' % howmuchMore

            monthly = 0.05 / 12
            convert = monthly / 100
            interest = saveTotal * convert
            i = '%.2f' % interest

            a = '%.2f' % goal

            s = Goal(list[0], list[1], list[2], list[3], a, list[5], list[6],
                     list[7], howmuchMore, i, list[8], list[9], list[10])
            rList.append(s)
    return rList
Example #11
0
    def __init__(self, width, height):
        Level.__init__(self, width, height)
        ##initialize blocks##
        boxtop = Terrain(20, -19, 40, 2, 0, 0, 100, self, 0.5)
        boxleft = Terrain(-1, -5, 2, 30, 0, 0, 100, self, 0.5)
        boxbottom = Terrain(20, 9, 40, 2, 0, 0, 100, self, 0.5)
        boxright = Terrain(41, -5, 2, 30, 0, 0, 100, self, 0.5)
        barrbottom = Terrain(15, -6, 6, 1, 0, 0, 100, self, .5)
        barrright = Terrain(18.5, -11, 1, 10, 0, 0, 100, self, .5)

        goal = Goal(38, -15.5, 1, 5, 0, 0, 100, self, 0.5)

        tramp1 = Trampoline(7, 7, 6, 1, 0, 0, 100, self, .5)
        tramp2 = Trampoline(36, 7, 6, 1, 0, 0, 100, self, .5)
        tramp3 = Trampoline(32, -8, 6, 1, 0, 0, 100, self, .5)
        tramp4 = Trampoline(36, -23, 6, 1, 0, 0, 100, self, .5)
        p = Player(2, 5, 1, 2, 0, 0, 1, self, 0.5)
        g = GoalBlock(16.5, -7, 2, 2, 0, 0, 2, self, 0.5)
        self.add_elem(p)
        self.add_elem(barrbottom)
        self.add_elem(barrright)
        self.add_elem(tramp1)
        self.add_elem(tramp2)
        self.add_elem(tramp3)
        self.add_elem(tramp4)
        self.add_elem(g)
        self.add_elem(boxtop)
        self.add_elem(boxright)
        self.add_elem(boxbottom)
        self.add_elem(boxleft)
        self.add_elem(goal)
Example #12
0
 def put_goal(self, command):
     #PutGoal <lowercase_goal_name_without_spaces> <lowercase_description_without_spaces>
     elements = command.split()
     name = elements[1].lower()
     description = "dummy_description"
     goal = Goal.build_new_goal(name, description)
     self.life.put_goal(goal)
Example #13
0
    def __init__(self):
        if self.isMember():
            filePath = "./user/profile.txt"
            f = open(filePath, "r")
            s = f.readlines()
        
            self.name = s[0].split('\n')[0]
            self.gender = s[1].split('\n')[0]
            self.birth = s[2].split('\n')[0]
            self.currentDate = s[3].split('\n')[0]
            self.height = s[4].split('\n')[0]
            self.weight = s[5].split('\n')[0]
            self.goal = Goal(self)
            self.workOut = WorkOut(self.gender)
            self.activity = Activity()

            f.close()
        else:
            self.name = None
            self.gender = None
            self.birth = None
            self.currentDate = None
            self.height = None
            self.weight = None
            self.goal = None
            self.workOut = None
            self.activity = None
Example #14
0
    def __init__(self, width, height):
        Level.__init__(self, width, height)
        ##initialize blocks##
        boxtop = Terrain(20, -19, 40, 2, 0, 0,100, self, 0.5)
        boxleft= Terrain(-1,-5,2,30,0,0,100,self,0.5)
        boxbottom= Terrain(27.0,9.0,54.0,2.0,0.0,0.0,100,self,0.5)
        boxright= Terrain(55,-5,2,30,0,0,100,self,0.5)

        goal= Goal(53,5,1,5,0,0,100,self,0.5)
        
        
        b =   Block(2, 2,  4, 1, 0, 0,  1, self, 0.5)
        c =  Player(7, 5,  1, 2, 0, 0,  1, self, 0.5)
        d =   Block(4, 2, 4, 1, 0, 5,  2, self, 0.5)  
        a =   GoalBlock(4, 5, 2, 2, 0, 5,  2, self, 0.5) 
        m = Trampoline(30, -4, 2, 1, 0, 0, 1, self, 0.5)
        e = Spike(30.0, 7.5, 41.0, 1.0, 0.0, 0.0, 100, self, 0.1)
        f = Spike(29.0, 6.5, 1.0, 1.0, 0.0, 0.0, 100, self, 0.1)
        self.add_elem(c)
        self.add_elem(m)
        self.add_elem(b)
        self.add_elem(a)
        self.add_elem(d)
        self.add_elem(e)
        self.add_elem(f)
        self.add_elem(boxtop)
        self.add_elem(boxright)
        self.add_elem(boxbottom)
        self.add_elem(boxleft)
        self.add_elem(goal)
Example #15
0
    def __init__(self, frame_skip = 2):
        
        height = 400
        width = 600
        goal_length = 300
        self.scene =  Scene(width, height)
        self.frame_skip = frame_skip
        self.ball_idle = 0
        self.ball_idle_limit = 3

        self.action_space = ActionSpace([Action.up, Action.down, Action.nomoveshoot])
       
        self.box = Box(0, width, 0, height, 0)
        self.goal1 = Goal(leftright_margin, height / 2, Way.left, goal_length)

        self.player1 = Player(80, height / 2, player_radius, player_mass, \
                                     player_restitution, player_damping, player_kick_damping, player_kick_power, Side.red)
       
       
        self.ball = Ball(width - 100, height / 2, ball_radius, ball_mass, ball_restitution, ball_damping)
        self.penalty_spot = Disc(self.ball.center.x, self.ball.center.y, 4, 0, 0, 0, Color.green).make_ghost().make_hollow()
#        self.player_border_left = VerticalBorder(50, height / 2, height, 0, visible=True)
#        self.player_border_right = VerticalBorder(100, height / 2, height, 0, visible=True)
        
        self.scene.add_object(self.goal1)
        self.scene.add_object(self.player1)
        self.scene.add_object(self.ball)
        self.scene.add_object(self.penalty_spot)
        self.scene.add_object(self.box)
        self.reset()
Example #16
0
def taskEditPost(handler, ids, p_hours, p_status, p_goal, p_assigned=[], p_include={}):
    handler.title("Edit tasks")
    requirePriv(handler, "Write")

    allIDs = map(int, uniq(ids.split(",")))
    ids = map(lambda i: to_int(i, "include", ErrorBox.die), p_include.keys())
    if not set(ids) <= set(allIDs):
        ErrorBox.die("Included tasks don't match query arguments")

    tasks = dict((id, Task.load(id)) for id in ids)
    if not all(tasks.values()):
        ids = [str(id) for (id, task) in tasks.iteritems() if not task]
        ErrorBox.die(
            "No %s with %s %s"
            % ("task" if len(ids) == 1 else "tasks", "ID" if len(ids) == 1 else "IDs", ", ".join(ids))
        )
    tasks = [tasks[id] for id in ids]
    if len(set(task.sprint for task in tasks)) > 1:
        ErrorBox.die("All tasks must be in the same sprint")
    sprint = (tasks[0] if len(tasks) > 0 else Task.load(allIDs[0])).sprint
    if sprint.isHidden(handler.session["user"]):
        ErrorBox.die(
            "No %s with %s %s"
            % ("task" if len(ids) == 1 else "tasks", "ID" if len(ids) == 1 else "IDs", ", ".join(ids))
        )
    if not sprint.canEdit(handler.session["user"]):
        ErrorBox.die("You don't have permission to modify this sprint")

    assignedids = set(to_int(i, "assigned", ErrorBox.die) for i in p_assigned)

    changes = {
        "assigned": False if assignedids == set() else {User.load(assignedid) for assignedid in assignedids},
        "hours": False if p_hours == "" else int(p_hours),
        "status": False if p_status == "" else p_status,
        "goal": False if p_goal == "" else Goal.load(int(p_goal)),
    }

    if changes["assigned"] and not all(changes["assigned"]):
        ErrorBox.die("Invalid assignee")
    if changes["assigned"] and not set(changes["assigned"]).issubset(sprint.members):
        ErrorBox.die("Unable to assign tasks to non-sprint members")
    if changes["goal"] and changes["goal"].sprint != sprint:
        ErrorBox.die("Unable to set goal to a goal outside the sprint")

    changed = set()
    for task in tasks:
        for field, value in changes.iteritems():
            if value is not False and getattr(task, field) != value:
                setattr(task, field, value)
                changed.add(task)
                Event.taskUpdate(handler, task, field, value)

    if len(changed) == 0:
        delay(handler, WarningBox("No changes necessary", close=3, fixed=True))
    else:
        for task in changed:
            task.saveRevision(handler.session["user"])
        delay(handler, SuccessBox("Updated %d %s" % (len(changed), "task" if len(changed) == 1 else "tasks")))
    redirect("/sprints/%d" % sprint.id)
 def addGoal(self, _model, _goalInformation, _startDate, _dueDate):
     goalList = _model.getGoalList()  #retrieves goalList from the model
     gid = _model.getNewGID()  #retreieves a new goal id from the model
     goal = Goal(gid, _goalInformation, _startDate,
                 _dueDate)  #create new Goal object using _goalInformation
     goalList.append(goal)  #append new Goal to goalList
     _model.setGoalList(goalList)  #sets the updated goallist in the model
     return _model  #returns the model
Example #18
0
def newTaskPost(handler, p_group, p_name, p_goal, p_status, p_hours, p_assigned=[]):
    def die(msg):
        print msg
        done()

    requirePriv(handler, "User")
    handler.wrappers = False

    groupid = to_int(p_group, "group", die)
    group = Group.load(groupid)
    if not group or group.sprint.isHidden(handler.session["user"]):
        die("No group with ID <b>%d</b>" % groupid)

    sprint = group.sprint
    if not (sprint.isActive() or sprint.isPlanning()):
        die("Unable to modify inactive sprint")
    elif not sprint.canEdit(handler.session["user"]):
        die("You don't have permission to modify this sprint")

    if p_name.strip() == "":
        die("Task must have a non-empty name")

    assignedids = set(to_int(i, "assigned", die) for i in p_assigned)
    assigned = set(User.load(assignedid) for assignedid in assignedids)
    if assigned == set():
        assigned.add(handler.session["user"] if handler.session["user"] in sprint.members else sprint.owner)
    if not all(assigned):
        die("Invalid assignee")

    goalid = to_int(p_goal, "goal", die)
    if goalid != 0:
        goal = Goal.load(goalid)
        if not goal:
            die("No goal with ID <b>%d</b>" % goalid)
        if goal.sprint != group.sprint:
            die("Goal does not belong to the correct sprint")

    hours = to_int(p_hours, "hours", die)

    task = Task(groupid, group.sprintid, handler.session["user"].id, goalid, p_name, p_status, hours)
    task.assigned |= assigned
    task.save()

    handler.responseCode = 299
    delay(
        handler,
        """
<script type=\"text/javascript\">
$(document).ready(function() {
	$('#task%d').effect('highlight', {}, 3000);
});
</script>"""
        % task.id,
    )
    delay(handler, SuccessBox("Added task <b>%s</b>" % task.safe.name, close=3, fixed=True))
    Event.newTask(handler, task)
Example #19
0
def processUser(userid):
    usersList = []
    user_file = open('file/addgoals.txt', 'r')
    for ulist in user_file:
        list = ulist.split(',')
        if list[0] == userid:
            s = Goal(list[0], list[1], list[2], list[3], int(list[4]), list[5],
                     list[6], list[7], list[8], list[9], list[10])
            usersList.append(s)
    return usersList
Example #20
0
def countUser(userid):
    countList = []
    user_file = open('file/addgoals.txt', 'r')
    for ulist in user_file:
        list = ulist.split(',')
        today = datetime.datetime.now().date()
        if list[0] == userid and list[8] == 'A':
            s = Goal(list[0], list[1], list[2], list[3], int(list[4]), list[5],
                     list[6], list[7], list[8], list[9], list[10])
            countList.append(s)
    return countList
Example #21
0
    def addGoal(self):
        '''
        @param: None

        @return: None

        @purpose: Creates a Goal object and then appends it to the goalList
        '''
        newGID = self.getNewGID()  #gets a new id
        self.goalList.append(
            Goal(newGID))  #appends a new goal with the new id to the goallist
        return newGID  #returns the new gid
Example #22
0
 def add_Racers(self, players, positions):
     '''
         Takes in players; a dictionary of the players.
         positions, a list of integer postions for the 
         turtle's track lines
     '''
     self.racers = [
     ]  # Keeps track of the turtles that are created to be racers
     with open('src/score.txt', 'w') as edit:  # Creates the stats sheet
         i = 0  # Match the positions with the players
         for player in players.keys():
             new_turtle = Turtle(player, players[player])
             new_turtle.setpos(positions[i], 30)
             new_turtle.write(new_turtle.name,
                              font=("Verdana", 8, "bold"),
                              align='center',
                              move=False)
             new_turtle.showturtle()
             new_goal = Goal()
             new_goal.color(new_turtle.col)
             new_goal.setpos(positions[i], self.s.window_height() - 50)
             self.racers.append(new_turtle)  # Append the new racer
             self.player_scores[player] = 0
             # Write the turtle's name in the stats sheet
             edit.write(player + ' 0 \n')
             i += 1  # Increment the index for the position
Example #23
0
    def __init__(self, width, height):
        Level.__init__(self, width, height)
        ##initialize blocks##
        boxtop = Terrain(20, -19, 40, 2, 0, 0, 100, self, 0.5)
        boxleft = Terrain(-1, -5, 2, 30, 0, 0, 100, self, 0.5)
        boxbottom = Terrain(20, 9, 40, 2, 0, 0, 100, self, 0.5)
        boxright = Terrain(41, -5, 2, 30, 0, 0, 100, self, 0.5)

        goal = Goal(38, 5, 1, 5, 0, 0, 100, self, 0.5)

        b10 = Block(1, 7, 2, 2, 0, 0, 1, self, 0.5)
        b20 = Block(3, 7, 2, 2, 0, 0, 1, self, 0.5)
        b30 = Block(5, 7, 2, 2, 0, 0, 1, self, 0.5)
        b40 = Block(7, 7, 2, 2, 0, 0, 1, self, 0.5)
        b50 = Block(9, 7, 2, 2, 0, 0, 1, self, 0.5)
        b11 = Block(1, 5, 2, 2, 0, 0, 1, self, 0.5)
        b21 = Block(3, 5, 2, 2, 0, 0, 1, self, 0.5)
        b31 = Block(5, 5, 2, 2, 0, 0, 1, self, 0.5)
        b41 = Block(7, 5, 2, 2, 0, 0, 1, self, 0.5)
        b51 = Block(9, 5, 2, 2, 0, 0, 1, self, 0.5)
        b12 = Block(1, 3, 2, 2, 0, 0, 1, self, 0.5)
        b22 = Block(3, 3, 2, 2, 0, 0, 1, self, 0.5)
        b32 = Block(5, 3, 2, 2, 0, 0, 1, self, 0.5)
        b42 = Block(7, 3, 2, 2, 0, 0, 1, self, 0.5)
        b52 = Block(9, 3, 2, 2, 0, 0, 1, self, 0.5)
        p = Player(15, 5, 1, 2, 0, 0, 1, self, 0.5)
        g = GoalBlock(17, 5, 2, 2, 0, 0, 2, self, 0.5)
        barrier = Terrain(35, -3, 1, 22, 0, 0, 100, self, 0.5)
        self.add_elem(p)
        self.add_elem(b10)
        self.add_elem(b20)
        self.add_elem(b30)
        self.add_elem(b40)
        self.add_elem(b50)
        self.add_elem(b11)
        self.add_elem(b21)
        self.add_elem(b31)
        self.add_elem(b41)
        self.add_elem(b51)
        self.add_elem(b12)
        self.add_elem(b22)
        self.add_elem(b32)
        self.add_elem(b42)
        self.add_elem(b52)
        self.add_elem(barrier)
        self.add_elem(g)
        self.add_elem(boxtop)
        self.add_elem(boxright)
        self.add_elem(boxbottom)
        self.add_elem(boxleft)
        self.add_elem(goal)
Example #24
0
    def __init__(self, numPlayers, mapInstance):
        self.endGame = False
        self.num = 0
        self.numPlayers = numPlayers
        self.turnList = list(range(1, numPlayers + 1))
        random.shuffle(self.turnList)
        self.numTerritories = mapInstance.numTerritories
        self.players = []

        for k in range(0, numPlayers):
            self.players.append(Player(k + 1, mapInstance, self))

        # assigns player goals
        self.goal = Goal(mapInstance, self)
        for k in range(0, numPlayers):
            self.players[k].obj = Objective(self.goal, self.players[k])
        self.id_turnList = 0
        self.map = mapInstance
        self.list_phase = ["Placement", "Attack", "Movement"]
        self.phase = 0
        self._player_ = self.turnList[self.id_turnList]
Example #25
0
    def __init__(self,
                 inpParam=None,
                 outParam=None,
                 functionToCall=None,
                 feasibleVal=0.0,
                 tolerance=1.0E-6,
                 maxLoops=40,
                 failValue=None):
        '''Initialize parameter properties
           
           @param inpParam: input parameter object (InputParam)
           @param outParam: output parameter object (OutputParam)
           @param functionToCall: function using InputParam to calc OutputParam (callable)
           @param feasibleVal: feasible value that OutputParam Must have (float)
           @param tolerance: allowable error of OutputParam.val (float)
           @param maxLoops: maximum loops in root solver
           @param failValue: returned value if solution attempt fails, 
              (if not input use inpParam.minVal)
        '''
        self.inpParam = inpParam  #: InputParam object
        self.outParam = outParam  #: OutputParam object
        self.functionToCall = functionToCall  #: function using InputParam to calc OutputParam
        self.feasibleVal = floatDammit(
            feasibleVal)  #: feasable value of OutputParam.val
        self.tolerance = floatDammit(
            tolerance)  #: allowable error of OutputParam.val
        self.maxLoops = intDammit(maxLoops)  #: maximum loops in root solver

        if failValue == None:
            failValue = inpParam.minVal
        self.failValue = failValue  #: returned value if solution attempt fails

        self.G = Goal(goalVal=feasibleVal,
                      minX=inpParam.minVal,
                      maxX=inpParam.maxVal,
                      funcOfX=self.feasibleFunc,
                      tolerance=tolerance,
                      maxLoops=maxLoops,
                      failValue=failValue)
Example #26
0
def assignGroupGoalPost(handler, id, p_goal):
	def die(msg):
		print msg
		done()

	handler.title('Manage Group')
	requirePriv(handler, 'User')
	handler.wrappers = False

	id = int(id)
	group = Group.load(id)
	if not group:
		ErrorBox.die('Invalid Group', "No group with ID <b>%d</b>" % id)

	if p_goal == '0':
		goal = None
	else:
		goal = Goal.load(int(p_goal))
		if not goal:
			ErrorBox.die('Invalid Goal', "No goal with ID <b>%d</b>" % int(p_goal))
		elif not goal.sprint == group.sprint:
			ErrorBox.die('Invalid Goal', "Selected goal is not part of the correct sprint")

	for task in group.getTasks():
		if task.goal != goal:
			task.goal = goal

			if task.creator == handler.session['user'] and (dateToTs(getNow()) - task.timestamp) < 5*60:
				task.save()
			else:
				task.saveRevision(handler.session['user'])

			#TODO Event
			# NO

	redirect("/sprints/%d#group%d" % (group.sprintid, group.id))
Example #27
0
# load a path file
#p = Path("Path-around-table.json")
p = Path("Path-around-table-and-back.json")
#p = Path("Path-from-bed.json")
#p = Path("Path-to-bed.json")
path = p.getPath()

print("Path length = " + str(len(path)))
print("First point = " + str(path[0]['X']) + ", " + str(path[0]['Y']))

# make a robot to move around
robot = Robot()
converter = AngleConverter()
pathHandler = PathHandler()
navigator = Navigator()
goal = Goal()

#### Intialize variables
position = robot.getPosition()
speed = 0.25
heading = 0
nextPoint = 0
dropOut = 0
lookAheadDistance = 0.85

while (goal.notGoal(position, nextPoint, path)):

    ### get current status (position, heading)
    position = robot.getPosition()
    heading = converter.convertToDegree(robot.getHeading())
Example #28
0
 def __init__(self, gameInfo):
     """Méthode pour initialiser le but"""
     Goal.__init__(self, gameInfo)
     self.goalString = "KillAnyone"
Example #29
0
def sprintPost(handler, sprintid, p_id, p_rev_id, p_field, p_value):
	def die(msg):
		print msg
		done()

	handler.wrappers = False
	sprintid = to_int(sprintid, 'sprintid', die)
	p_id = to_int(p_id, 'id', die)
	p_rev_id = to_int(p_rev_id, 'rev_id', die)

	if not handler.session['user']:
		die("You must be logged in to modify tasks")

	sprint = Sprint.load(sprintid)
	if not sprint or sprint.isHidden(handler.session['user']):
		die("There is no sprint with ID %d" % sprintid)
	elif not (sprint.isActive() or sprint.isPlanning()):
		die("Unable to modify inactive sprint")
	elif not sprint.canEdit(handler.session['user']):
		die("You don't have permission to modify this sprint")

	# Special case group moves; p_id is the group ID, not task
	task = None
	if p_field != 'groupmove':
		task = Task.load(p_id)
		if not task:
			die("Task %d does not exist" % p_id)
		if task.sprint != sprint:
			die("Attempting to modify task outside the specified sprint")
		if task.revision != p_rev_id: #TODO Implement collision support
			die("Collision with %s detected. Changes not saved" % task.creator)

	if p_value.strip() == '':
		die("Value cannot be empty")

	if p_field in ['status', 'name', 'goal', 'assigned', 'hours', 'deleted']:
		for case in switch(p_field):
			if case('status') or case('name'):
				parsedValue = p_value
				break
			elif case('goal'):
				parsedValue = None
				if p_value != '0':
					parsedValue = Goal.load(to_int(p_value, 'goal', die))
					if not parsedValue:
						die("Unknown goal: <b>%s</b>" % stripTags(p_value))
					if parsedValue.sprint != sprint:
						die("Attempting to use goal outside the specified sprint")
				break
			elif case('assigned'):
				parsedValue = set(User.load(username = username) for username in p_value.split(' '))
				if not all(parsedValue):
					die("Unknown user(s): <b>%s</b>" % stripTags(p_value))
				break
			elif case('hours'):
				parsedValue = int(p_value)
				break
			elif case('deleted'):
				parsedValue = True if p_value == 'true' else False if p_value == 'false' else die("Bad value for field 'deleted'")
				break

		if task.__getattribute__(p_field) != parsedValue: # Only save if the field has changed
			task.__setattr__(p_field, parsedValue)

			# Is this within the 5-minute window, by the same user?
			# If we're in pre-planning, the task's timestamp will be in the future, so (ts - task.timestamp) will be negative, which satisfies the check
			if task.creator == handler.session['user'] and (dateToTs(getNow()) - task.timestamp) < 5*60:
				task.save()
			else:
				task.saveRevision(handler.session['user'])

			Event.taskUpdate(handler, task, p_field, parsedValue)

	elif p_field == 'taskmove':
		if ':' not in p_value:
			die("Malformed value")
		newGroupID, newSeq = map(lambda i: to_int(i, 'value', die), p_value.split(':', 1))
		newGroup = Group.load(newGroupID)
		if not newGroup:
			die("No group with ID %d" % newGroupID)
		maxSeq = len(Task.loadAll(groupid = newGroup.id))
		if task.group != newGroup:
			maxSeq += 1
		if not 1 <= newSeq <= maxSeq:
			die("Bad sequence number")

		task.move(newSeq, newGroup)

	elif p_field == 'groupmove':
		group = Group.load(p_id)
		if not group:
			die("Group %d does not exist" % p_id)
		if group.sprint != sprint:
			die("Attempting to modify group outside the specified sprint")

		newSeq = to_int(p_value, 'value', die)
		if not 1 <= newSeq <= len(sprint.getGroups()):
			die("Bad sequence number")

		group.move(newSeq)

	else:
		die("Unexpected field name: %s" % stripTags(p_field))

	handler.responseCode = 299
	if task is not None:
		print task.revision
Example #30
0
def sprintInfoPost(handler, id, p_name, p_start, p_end, p_goals, p_members = None, p_clear = [], p_private = False, p_hidden = False):
	def die(msg):
		print msg
		done()

	handler.wrappers = False

	if not handler.session['user']:
		die("You must be logged in to modify sprint info")

	id = to_int(id, 'id', die)
	p_members = to_int(p_members, 'members', die)
	sprint = Sprint.load(id)
	if not sprint or sprint.isHidden(handler.session['user']):
		die("There is no sprint with ID %d" % id)
	if sprint.owner != handler.session['user']:
		die("You must be the scrummaster to modify sprint information")

	try:
		start = re.match("^(\d{1,2})/(\d{1,2})/(\d{4})$", p_start)
		if not start:
			raise ValueError
		month, day, year = map(int, start.groups())
		start = datetime(year, month, day, 0, 0, 0)
	except ValueError:
		die("Malformed start date: %s" % stripTags(p_start))

	try:
		end = re.match("^(\d{1,2})/(\d{1,2})/(\d{4})$", p_end)
		if not end:
			raise ValueError
		month, day, year = map(int, end.groups())
		end = datetime(year, month, day, 23, 59, 59)
	except ValueError:
		die("Malformed end date: %s" % stripTags(p_end))

	msg = Sprint.validateDates(start, end, tsToDate(sprint.start), tsToDate(sprint.end))
	if msg:
		die(msg)

	goals = map(Goal.load, to_int(p_goals.keys(), 'goals', die))
	if not all(goals):
		die("One or more goals do not exist")

	members = set(map(User.load, p_members)) if p_members else set()
	if not all(members):
		die("One or more members do not exist")
	if sprint.owner not in members:
		die("The scrummaster (%s) must be a sprint member" % sprint.owner)

	tasks = sprint.getTasks()
	changedTasks = set()
	avail = Availability(sprint)
	addMembers = set(members) - set(sprint.members)
	delMembers = set(sprint.members) - set(members)
	for user in delMembers:
		for task in filter(lambda task: user in task.assigned, tasks):
			print "Removing %s from %d<br>" % (user, task.id)
			task.assigned -= {user}
			if len(task.assigned) == 0:
				print "Adding %s to %d<br>" % (sprint.owner, task.id)
				task.assigned = {sprint.owner}
			changedTasks.add(task)
		avail.delete(user)
		sprint.members -= {user}

	# For event dispatching
	changes = OrderedDict([
		('name', None if sprint.name == p_name else p_name),
		('start', None if tsToDate(sprint.start) == start else start),
		('end', None if tsToDate(sprint.end) == end else end),
		('addMembers', addMembers),
		('delMembers', delMembers),

		# Updated later
		('addGoals', []),
		('removeGoals', []),
		('addFlags', []),
		('removeFlags', []),
	])

	sprint.members |= addMembers
	sprint.name = p_name
	p_private = (p_private or p_hidden) # Hidden implies Private
	for flagName, flagValue in (('private', p_private), ('hidden', p_hidden)):
		if flagValue and flagName not in sprint.flags:
			sprint.flags.add(flagName)
			changes['addFlags'].append(flagName)
		elif not flagValue and flagName in sprint.flags:
			sprint.flags.remove(flagName)
			changes['removeFlags'].append(flagName)

	if dateToTs(start) != sprint.start or dateToTs(end) != sprint.end:
		sprint.start = dateToTs(start)
		sprint.end = dateToTs(end)
		avail.trim()

	sprint.save()

	for id in p_goals:
		goal = Goal.load(int(id))
		if goal.name != p_goals[id]:
			if goal.name:
				changes['removeGoals'].append(goal.name)
			if p_goals[id]:
				changes['addGoals'].append(p_goals[id])

		goal.name = p_goals[id]
		goal.save()

	if start:
		for task in sprint.getTasks(includeDeleted = True):
			for rev in task.getRevisions():
				if rev.timestamp < sprint.start:
					rev.timestamp = sprint.start
					rev.save()
				else:
					break
		for task in changedTasks:
			if task.timestamp < sprint.start:
				task.timestamp = sprint.start

	if p_clear:
		ids = [to_int(goalid, 'p_clear', die) for goalid in p_clear]
		for task in tasks:
			if task.goal and task.goal.id in ids:
				task.goal = None
				changedTasks.add(task)

	for task in changedTasks:
		print "Saving new revision for %d<br>" % task.id
		task.saveRevision(handler.session['user'])

	handler.responseCode = 299
	delay(handler, SuccessBox("Updated info", close = 3, fixed = True))
	Event.sprintInfoUpdate(handler, sprint, changes)
 def __init__(self, gameInfo):
     """Méthode pour initialiser le but"""
     Goal.__init__(self, gameInfo)
     self.goalString = "KillSpecificDefender"
Example #32
0
from Goal import Goal
from Action import Action
from GameState import GameState

working = True

if working:
    goal1 = Goal("Get a high distinction", 1)
    goal2 = Goal("Have fun!",5)
    goal3 = Goal("Sleep",0)
    goals = [goal1,goal2,goal3]
    game_state = GameState(goals)

    #actions
    action1 = Action("Study...",game_state,[
        {"goal":goal1,"insistance_change": -2},
        {"goal":goal2,"insistance_change": 1},
        {"goal":goal3,"insistance_change": 3},
    ])
    action2 = Action("Party!!",game_state,[
        {"goal":goal2,"insistance_change": -3},
        {"goal":goal3,"insistance_change": 3},
    ])
    action3 = Action("Go to bed",game_state,[
        {"goal":goal3,"insistance_change": -7},
    ])

    actions = [action1, action2, action3]
else:
    goal1 = Goal("Get a high distinction", 10)
    goal2 = Goal("Sleep", 3)
Example #33
0

#Check mainly if isComplete properly returns false for y
def test_SubGoal_isComplete():
    assert x.isComplete()
    assert not (y.isComplete())


#Check if the string representations are correct
def test_SubGoal_toString():
    assert "Name: test | Status: Complete" == x.toString()
    assert "Name: test | Status: Incomplete" == y.toString()


#Test Goals
a = Goal(1)
b = Goal(2)
c = Goal(3)


#Update all the goals and assert information from the dictionaries
def test_update():
    a.update(agoalInformation)
    b.update(bgoalInformation)
    c.update(cgoalInformation)
    assert a.name == agoalInformation["name"]
    assert b.category == bgoalInformation["category"]
    assert c.priority == cgoalInformation["priority"]
    assert a.memo == agoalInformation["memo"]
    assert a.initialDueDate == agoalInformation["dueDate"]
    c.update(bgoalInformation)
Example #34
0
 def __init__(self, gameInfo):
     """Methode pour initialiser le but"""
     Goal.__init__(self, gameInfo)
     self.goalString = "BringBackEnemyFlag"
Example #35
0
    def prepare_new_goal(self):
        new_goal_refinements = [
            [
                "PreventUnauthorised Certificate Access",
                "goal",
                "or",
                "No",
                "None"
            ]
        ]
        new_subgoal_refinements = [
            [
                "PreventUnauthorised Certificate Access",
                "goal",
                "or",
                "No",
                "None"
            ]
        ]
        new_goal_props = [
            GoalEnvironmentProperties(
                environmentName=self.existing_environment_name_1,
                lbl='Test 1',
                definition='This is a first test property',
                category=self.existing_category,
                priority='Medium',
                fitCriterion='None',
                issue='None',
                goalRefinements=new_goal_refinements,
                subGoalRefinements=new_subgoal_refinements,
                concs=[],cas=[]
            ),
            GoalEnvironmentProperties(
                environmentName=self.existing_environment_name_2,
                lbl='Test 2',
                definition='This is a second test property',
                category=self.existing_category,
                priority='Low',
                fitCriterion='None',
                issue='Test issue',
                goalRefinements=new_goal_refinements,
                subGoalRefinements=new_subgoal_refinements,
                concs=[],cas=[]
            )
        ]

        new_goal = Goal(
            goalId=-1,
            goalName='Test goal',
            goalOrig='',
            tags=['test', 'test123'],
            environmentProperties=[]
        )
        new_goal.theEnvironmentProperties = new_goal_props

        new_goal.theEnvironmentDictionary = {}
        new_goal.theGoalPropertyDictionary = {}

        delattr(new_goal, 'theEnvironmentDictionary')
        delattr(new_goal, 'theGoalPropertyDictionary')

        return new_goal
Example #36
0
def deserialize_goal(dict):
    goal = Goal(dict['theId'], dict['theName'], dict['theOriginator'],
                dict['theTags'], dict['theEnvironmentProperties'])
    return goal
# Create an object to help track time
clock = pygame.time.Clock()

# Objects
board = Board(50, 50, 16, 32, 0, STANDARD_COLOR)

# Player sprite
player = Player(board)
player.rect.x = 25
player.rect.y = 25

# Sprite list
sprite_list = pygame.sprite.Group()

# Fruits sprite
fruit_list = []
for i in range(80):
    grape = Grape(board, player)
    fruit_list.append(grape)
    sprite_list.add(grape)

# Goal
for i in range(10):
    goal = Goal(board, player)
    fruit_list.append(goal)
    sprite_list.add(goal)
player_movement = 3

sprite_list.add(player)
Example #38
0
	def getGoals(self):
		from Goal import Goal
		return Goal.loadAll(sprintid = self.id)
Example #39
0
class GameEngine(object):
    # object containing Game's data

    screen_w = 1100
    screen_h = int(screen_w / 1.57)

    pitch_w = int(screen_w * 0.8)
    pitch_h = int(pitch_w / 1.57)

    back_color = (164, 143, 91)
    pitch_color_1 = (113, 152, 63)
    pitch_color_2 = (134, 185, 80)

    border_width = 2
    border_color = (174, 202, 137)

    sector_size = 50

    fps = 60
    bots_timer = 0
    test_mode = False
    wall_bounce = 1.0

    goal_delay = 2000  # in miliseconds
    start_delay = 2000  # in miliseconds
    delay_counter = 0
    play_mode = 1
    # play_mode flags states:
    # play_mode = 0 => game running
    # play_mode = -2 => game freezed, players and ball not set on the right positions, waiting time not initialized (set after goal score)
    # play_mode = -1 => game freezed, players and ball not set on the right positions, waiting time initialized (set after goal score and -2 state)
    # play_mode = 1 => game freezed, players and ball set on the right positions, waiting time not initialized (set at the beginning of the game and after -1 state (after goal score cooldown))
    # play_mode = 2 => game freezed, players and ball set on the right positions, waiting time initialized (set after 1 state; after time counter drops to 0, game starts)

    balls = []  # list containing balls
    players = []  # list containing players

    team1_color = (0, 0, 255)
    team2_color = (255, 0, 0)

    def __init__(self):
        pygame.init()

        self.screen = pygame.display.set_mode((self.screen_w, self.screen_h))
        self.fps_clock = pygame.time.Clock()

        # 2D array containing arrays, to store object in the secotrs and optimise collisions
        self.sectors = [[[]
                         for j in range(ceil(self.screen_h / self.sector_size))
                         ]
                        for i in range(ceil(self.screen_w / self.sector_size))]

        # create goals
        screen_margin = (self.screen_h - self.pitch_h) / 2
        self.goal_left = Goal(self, self.pitch_color_1,
                              (self.screen_w - self.pitch_w) / 2,
                              screen_margin + self.pitch_h * 6 / 16,
                              screen_margin + self.pitch_h * 10 / 16, 50, -1)
        self.goal_right = Goal(
            self, self.pitch_color_2,
            self.pitch_w + (self.screen_w - self.pitch_w) / 2,
            screen_margin + self.pitch_h * 6 / 16,
            screen_margin + self.pitch_h * 10 / 16, 50, 0)

        self.team_right = Team(self, self.team1_color, self.goal_right, 1)
        self.team_left = Team(self, self.team2_color, self.goal_left, -1)

        self.start_time = pygame.time.get_ticks()

    def reset(self):
        pygame.quit()

        if self.team_left.score > self.team_right.score:
            print('Team red won!')
        elif self.team_left.score < self.team_right.score:
            print('Team blue won!')
        else:
            print('It is a tie!')

        del self.sectors[:]

        del self.goal_left
        del self.goal_right

        del self.team_right
        del self.team_left

        del self.balls[:]
        del self.players[:]

    def draw_background(self):
        # draw backgroud
        self.screen.fill(self.back_color)

        # draw score
        font = pygame.font.Font(pygame.font.get_default_font(), 30)
        score_left = font.render(str(self.team_left.score), True,
                                 self.team_left.color)
        score_right = font.render(str(self.team_right.score), True,
                                  self.team_right.color)

        self.screen.blit(score_left, ((self.screen_w - self.pitch_w) / 4,
                                      (self.screen_h - self.pitch_h) / 4))
        self.screen.blit(score_right, (self.pitch_w +
                                       (self.screen_w - self.pitch_w) * 3 / 4,
                                       (self.screen_h - self.pitch_h) / 4))

        # draw status message
        if self.play_mode == -1:
            status_message = font.render('GOAL!', True, (0, 0, 0))
            status_message_rect = status_message.get_rect(
                center=(self.screen_w / 2, (self.screen_h - self.pitch_h) / 4))
            self.screen.blit(status_message, status_message_rect)
        elif self.play_mode == 2 and self.delay_counter < 500:
            status_message = font.render('PLAY!', True, (0, 0, 0))
            status_message_rect = status_message.get_rect(
                center=(self.screen_w / 2, (self.screen_h - self.pitch_h) / 4))
            self.screen.blit(status_message, status_message_rect)

        # measure time
        time = pygame.time.get_ticks() - self.start_time

        # draw time
        time_message = font.render(
            str(datetime.timedelta(seconds=int(time / 1000)))[-5:], True,
            (0, 0, 0))
        time_message_rect = time_message.get_rect(
            center=(self.screen_w / 2,
                    self.pitch_h + (self.screen_h - self.pitch_h) * 3 / 4))
        self.screen.blit(time_message, time_message_rect)

        # draw pitch border
        pygame.draw.rect(self.screen, self.border_color, \
            ((self.screen_w - self.pitch_w) / 2 - self.border_width, \
            (self.screen_h - self.pitch_h) / 2 - self.border_width, \
            self.pitch_w + self.border_width * 2 - 1, \
            self.pitch_h + self.border_width * 2 - 1), \
            self.border_width)

        # draw pitch stripes
        for i in range(0, 10):
            if i % 2:
                pygame.draw.rect(self.screen, self.pitch_color_1, \
                   ((self.screen_w - self.pitch_w) / 2 + i * self.pitch_w / 10, \
                   (self.screen_h - self.pitch_h) / 2, self.pitch_w / 10, \
                   self.pitch_h))
            else:
                pygame.draw.rect(self.screen, self.pitch_color_2, \
                    ((self.screen_w - self.pitch_w) / 2 + i * self.pitch_w / 10, \
                    (self.screen_h - self.pitch_h) / 2, self.pitch_w / 10, \
                    self.pitch_h))

        ### draw pitch lines

        # middle line
        pygame.draw.rect(self.screen, self.border_color, \
            ((self.screen_w / 2) - self.border_width + 1, \
            (self.screen_h - self.pitch_h) / 2, \
            self.border_width * 2, self.pitch_h))

        # circle
        pygame.gfxdraw.aacircle(self.screen, \
           int(self.screen_w / 2), \
           int(self.screen_h / 2), \
           int(self.pitch_w / 8), self.border_color)

        pygame.gfxdraw.aacircle(self.screen, \
           int(self.screen_w / 2), \
           int(self.screen_h / 2), \
           int(self.pitch_w / 8 - 1), self.border_color)

        pygame.gfxdraw.aacircle(self.screen, \
           int(self.screen_w / 2), \
           int(self.screen_h / 2), \
           int(self.pitch_w / 8 - 2), self.border_color)

        # dot
        pygame.gfxdraw.filled_circle(self.screen, \
           int(self.screen_w / 2), \
           int(self.screen_h / 2), \
           self.border_width * 3, self.border_color)

        # draw goals and borders

        pygame.draw.rect(
            self.screen, self.border_color,
            (self.goal_left.get_px() - self.border_width,
             self.goal_left.get_py() - self.border_width,
             self.goal_left.get_width() + self.border_width - 1,
             self.goal_left.get_height() + self.border_width * 2 - 1),
            self.border_width)
        pygame.draw.rect(
            self.screen, self.goal_left.color,
            (self.goal_left.get_px(), self.goal_left.get_py(),
             self.goal_left.get_width(), self.goal_left.get_height()))

        pygame.draw.rect(
            self.screen, self.border_color,
            (self.goal_right.get_px(),
             self.goal_right.get_py() - self.border_width,
             self.goal_right.get_width() + self.border_width - 1,
             self.goal_right.get_height() + self.border_width * 2 - 1),
            self.border_width)
        pygame.draw.rect(
            self.screen, self.goal_right.color,
            (self.goal_right.get_px(), self.goal_right.get_py(),
             self.goal_right.get_width(), self.goal_right.get_height()))

        # draw posts
        pygame.gfxdraw.filled_circle(self.screen,
                                     int(self.goal_left.post_up.p.x),
                                     int(self.goal_left.post_up.p.y),
                                     self.goal_left.post_up.size,
                                     self.goal_left.post_up.color)
        pygame.gfxdraw.aacircle(self.screen, int(self.goal_left.post_up.p.x),
                                int(self.goal_left.post_up.p.y),
                                self.goal_left.post_up.size,
                                self.goal_left.post_up.color)
        pygame.gfxdraw.filled_circle(self.screen,
                                     int(self.goal_left.post_down.p.x),
                                     int(self.goal_left.post_down.p.y),
                                     self.goal_left.post_down.size,
                                     self.goal_left.post_down.color)
        pygame.gfxdraw.aacircle(self.screen, int(self.goal_left.post_down.p.x),
                                int(self.goal_left.post_down.p.y),
                                self.goal_left.post_down.size,
                                self.goal_left.post_down.color)

        pygame.gfxdraw.filled_circle(self.screen,
                                     int(self.goal_right.post_up.p.x),
                                     int(self.goal_right.post_up.p.y),
                                     self.goal_right.post_up.size,
                                     self.goal_right.post_up.color)
        pygame.gfxdraw.aacircle(self.screen, int(self.goal_right.post_up.p.x),
                                int(self.goal_right.post_up.p.y),
                                self.goal_right.post_up.size,
                                self.goal_right.post_up.color)
        pygame.gfxdraw.filled_circle(self.screen,
                                     int(self.goal_right.post_down.p.x),
                                     int(self.goal_right.post_down.p.y),
                                     self.goal_right.post_down.size,
                                     self.goal_right.post_down.color)
        pygame.gfxdraw.aacircle(self.screen,
                                int(self.goal_right.post_down.p.x),
                                int(self.goal_right.post_down.p.y),
                                self.goal_right.post_down.size,
                                self.goal_right.post_down.color)

    def draw_graphics(self):
        #ball
        for obj in self.balls:
            self.screen.blit(
                obj.ballImage,
                pygame.rect.Rect(obj.p.x - obj.size, obj.p.y - obj.size,
                                 obj.size, obj.size))
        # goal left
        self.screen.blit(
            self.goal_left.goal,
            pygame.rect.Rect(self.goal_left.get_px(),
                             self.goal_left.get_py() - 3,
                             self.goal_left.get_width(),
                             self.goal_left.get_height()))
        #goal right
        self.screen.blit(
            self.goal_right.goal,
            pygame.rect.Rect(self.goal_right.get_px(),
                             self.goal_right.get_py() - 3,
                             self.goal_right.get_width(),
                             self.goal_right.get_height()))

    def clock_tick(self):
        return self.fps_clock.tick(self.fps)

    def new_player(self, player, team_number=None):
        # add new player to the game and team
        self.players.append(player)

        if team_number == None:
            if self.team_left.size() >= self.team_right.size():
                self.team_right.add_player(player)
            else:
                self.team_left.add_player(player)
        else:
            if team_number == 1:
                self.team_left.add_player(player)
            elif team_number == 2:
                self.team_right.add_player(player)
            else:
                print('ERROR: Wrong team number!')

    def new_ball(self, ball):
        self.balls.append(ball)

    def redraw(self):

        # control game states
        self.game_state_manager()

        # dt is time since last tick
        dt = self.clock_tick()

        self.bots_timer += dt

        if self.delay_counter != 0:
            self.delay_counter -= dt
        if self.delay_counter < 0:
            self.delay_counter = 0

        if self.play_mode == 0:
            # update objects positions and redraw players
            self.update()

        # redraw whole board
        self.display_redraw()

        # update the screen
        pygame.display.update()

    def update(self):
        # update object's positions
        for obj in self.players:
            obj.update()
        for obj in self.balls:
            obj.update()

    def display_redraw(self):
        # redraw board and players

        # draw static background
        self.draw_background()

        ### if test mode is on, draw additional markers on screen
        if self.test_mode:

            # draw sectors around ball and players
            for obj in self.players:
                sector_num = int(obj.size * 4 / self.sector_size)
                for i in range(
                        int(obj.p.x / self.sector_size) - sector_num,
                        int(obj.p.x / self.sector_size) + sector_num + 1):
                    for j in range(
                            int(obj.p.y / self.sector_size) - sector_num,
                            int(obj.p.y / self.sector_size) + sector_num + 1):
                        pygame.draw.rect(
                            self.screen, (0, 255 - ((i + j) % 2) * 50, 0),
                            (i * self.sector_size, j * self.sector_size,
                             int(self.sector_size), int(self.sector_size)))
            for obj in self.balls:
                sector_num = int(obj.size * 4 / self.sector_size)
                for i in range(
                        int(obj.p.x / self.sector_size) - sector_num,
                        int(obj.p.x / self.sector_size) + sector_num + 1):
                    for j in range(
                            int(obj.p.y / self.sector_size) - sector_num,
                            int(obj.p.y / self.sector_size) + sector_num + 1):
                        pygame.draw.rect(
                            self.screen, (0, 255 - ((i + j) % 2) * 50, 0),
                            (int(obj.p.x / self.sector_size) *
                             self.sector_size,
                             int(obj.p.y / self.sector_size) *
                             self.sector_size, int(
                                 self.sector_size), int(self.sector_size)))

            # draw hitboxes
            for obj in self.players:
                pygame.gfxdraw.aacircle(self.screen, int(obj.p.x),
                                        int(obj.p.y), obj.hitbox, (0, 0, 255))
            for obj in self.balls:
                pygame.gfxdraw.aacircle(self.screen, int(obj.p.x),
                                        int(obj.p.y), obj.hitbox, (0, 0, 255))

        # check collisions and redraw all players
        for obj in self.players:
            Collision.collide(obj)
            pygame.gfxdraw.filled_circle(self.screen, int(obj.p.x),
                                         int(obj.p.y), obj.size, obj.color)
            pygame.gfxdraw.aacircle(self.screen, int(obj.p.x), int(obj.p.y),
                                    obj.size, obj.border_color)
            pygame.gfxdraw.aacircle(self.screen, int(obj.p.x), int(obj.p.y),
                                    obj.size - 1, obj.border_color)

        # check collisions with posts
        self.goal_left.goal_collide()
        self.goal_right.goal_collide()

        # draw graphics on top of the screen
        self.draw_graphics()

    # fix objects position, to prevent walls collisions
    def walls_collision(self, obj):
        Collision.walls_collision(obj, self)

    # set game state to -2
    # add point to team which scored
    def goal_scored(self, goal):
        if goal == self.goal_left:
            self.team_right.add_point()
        else:
            self.team_left.add_point()

        self.play_mode = -2

    def game_state_manager(self):
        if self.play_mode == -2:
            # after goal score, prepare delay
            self.play_mode = -1
            self.delay_counter = self.goal_delay
        elif self.play_mode == -1 and self.delay_counter == 0:
            # if delay passed, reset positions and set mode to 1
            self.play_mode = 1
        elif self.play_mode == 1:
            # if game started (or is after goal), prepare delay
            self.positions_reset()
            self.team_left.reset_positions()
            self.team_right.reset_positions()

            self.play_mode = 2
            self.delay_counter = self.start_delay
        elif self.play_mode == 2 and self.delay_counter == 0:
            # if delay passed, start the game
            self.play_mode = 0

    def positions_reset(self):
        for obj in self.balls:
            obj.set_move((0, 0), (self.screen_w / 2, self.screen_h / 2))

    def deserialize(self, data):
        data = self.balls[0].deserialize(data)
        data = self.team_left.deserialize(data)
        data = self.team_right.deserialize(data)
Example #40
0
def main():
    # try to parse the program
    # if I fail, give up and die
    try:
        program = parse(open(argv[1], 'r').read())
        query = argv[2]
    except (LexException, ParseException) as e:
        print(e)
        return

    # Print out the program
    print("Program:")
    for (p, clauses) in program.items():
        for clause in clauses:
            if len(clause) == 0:
                print(p + ".")
            else:
                print(p + " :- " + ", ".join(clause) + ".")
    print("\n")
    goalStack = [Goal(query)]

    while len(goalStack) != 0:

        print("GS = " + ",".join([str(g) for g in goalStack]) + ".")

        # get the current goal
        goal = goalStack.pop(0)

        # If the goal is a choice, then our goal stack looks like
        # ?<[a,b], [c,d]>, e ...
        # We want to remove the first option
        # and put that on the goal stack
        # so It should look like
        # a,b, ?<[c,d]>, e ...
        #
        # If the choice becomes empty, we discard it
        # ?<[a,b]>, d, e ..
        # becomes
        # a, b, d, e ..
        # instead of
        # a, b, ?<>, d, e ..
        if goal.choice():
            firstChoice = goal.first()
            if not goal.empty():
                goalStack.insert(0, goal)
            for g in reversed(firstChoice):
                goalStack.insert(0, Goal(g))

        else:
            # if the current goal isn't a choice, then
            # 1. look it up in the program
            # 2. if the rule isn't a parallel rule,
            #    Add all goals to the goal stack
            # example:
            # GS = p,x,y
            # p :- a,b,c
            # then
            # GS = a,b,c,x,y
            # 3. if the rule parallel rule,
            #    Then add a new choice to the goal stack
            # GS = p,x,y
            # p :- a,b,c
            # p :- d,e,f
            # then
            # GS = ?<[a,b,c], [d,e,f]>, x, y
            if goal.var() in program:
                newGoals = deepcopy(program[goal.var()])
                if len(newGoals) == 1:
                    for g in reversed(newGoals[0]):
                        goalStack.insert(0, Goal(g))
                else:
                    goalStack.insert(0, choice(newGoals))

            # the current goal isn't in the program
            # That means it's a failure, so backtrack to the last choice.
            #
            # example:
            # GS = d,e,f ?<[a,b,c]>, x, y
            # d not defined
            # GS = ?<[a,b,c]>, x, y
            else:
                print("BACKTRACKING " + goal.var(), end=" ")
                while not goalStack[0].choice():
                    print(goalStack.pop(0), end=" ")
                print()
Example #41
0
def build(objtId, p):
    if (p.__class__.__name__ == 'AttackerParameters'):
        return Attacker(objtId, p.name(), p.description(), p.image(), p.tags(),
                        p.environmentProperties())
    if (p.__class__.__name__ == 'PersonaParameters'):
        return Persona(objtId, p.name(), p.activities(), p.attitudes(),
                       p.aptitudes(), p.motivations(),
                       p.skills(), p.intrinsic(), p.contextual(), p.image(),
                       p.assumption(), p.type(), p.tags(),
                       p.environmentProperties(), p.codes())
    if (p.__class__.__name__ == 'AssetParameters'):
        return Asset(objtId, p.name(), p.shortCode(), p.description(),
                     p.significance(), p.type(), p.critical(),
                     p.criticalRationale(), p.tags(), p.interfaces(),
                     p.environmentProperties())
    if (p.__class__.__name__ == 'TemplateAssetParameters'):
        return TemplateAsset(objtId, p.name(), p.shortCode(), p.description(),
                             p.significance(), p.type(), p.surfaceType(),
                             p.accessRight(), p.properties(), p.rationale(),
                             p.tags(), p.interfaces())
    if (p.__class__.__name__ == 'TemplateRequirementParameters'):
        return TemplateRequirement(objtId, p.name(), p.asset(), p.type(),
                                   p.description(), p.rationale(),
                                   p.fitCriterion())
    if (p.__class__.__name__ == 'TemplateGoalParameters'):
        return TemplateGoal(objtId, p.name(), p.definition(), p.rationale(),
                            p.concerns(), p.responsibilities())
    if (p.__class__.__name__ == 'SecurityPatternParameters'):
        return SecurityPattern(objtId, p.name(), p.context(), p.problem(),
                               p.solution(), p.requirements(),
                               p.associations())
    if (p.__class__.__name__ == 'ComponentParameters'):
        return Component(objtId, p.name(), p.description(), p.interfaces(),
                         p.structure(), p.requirements(), p.goals(),
                         p.associations())
    if (p.__class__.__name__ == 'ComponentViewParameters'):
        return ComponentView(objtId, p.name(), p.synopsis(), p.components(),
                             p.connectors(), p.attackSurfaceMetric())
    if (p.__class__.__name__ == 'ValueTypeParameters'):
        return ValueType(objtId, p.name(), p.description(), p.type(),
                         p.score(), p.rationale())
    if (p.__class__.__name__ == 'ClassAssociationParameters'):
        return ClassAssociation(objtId, p.environment(), p.headAsset(),
                                p.headDimension(), p.headNavigation(),
                                p.headType(), p.headMultiplicity(),
                                p.headRole(), p.tailRole(),
                                p.tailMultiplicity(), p.tailType(),
                                p.tailNavigation(), p.tailDimension(),
                                p.tailAsset(), p.rationale())
    if (p.__class__.__name__ == 'GoalAssociationParameters'):
        return GoalAssociation(objtId, p.environment(), p.goal(),
                               p.goalDimension(), p.type(), p.subGoal(),
                               p.subGoalDimension(), p.alternative(),
                               p.rationale())
    if (p.__class__.__name__ == 'DependencyParameters'):
        return Dependency(objtId, p.environment(), p.depender(), p.dependee(),
                          p.dependencyType(), p.dependency(), p.rationale())
    if (p.__class__.__name__ == 'GoalParameters'):
        return Goal(objtId, p.name(), p.originator(), p.tags(),
                    p.environmentProperties())
    if (p.__class__.__name__ == 'ObstacleParameters'):
        return Obstacle(objtId, p.name(), p.originator(), p.tags(),
                        p.environmentProperties())
    if (p.__class__.__name__ == 'DomainPropertyParameters'):
        return DomainProperty(objtId, p.name(), p.description(), p.type(),
                              p.originator(), p.tags())
    if (p.__class__.__name__ == 'ThreatParameters'):
        return Threat(objtId, p.name(), p.type(), p.method(), p.tags(),
                      p.environmentProperties())
    if (p.__class__.__name__ == 'VulnerabilityParameters'):
        return Vulnerability(objtId, p.name(), p.description(), p.type(),
                             p.tags(), p.environmentProperties())
    if (p.__class__.__name__ == 'RiskParameters'):
        return Risk(objtId, p.name(), p.threat(), p.vulnerability(), p.tags(),
                    p.misuseCase())
    if (p.__class__.__name__ == 'ResponseParameters'):
        return Response(objtId, p.name(), p.risk(), p.tags(),
                        p.environmentProperties(), p.responseType())
    if (p.__class__.__name__ == 'CountermeasureParameters'):
        return Countermeasure(objtId, p.name(), p.description(), p.type(),
                              p.tags(), p.environmentProperties())
    if (p.__class__.__name__ == 'TaskParameters'):
        return Task(objtId, p.name(), p.shortCode(), p.objective(),
                    p.assumption(), p.author(), p.tags(),
                    p.environmentProperties())
    if (p.__class__.__name__ == 'UseCaseParameters'):
        return UseCase(objtId, p.name(), p.author(), p.code(), p.actors(),
                       p.description(), p.tags(), p.environmentProperties())
    if (p.__class__.__name__ == 'MisuseCaseParameters'):
        return MisuseCase(objtId, p.name(), p.environmentProperties(),
                          p.risk())
    if (p.__class__.__name__ == 'DotTraceParameters'):
        return DotTrace(p.fromObject(), p.fromName(), p.toObject(), p.toName())
    if (p.__class__.__name__ == 'EnvironmentParameters'):
        return Environment(objtId, p.name(), p.shortCode(), p.description(),
                           p.environments(), p.duplicateProperty(),
                           p.overridingEnvironment(), p.tensions())
    if (p.__class__.__name__ == 'RoleParameters'):
        return Role(objtId, p.name(), p.type(), p.shortCode(), p.description(),
                    p.environmentProperties())
    if (p.__class__.__name__ == 'ResponsibilityParameters'):
        return Responsibility(objtId, p.name())
    if (p.__class__.__name__ == 'ExternalDocumentParameters'):
        return ExternalDocument(objtId, p.name(), p.version(), p.date(),
                                p.authors(), p.description())
    if (p.__class__.__name__ == 'InternalDocumentParameters'):
        return InternalDocument(objtId, p.name(), p.description(), p.content(),
                                p.codes(), p.memos())
    if (p.__class__.__name__ == 'CodeParameters'):
        return Code(objtId, p.name(), p.type(), p.description(),
                    p.inclusionCriteria(), p.example())
    if (p.__class__.__name__ == 'MemoParameters'):
        return Memo(objtId, p.name(), p.description())
    if (p.__class__.__name__ == 'DocumentReferenceParameters'):
        return DocumentReference(objtId, p.name(), p.document(),
                                 p.contributor(), p.description())
    if (p.__class__.__name__ == 'ConceptReferenceParameters'):
        return ConceptReference(objtId, p.name(), p.dimension(),
                                p.objectName(), p.description())
    if (p.__class__.__name__ == 'PersonaCharacteristicParameters'):
        return PersonaCharacteristic(objtId, p.persona(), p.qualifier(),
                                     p.behaviouralVariable(),
                                     p.characteristic(), p.grounds(),
                                     p.warrant(), p.backing(), p.rebuttal())
    if (p.__class__.__name__ == 'TaskCharacteristicParameters'):
        return TaskCharacteristic(objtId, p.task(), p.qualifier(),
                                  p.characteristic(), p.grounds(), p.warrant(),
                                  p.backing(), p.rebuttal())
    if (p.__class__.__name__ == 'ImpliedProcessParameters'):
        return ImpliedProcess(objtId, p.name(), p.description(), p.persona(),
                              p.network(), p.specification(), p.channels())
    if (p.__class__.__name__ == 'LocationsParameters'):
        return Locations(objtId, p.name(), p.diagram(), p.locations(),
                         p.links())
    else:
        raise UnknownParameterClass(str(objtId))
Example #42
0
    for i in range(its):
        if mdl_name == 'kinematic_point':
            player = KinematicPoint(vel_start, pos_start, dt, v_max, win)
        elif mdl_name == "dynamic_point":
            player = DynamicPoint(vel_start, pos_start, dt, v_max, a_max, win)
        elif mdl_name == "differential_drive":
            player = DifferentialDrive(vel_start, pos_start, v_max, omega_max,
                                       dt, win)
        elif mdl_name == "kinematic_car":
            player = KinematicCar(vel_start, pos_start, v_max, vehicle_length,
                                  phi_max, dt, win)
        else:
            print('Invalid model name, exiting')
            sys.exit(0)

        goal = Goal(vel_goal, pos_goal, win)
        env = Environment(obstacles,
                          bounding_poly,
                          player,
                          goal,
                          win,
                          quick_draw=True)
        rrt_setup = {
            'delta_q': delta_q,
            'k': k,
            'strategy': rrt_strat,
            'x_range': [-2, 60],
            'y_range': [-2, 60]
        }
        rrt_time, time = env.run(rrt_setup)
        times.append(time)
Example #43
0
 def __init__(self, gameInfo):
     """Methode pour initialiser le but"""
     Goal.__init__(self, gameInfo)
     self.goalString = "ProtectFlag"
     self.defaultValue = 30
    # Area setup for visualisation
    canvas_width = 800
    canvas_height = 800
    win = GraphWin("area", canvas_width, canvas_height)

    # Setup Initial Conditions
    players = []
    goals = []
    if mdl_name == 'kinematic_point':
        for pos in pos_start:
            players.append(KinematicPoint(pos, dt, v_max, win))
    else:
        print('Invalid model name, exiting')
        sys.exit(0)
    for pos in pos_goal:
        goals.append(Goal(pos, win))

    # Generate paths and run environment
    env = Environment(obstacles,
                      bounding_poly,
                      players,
                      goals,
                      win,
                      quick_draw=True)
    rrt_setup = {
        'delta_q': delta_q,
        'k': k,
        'strategy': rrt_strat,
        'x_range': [-2, 60],
        'y_range': [-2, 60]
    }
Example #45
0
 def __init__(self, gameInfo):
     """Methode pour initialiser le but"""
     Goal.__init__(self, gameInfo)
     self.goalString = "KillFlagCarrier"
     self.defaultValue = 70