Exemplo n.º 1
0
def createBadGuys(amount, level, type):
    '''Create a list of bad guys'''
#    badguylist = []
    mngr = EventManager()
    group = Group(mngr, "Gangsters", (0, 0), "img/player.png")
    group.populateClones(Character(mngr, 'Bad Guy', (0, 0), "", None, None), amount)
    return group
Exemplo n.º 2
0
def OnGroupMsgs(message):
    ''' 监听群组消息'''

    tmp1 = message
    tmp2 = tmp1['CurrentPacket']
    tmp3 = tmp2['Data']
    a = GMess(tmp3)
    '''
    a.FrQQ 消息来源
    a.QQGName 来源QQ群昵称
    a.FromQQG 来源QQ群
    a.FromNickName 来源QQ昵称
    a.Content 消息内容
    a.MsgSeq 消息ID
    '''
    if 'GroupPic' in str(a.Content):
        Group.Group(msg=a.Content, QQ=a.FromQQID, GroupID=a.FromQQG)
    else:
        Jiance = Text.Check(msg=a.Content)
        if Jiance['Data']['DetailResult'] == None:
            Group.Group(msg=a.Content, QQ=a.FromQQID, GroupID=a.FromQQG)
        else:
            Group.Block(Jiance['Data']['DetailResult'][0]['EvilLabel'],
                        GroupID=a.FromQQG,
                        MsgSeq=a.MsgSeq,
                        MsgRandom=a.MsgRandom,
                        QQ=a.FromQQID)

    te = re.search(r'\#(.*)', str(a.Content))
    if te == None:
        return
Exemplo n.º 3
0
def build(install_config):
    if install_config != None:
        cleanup = Cleanup()
        session = Database.create_sqlalchemy_session_push(cleanup)
        
        Group.add(session, "owner", "Owner")
        GroupPermission.set(session, "owner", "admin", 99999999, True)

        User.add_user_account(session, install_config.OWNER_USERNAME, install_config.OWNER_PASSWORD)
        UserGroup.join(session, install_config.OWNER_USERNAME, "owner")
        session.commit()
Exemplo n.º 4
0
 def __init__(self, handtiles, ting_tile, iszimo, melds=[]):
     assert len(handtiles) + len(melds) * 3 == 14
     self.funList = [dandiao, wuzi, queyimen, erwubajiang, pengfeng, laoshaofu, yibangao, siguiyi, minggang, angang,
                     bianzhang, kanzhang, lianliu, xixiangfeng, pinghu, self.buqiuren, self.menqing, self.zimo]
     self.handtiles = handtiles
     self.ting_tile = ting_tile
     self.iszimo = iszimo
     self.melds = melds
     self.fan = 0
     self.group = Group(handtiles, melds)
     self.group.judge()
Exemplo n.º 5
0
    def create(self):

        self.setTitle("Space Rocks")
        self.fpsDisplay = True

        space = Sprite()
        space.setTexture(Texture.load("assets/space-rocks/space.png"))
        space.setPosition(400, 300)
        self.group.addEntity(space)

        self.spaceship = Sprite()
        self.spaceship.setTexture(
            Texture.load("assets/space-rocks/spaceship.png"))
        self.spaceship.setPosition(100, 300)
        # physics values
        self.spaceship.setPhysics(100, 200, 10)
        self.spaceship.addAction(ActionFactory.wrapToScreen(800, 600))
        self.group.addEntity(self.spaceship)

        rockTexture = Texture.load("assets/space-rocks/rock.png")
        self.rockGroup = Group()
        self.group.addEntity(self.rockGroup)

        for n in range(6):
            rock = Sprite()
            x = random() * 400 + 300
            y = random() * 600
            rock.setPosition(x, y)
            rock.setTexture(rockTexture)
            rock.setPhysics(0, 80, 0)
            rock.physics.setSpeed(80)
            angle = random() * 360
            rock.angle = angle
            rock.physics.setMotionAngle(angle)
            rock.addAction(ActionFactory.wrapToScreen(800, 600))
            self.rockGroup.addEntity(rock)

        self.laserTexture = Texture.load("assets/space-rocks/laser.png")
        self.laserGroup = Group()
        self.group.addEntity(self.laserGroup)

        self.explosionAnimation = Animation.load(
            "assets/space-rocks/explosion.png", 6, 6, 0.03, False)

        self.messageWin = Sprite()
        self.messageWin.setTexture(
            Texture.load("assets/space-rocks/message-win.png"))
        self.messageWin.setPosition(400, 300)
        self.messageWin.opacity = 0
        self.messageWin.visible = False
        self.group.addEntity(self.messageWin)
Exemplo n.º 6
0
def fetchQuestions(series):
    mongo_client = MongoClient('localhost', 27017)

    DB = mongo_client[Constants.DBNAME]
    QuestionCollection = DB[series + "__" + Constants.QUESTION_SUFFIX]

    res_list = list(QuestionCollection.find({}))
    groups = Group.fetchGroups(series)

    questions = []
    for gr in range(len(groups)):
        questions.append([])
        nb_questions = groups[gr]["group_nb_questions"]
        for q in range(nb_questions):
            questions[gr].append({})

    for item in res_list:
        _id = item["_id"]
        q = int(_id[3:])
        gr = int(_id[1])
        for key, value in item.items():
            if gr < len(groups) and q < groups[gr]["group_nb_questions"]:
                questions[gr][q][key] = value

    mongo_client.close()
    return questions
Exemplo n.º 7
0
def resetArrays(series):
    mongo_client = MongoClient('localhost', 27017)

    DB = mongo_client[Constants.DBNAME]
    QuestionCollection = DB[series + "__" + Constants.QUESTION_SUFFIX]

    groups = Group.fetchGroups(series)

    questions = []

    for gr in range(len(groups)):
        questions.append([])
        nb_questions = groups[gr]["group_nb_questions"]
        for q in range(nb_questions):
            questions[gr].append({})
            questions[gr][q]["_id"] = "G" + str(gr) + "Q" + str(q)
            questions[gr][q]["question_answers_from_player"] = []
            questions[gr][q]["question_times_from_player"] = []
            questions[gr][q]["question_answered_players"] = []
            questions[gr][q]["question_start_timestamp"] = -1
            questions[gr][q]["active"] = 0

    for gr in range(len(groups)):
        for q in range(len(questions[gr])):
            QuestionCollection.update_one(
                {"_id": "G" + str(gr) + "Q" + str(q)},
                {"$set": questions[gr][q]},
                upsert=True)

    mongo_client.close()
    return
Exemplo n.º 8
0
def updatePartialPlayers(current, player_names_str, old_player_names):
    groups = Group.fetchGroups(current["series"])
    mongo_client = MongoClient('localhost', 27017)

    DB = mongo_client[Constants.DBNAME]
    PlayerCollection = DB[current["series"] + "__" + Constants.PLAYER_SUFFIX]
    
    player_names_str = player_names_str.replace(" , ", ",").replace(", ", ",").replace(" ,", ",").replace(" ", "_")
    player_names = player_names_str.split(",")
    players = {}

    for player in old_player_names:
        players[player] = {}
        players[player]["_id"] = player
        players[player]["star_chosen"] = 0
        if player in player_names:
            players[player]["G" + str(current["group"]) + "_active"] = 1
        else:
            players[player]["G" + str(current["group"]) + "_active"] = 0
            players[player]["G" + str(current["group"]) + "_nb_stars"] = groups[current["group"]]["group_nb_stars"]
    
    for pl in players.keys():
        PlayerCollection.update_one({"_id": players[pl]["_id"]}, {"$set": players[pl]}, upsert=True)
    
    mongo_client.close()
Exemplo n.º 9
0
 def __init__(self):
     pygame.display.init()
     pygame.font.init()
     self.windowSize = (800, 600)
     self.windowMode = pygame.locals.DOUBLEBUF  # much better than default (0)
     self.displaySurface = pygame.display.set_mode(self.windowSize,
                                                   self.windowMode)
     self.running = True
     self.input = Input()
     self.group = Group()
     self.clearColor = (255, 255, 255)
     self.deltaTime = 0
     # display FPS
     self.fpsDisplay = False
     self.fps = 60
     self.fpsClock = pygame.time.Clock()
Exemplo n.º 10
0
 def out_of_band_members(self):
     '''
     (MemberDatabase) -> list
     
     Returns a list of Members with out-of-band status.
     '''
     return Group.Group(self._directory, self._database,
                        "type-outofband").members()
Exemplo n.º 11
0
def main():
  print('\n- Cost Splitter -')

  # Load save.
  groups = s.load_all_groups()
  if groups is None:
    groups = {}

  # Loop.
  user_in = ''
  while user_in != 'exit' and user_in != 'q':
    print_main_menu()
    user_in = input()
    print('')

    # Print groups.
    if user_in == '1':
      if len(groups) == 0:
        print('No stored groups')
        continue
      print('Stored Groups:')
      for group_name in groups:
        groups[group_name].print_group()
        print('')
    
    # Select group.
    if user_in == '2':
      print('Which group would you like to select?:')
      list_group_names(groups)
      group_name = input()
      if group_name not in groups:
        print('Group ' + group_name + ' does not exist\n')
        continue
      group_menu(groups[group_name])

    # Add new group.
    if user_in == '3':
      print('Enter name of group to add: ', end='')
      group_name = input()
      if group_name in groups:
        print('"' + group_name+ '" already exists in list of groups.')
        continue
      groups[group_name] = Group.Group(group_name)
      s.save_group(groups[group_name])
      # Select group automatically after creation.
      group_menu(groups[group_name])
    
    # Remove existing group.
    if user_in == '4':
      print('Enter name of group to remove:')
      list_group_names(groups)
      group_name = input()
      if group_name not in groups:
        print('"' + group_name+ '" cannot be found in list of groups.')
        continue
      deleted_group = groups.pop(group_name)
      s.delete_group(deleted_group)
Exemplo n.º 12
0
def MatchContinueDress(who, s):
    ret = []
    pattern = MATCH_YB_CONTINUE_DRESS if who == YB else MATCH_PLAYER_CONTINUE_DRESS
    for i in re.finditer(pattern, s):
        group = Group(i.span()[0], i.span()[1] - 1)
        #		print(group)
        ret.append(group)
    ret.sort()
    return ret
Exemplo n.º 13
0
def create_group(guestArray, guestIndices, groupList=[], useAll='True'):
    """
    Function takes in indices of guests to be grouped together. 
    The group that is created gets appended onto groupList. 
    If "useAll" parameter is True, then the remaining guests in the guestArray
    get grouped together into a second group (which then gets appended onto groupList). 
    Otherwise, the remaining guests are left in guestArray for future grouping.
    """
    guestListTemp = list()
    #the pointers to all of the objects needed to be removed
    listTorem = list()
    
    #add all the pointers of the objects needed to be removed to the holding arr
    for i in guestIndices:
        g = guestArray[i]
        listTorem.append(g)
    #run through each object needed to be removed and remove it from the GL
    
    print listTorem
    print guestIndices
    
    for i in range(len(listTorem)): 
        #pointer to object
        gRem = listTorem[i]
        #put that object into guest List temp
        guestListTemp.append(gRem)
        #If we are using everything
        if useAll: 
            #remove it from the guestArray
            guestArray.remove(gRem)
            
    print listTorem
    #create a group for this guest List
    group = Group(guestListTemp)
    #append it to our returning list
    groupList.append(group)
    #if we are using everything
    if useAll: 
        #make a group from the remnants
        group = Group(guestArray)
        #append it to our returning thingy
        groupList.append(group)
    #return our t
    return groupList, guestArray
Exemplo n.º 14
0
 def __init__(self, directory, database, roleName):
     '''
     (Role, LdapConnection, SqlConnection, str) -> None
     
     Initialize the Role instance from the role name.
     '''
     self._directory = directory
     self._database = database
     self._name = roleName
     self._roleGroup = Group.Group(directory, database, roleName)
Exemplo n.º 15
0
 def addGroupToContainer():
     newGroup = Group(groupE.get())
     errorCode = checkNewGroup(newGroup.getName(), groupContainer)
     if errorCode == 0:
         groupContainer.getGroupList().append(newGroup)
         grpWindow.destroy()
     elif errorCode == 1:
         errorL = makeLabel(grpWindow, "Group Name Empty", "Red")
         errorL.grid(row=3,
                     column=0,
                     sticky="nsew",
                     padx=(15, 15),
                     pady=(0, 10))
     elif errorCode == 2:
         errorL = makeLabel(grpWindow, "Group Already Exists", "Red")
         errorL.grid(row=3,
                     column=0,
                     sticky="ew",
                     padx=(15, 15),
                     pady=(0, 10))
Exemplo n.º 16
0
def decompose_addition_group(m: int):
    subgroups = []
    orders = []

    if get_euler(m) == m - 1:
        subgroups.append(Group.Group(1, [0], Group.OperationType.ADDITION))
        subgroups.append(Group.Group(2, list(range(m)), Group.OperationType.ADDITION))
        return subgroups

    for a in range(1, m + 1):
        for n in range(1, m + 1):
            if a * n % m == 0:
                if n in orders:
                    break
                subgroups.append(Group.Group(a,
                                             fill_subgroup(a, n, m, OperationType.ADDITION),
                                             Group.OperationType.ADDITION))
                orders.append(n)
                break

    return subgroups
Exemplo n.º 17
0
    def __init__(self, parent, username):
        self._user = username
        self._group_model = Group()
        self._user_group_model = UserGroup()
        self._custom_goal = CustomGoal()

        self.data = self.read_data()
        self.proxyModel = SortFilterProxyModel()  # make a proxy model object
        self.model = CustomTableModel(self.data)
        self.proxyModel.setSourceModel(self.model)

        self.ui = Ui_group(parent, self.proxyModel, self.data)
        #self.ui.group_table.setModel(self.proxyModel)  # At initialisation, the proxyModel is the model itself
        self.checkGroupSearch()  # method for searching the database
        self.ui.group_table.clicked.connect(
            partial(self.displayInQlineEdit
                    ))  # method for displaying text when row is clicked

        #self.ui.group_name_output.textEdited.connect(partial(self.addNewGroup))  # method for editing calorific value when portion changes
        self.ui.create_group_button.clicked.connect(partial(
            self.addNewGroup))  # method to add new food to database
        self.ui.join_group_button.clicked.connect(partial(
            self.joinNewGroup))  # method to add new food to database
Exemplo n.º 18
0
def load(graph):
    with open('users_data.json') as f:
        data = json.load(f)

    graph.numUsers = 0
    graph.maxUsers = int(data["maxUsers"])
    graph.num_posts = int(data["num_posts"])
    for one in data["Users"]:
        graph.AddUser(
            person.Person(one["name"], one["email"], one["password"],
                          one["age"], one["location"], one["gender"]))
        graph.Users[-1].groups = [int(i) for i in one["groups"]]
        graph.Users[-1].posts = [int(i) for i in one["posts"]]
        graph.Users[-1].admin = [int(i) for i in one["admin"]]
        for x in one["requests_sent"]:
            graph.Users[-1].requests_sent[int(x)] = int(
                one["requests_sent"][x])

        for x in one["requests_received"]:
            graph.Users[-1].requests_received[int(x)] = int(
                one["requests_received"][x])

    graph.edges = []
    for row in range(0, len(data["edges"])):
        graph.edges.append([])
        for col in range(0, len(data["edges"][row])):
            graph.edges[row].append([
                int(data["edges"][row][col][0]),
                int(data["edges"][row][col][1])
            ])

    for i in data["Posts"]:
        graph.Posts.append(post.Post(i["text"], int(i["user_id"])))
        graph.Posts[-1].post_id = int(i["post_id"])
        graph.Posts[-1].time = i["time"]
        for j in i["Comments"]:
            graph.Posts[-1].Comments.append(
                post.Comment(j["text"], int(j["user_id"]), int(j["post_id"])))
            graph.Posts[-1].Comments[-1].time = j["time"]
            graph.Posts[-1].Comments[-1].comment_id = int(j["comment_id"])

    for g in data["Groups"]:
        graph.Groups.append(
            group.Group(0, g["group_name"], g["group_description"]))
        graph.Groups[-1].admin_id = [int(i) for i in g["admin_id"]]
        graph.Groups[-1].group_id = int(g["group_id"])
        graph.Groups[-1].group_members = [int(i) for i in g["group_members"]]
        graph.Groups[-1].group_posts = [int(i) for i in g["group_posts"]]
        graph.Groups[-1].group_count = int(g["group_count"])
Exemplo n.º 19
0
    def to_json(self):
        vs = VarsSetting()
        vs.config = self.config
        for k, d in self.devices.items():
            vs.devices[k] = (Device.PureController(d))

            if d.groups:
                for g in d.groups.values():
                    pg = Group.PureGroup(g)
                    vs.groups.append(pg)
        try:
            s = json.dumps(vs, default=Utilities.Utility.serialize_instance)
        except Exception as e:
            s = json.dumps(vs)
        return s
Exemplo n.º 20
0
    def login_user(self, user: User):
        """ Logs the user in and gets the group name. A new group is created
            if the group requested does not exist already.

        Args:
            user (User): The user who is supposed to be logged in
        """
        user_name = self.get(user)
        user.user_name = user_name
        self.send(user, '/sendgroup')
        group_name = self.get(user)
        user.group_name = group_name
        if group_name in self.groups.keys():
            self.groups[group_name].connect(user)
        else:
            self.groups[group_name] = Group.Group(group_name)
            self.groups[group_name].connect(user)
Exemplo n.º 21
0
def updateQuestions(series, query):
    mongo_client = MongoClient('localhost', 27017)

    DB = mongo_client[Constants.DBNAME]
    QuestionCollection = DB[series + "__" + Constants.QUESTION_SUFFIX]

    groups = Group.fetchGroups(series)

    questions = []
    nb_questions_in_collection = QuestionCollection.count()

    for gr in range(len(groups)):
        questions.append([])
        nb_questions = groups[gr]["group_nb_questions"]
        for q in range(nb_questions):
            questions[gr].append({})
            questions[gr][q]["_id"] = "G" + str(gr) + "Q" + str(q)
            questions[gr][q]["question_answers_from_player"] = []
            questions[gr][q]["question_times_from_player"] = []
            questions[gr][q]["question_answered_players"] = []
            questions[gr][q]["question_start_timestamp"] = -1
            questions[gr][q]["active"] = 0

    for key, value in query.items():
        try:
            last_ = key.rfind("_")
            q = int(key[last_ + 1:])
            gr = int(key[last_ - 1])
            questions[gr][q][key[:last_ - 2:]] = convertInt(value)
        except:
            pass

    for gr in range(len(groups)):
        for q in range(len(questions[gr])):
            QuestionCollection.update_one(
                {"_id": "G" + str(gr) + "Q" + str(q)},
                {"$set": questions[gr][q]},
                upsert=True)

        for q in range(len(questions[gr]), nb_questions_in_collection):
            QuestionCollection.delete_one(
                {"_id": "G" + str(gr) + "Q" + str(q)})

    mongo_client.close()
    return
Exemplo n.º 22
0
def decompose_multiple_group(m: int):
    subgroups = []
    orders = []

    for a in range(1, m):
        eul = get_euler(m)
        n = 1
        while n <= eul:
            if a ** n % m == 1:
                if n in orders:
                    break
                subgroups.append(Group.Group(a,
                                             fill_subgroup(a, n, m, OperationType.MULTIPLE),
                                             Group.OperationType.MULTIPLE))
                orders.append(n)
                break
            n += 1

    return subgroups
Exemplo n.º 23
0
    def build_account_object(self, received_list):
        """
        This functions builds an account object which can be written directly to the database. The function received a
        list containing the teacher, course, groups and students plus semester.

        Example list style: [{"teacher": ["Teachername"], {"course":["Coursename"]}...}]
        :param received_list:
        :type received_list:
        :return account:
        :rtype DbAccount:
        """
        account = DbAccount()
        teacher = Teacher()
        course = Course()
        group = Group()
        groupdict = {}
        for i in received_list:
            for key, value in i.iteritems():
                if "teacher" in key:
                    teacher.set_name(value[0])
                elif "semester" in key:
                    teacher.set_semester(value[0])
                elif "course" in key:
                    course.set_coursename(value[0])
                elif "group" in key:
                    for groupkey, memberlist in value.iteritems():
                        group = Group()
                        groupdict.update({groupkey: memberlist})
                        group.set_groupname(groupkey)
                        group.set_students(memberlist)
                        if any(x.get_groupname() == groupkey
                               for x in course.get_groups()):
                            logging.info(groupkey +
                                         " exists in the object from before")
                        else:
                            course.set_group_list(group)
        teacher.set_course(course)
        account.set_teacher(teacher)
        return account
Exemplo n.º 24
0
    def json_to_data(self, data, conn):
        self.conn = conn

        # init data
        self.plan = []
        self.constraints = []
        self.groups = []

        width = data["width"]
        height = data["height"]
        forbidden_seats = data["forbidden_seats"]
        for line in range(height - 1):
            self.plan.append([])
            for cell in range(width - 1):
                forbid = any(fseat["line"] == line and fseat["cell"] == cell
                             for fseat in forbidden_seats)
                self.plan[line].append(0 if forbid else 1)

        groups = data["groups"]
        for group in groups:
            self.groups.append(Group(group["name"], group["number"], None, 0))

        self.lets_go()
Exemplo n.º 25
0
def updatePlayers(series, player_names_str):
    groups = Group.fetchGroups(series)
    questions = Question.fetchQuestions(series)
    mongo_client = MongoClient('localhost', 27017)
    DB = mongo_client[Constants.DBNAME]
    PlayerCollection = DB[series + "__" + Constants.PLAYER_SUFFIX]
    
    PlayerCollection.drop()
    
    player_names_str = player_names_str.replace(" , ", ",").replace(", ", ",").replace(" ,", ",").replace(" ", "_")
    player_names = player_names_str.split(",")
    
    players = {}

    for player in player_names:
        players[player] = {}
        players[player]["_id"] = player
        players[player]["point"] = 0
        players[player]["star_chosen"] = 0

        for group in groups:
            players[player][group["_id"] + "_active"] = 1
            players[player][group["_id"] + "_nb_stars"] = group["group_nb_stars"]
            players[player][group["_id"] + "_point"] = 0
            
            for question in questions[int(group["_id"][1])]:
                if int(question["_id"][3:]) < group["group_nb_questions"]:
                    players[player][question["_id"] + "_answer"] = -1
                    players[player][question["_id"] + "_time"] = -1.0
                    players[player][question["_id"] + "_point"] = 0
                    players[player][question["_id"] + "_star"] = 0
                    players[player][question["_id"] + "_correct"] = 0
    
    for pl in players.keys():
        PlayerCollection.update_one({"_id": players[pl]["_id"]}, {"$set": players[pl]}, upsert=True)
        
    mongo_client.close()
Exemplo n.º 26
0
    def build_account_object(self, received_list):
        """
        This functions builds an account object which can be written directly to the database. The function received a
        list containing the teacher, course, groups and students plus semester.

        Example list style: [{"teacher": ["Teachername"], {"course":["Coursename"]}...}]
        :param received_list:
        :type received_list:
        :return account:
        :rtype DbAccount:
        """
        account = DbAccount()
        teacher = Teacher()
        course = Course()
        group = Group()
        groupdict = {}
        for i in received_list:
            for key, value in i.iteritems():
                if "teacher" in key:
                    teacher.set_name(value[0])
                elif "semester" in key:
                    teacher.set_semester(value[0])
                elif "course" in key:
                    course.set_coursename(value[0])
                elif "group" in key:
                    for groupkey, memberlist in value.iteritems():
                        group = Group()
                        groupdict.update({groupkey: memberlist})
                        group.set_groupname(groupkey)
                        group.set_students(memberlist)
                        if any(x.get_groupname() == groupkey for x in course.get_groups()):
                            logging.info(groupkey + " exists in the object from before")
                        else:
                            course.set_group_list(group)
        teacher.set_course(course)
        account.set_teacher(teacher)
        return account
Exemplo n.º 27
0
 def all_groups(self):
     if self.is_wheel():
         return Group.all_groups()
     else:
         return dict([(k,v) for (k,v) in Group.all_groups().items() if self in v])
Exemplo n.º 28
0
def get_wheel_group():
    return Group.lookup(Config.wheel_group, Group.EmptyGroup())
Exemplo n.º 29
0
    def create(self):

        self.setTitle("Rectangle Destroyer")
        self.fpsDisplay = True

        background = Sprite()
        background.setTexture(
            Texture.load("assets/rectangle-destroyer/background.jpg"))
        background.setPosition(400, 300)
        self.group.addEntity(background)

        self.paddle = Sprite()
        self.paddle.setTexture(
            Texture.load("assets/rectangle-destroyer/paddle.png"))
        self.paddle.setPosition(400, 550)
        self.group.addEntity(self.paddle)

        self.ball = Sprite()
        self.ball.setTexture(
            Texture.load("assets/rectangle-destroyer/ball.png"))
        self.ball.setPosition(400, 525)
        self.ball.setPhysics(0, 1000, 0)
        self.group.addEntity(self.ball)

        self.wallGroup = Group()
        self.group.addEntity(self.wallGroup)
        wallSideTexture = Texture.load(
            "assets/rectangle-destroyer/wall-side.jpg")  # 20 x 600
        wallTopTexture = Texture.load(
            "assets/rectangle-destroyer/wall-top.jpg")  # 800 x 60
        leftWall = Sprite()
        leftWall.setTexture(wallSideTexture)
        leftWall.setPosition(10, 300)
        rightWall = Sprite()
        rightWall.setTexture(wallSideTexture)
        rightWall.setPosition(790, 300)
        topWall = Sprite()
        topWall.setTexture(wallTopTexture)
        topWall.setPosition(400, 30)
        self.wallGroup.addEntity(leftWall)
        self.wallGroup.addEntity(rightWall)
        self.wallGroup.addEntity(topWall)

        self.brickGroup = Group()
        self.group.addEntity(self.brickGroup)

        brickTexture = Texture.load("assets/rectangle-destroyer/brick.jpg")

        for col in range(0, 11):
            for row in range(0, 8):
                brick = Sprite()
                brick.setTexture(brickTexture)
                brick.setPosition(80 + 64 * col, 120 + row * 32)
                self.brickGroup.addEntity(brick)

        self.messageLabel = Label()
        self.messageLabel.loadFont("assets/starfish-collector/OpenSans.ttf",
                                   48)
        self.messageLabel.fontColor = (128, 128, 128)
        self.messageLabel.text = "click to start"
        self.messageLabel.setPosition(400, 400)
        self.messageLabel.alignment = "CENTER"
        self.group.addEntity(self.messageLabel)

        self.score = 0
        self.scoreLabel = Label()
        self.scoreLabel.loadFont("assets/starfish-collector/OpenSans.ttf", 36)
        self.scoreLabel.fontColor = (255, 255, 0)
        self.scoreLabel.text = "Score: " + str(self.score)
        self.scoreLabel.setPosition(400, 0)
        self.scoreLabel.alignment = "CENTER"
        self.group.addEntity(self.scoreLabel)
Exemplo n.º 30
0
class RectangleDestroyer(Game):
    def create(self):

        self.setTitle("Rectangle Destroyer")
        self.fpsDisplay = True

        background = Sprite()
        background.setTexture(
            Texture.load("assets/rectangle-destroyer/background.jpg"))
        background.setPosition(400, 300)
        self.group.addEntity(background)

        self.paddle = Sprite()
        self.paddle.setTexture(
            Texture.load("assets/rectangle-destroyer/paddle.png"))
        self.paddle.setPosition(400, 550)
        self.group.addEntity(self.paddle)

        self.ball = Sprite()
        self.ball.setTexture(
            Texture.load("assets/rectangle-destroyer/ball.png"))
        self.ball.setPosition(400, 525)
        self.ball.setPhysics(0, 1000, 0)
        self.group.addEntity(self.ball)

        self.wallGroup = Group()
        self.group.addEntity(self.wallGroup)
        wallSideTexture = Texture.load(
            "assets/rectangle-destroyer/wall-side.jpg")  # 20 x 600
        wallTopTexture = Texture.load(
            "assets/rectangle-destroyer/wall-top.jpg")  # 800 x 60
        leftWall = Sprite()
        leftWall.setTexture(wallSideTexture)
        leftWall.setPosition(10, 300)
        rightWall = Sprite()
        rightWall.setTexture(wallSideTexture)
        rightWall.setPosition(790, 300)
        topWall = Sprite()
        topWall.setTexture(wallTopTexture)
        topWall.setPosition(400, 30)
        self.wallGroup.addEntity(leftWall)
        self.wallGroup.addEntity(rightWall)
        self.wallGroup.addEntity(topWall)

        self.brickGroup = Group()
        self.group.addEntity(self.brickGroup)

        brickTexture = Texture.load("assets/rectangle-destroyer/brick.jpg")

        for col in range(0, 11):
            for row in range(0, 8):
                brick = Sprite()
                brick.setTexture(brickTexture)
                brick.setPosition(80 + 64 * col, 120 + row * 32)
                self.brickGroup.addEntity(brick)

        self.messageLabel = Label()
        self.messageLabel.loadFont("assets/starfish-collector/OpenSans.ttf",
                                   48)
        self.messageLabel.fontColor = (128, 128, 128)
        self.messageLabel.text = "click to start"
        self.messageLabel.setPosition(400, 400)
        self.messageLabel.alignment = "CENTER"
        self.group.addEntity(self.messageLabel)

        self.score = 0
        self.scoreLabel = Label()
        self.scoreLabel.loadFont("assets/starfish-collector/OpenSans.ttf", 36)
        self.scoreLabel.fontColor = (255, 255, 0)
        self.scoreLabel.text = "Score: " + str(self.score)
        self.scoreLabel.setPosition(400, 0)
        self.scoreLabel.alignment = "CENTER"
        self.group.addEntity(self.scoreLabel)

    def update(self):

        position = self.input.getMousePosition()
        self.paddle.x = position.x
        self.paddle.boundToScreen(800, 600)

        if (self.messageLabel.visible
                and self.messageLabel.text == "click to start"):
            self.ball.x = self.paddle.x
            if (self.input.isMouseButtonDown()):
                self.ball.physics.setSpeed(250)
                self.ball.physics.setMotionAngle(270)
                self.messageLabel.visible = False

        for wall in self.wallGroup.list():
            self.ball.bounceAgainst(wall)

        if (self.ball.isOverlapping(self.paddle)):
            self.ball.preventOverlap(self.paddle)
            paddlePercent = percent(self.ball.x,
                                    self.paddle.x - self.paddle.width / 2,
                                    self.paddle.x + self.paddle.width / 2)
            reboundAngle = lerp(paddlePercent, 225, 315) + randomBetween(-2, 2)
            self.ball.physics.setMotionAngle(reboundAngle)
            self.ball.physics.setSpeed(self.ball.physics.getSpeed() + 2)
            self.score += 1

        for brick in self.brickGroup.list():
            if (self.ball.isOverlapping(brick)):
                self.ball.bounceAgainst(brick)
                brick.remove()
                self.score += 100

        self.scoreLabel.text = "Score: " + str(self.score)

        if ((self.messageLabel.visible == False) and (self.ball.y > 700)):
            self.ball.physics.setSpeed(0)
            self.ball.setPosition(self.paddle.x, self.paddle.y - 20)
            self.messageLabel.visible = True
            self.messageLabel.text = "click to start"

        if (self.brickGroup.count == 0):
            self.messageLabel.visible = True
            self.messageLabel.setPosition(400, 300)
            self.messageLabel.fontColor = (0, 255, 0)
            self.messageLabel.text = "You Win!"
Exemplo n.º 31
0
class SpaceRocks(Game):
    def create(self):

        self.setTitle("Space Rocks")
        self.fpsDisplay = True

        space = Sprite()
        space.setTexture(Texture.load("assets/space-rocks/space.png"))
        space.setPosition(400, 300)
        self.group.addEntity(space)

        self.spaceship = Sprite()
        self.spaceship.setTexture(
            Texture.load("assets/space-rocks/spaceship.png"))
        self.spaceship.setPosition(100, 300)
        # physics values
        self.spaceship.setPhysics(100, 200, 10)
        self.spaceship.addAction(ActionFactory.wrapToScreen(800, 600))
        self.group.addEntity(self.spaceship)

        rockTexture = Texture.load("assets/space-rocks/rock.png")
        self.rockGroup = Group()
        self.group.addEntity(self.rockGroup)

        for n in range(6):
            rock = Sprite()
            x = random() * 400 + 300
            y = random() * 600
            rock.setPosition(x, y)
            rock.setTexture(rockTexture)
            rock.setPhysics(0, 80, 0)
            rock.physics.setSpeed(80)
            angle = random() * 360
            rock.angle = angle
            rock.physics.setMotionAngle(angle)
            rock.addAction(ActionFactory.wrapToScreen(800, 600))
            self.rockGroup.addEntity(rock)

        self.laserTexture = Texture.load("assets/space-rocks/laser.png")
        self.laserGroup = Group()
        self.group.addEntity(self.laserGroup)

        self.explosionAnimation = Animation.load(
            "assets/space-rocks/explosion.png", 6, 6, 0.03, False)

        self.messageWin = Sprite()
        self.messageWin.setTexture(
            Texture.load("assets/space-rocks/message-win.png"))
        self.messageWin.setPosition(400, 300)
        self.messageWin.opacity = 0
        self.messageWin.visible = False
        self.group.addEntity(self.messageWin)

    def update(self):

        if self.input.isKeyPressed(K_LEFT):
            self.spaceship.rotateBy(-2)
        if self.input.isKeyPressed(K_RIGHT):
            self.spaceship.rotateBy(2)
        if self.input.isKeyPressed(K_UP):
            self.spaceship.physics.accelerateAtAngle(self.spaceship.angle)

        if (self.input.isKeyDown(K_SPACE)):
            laser = Sprite()
            laser.setPosition(self.spaceship.x, self.spaceship.y)
            laser.setPhysics(0, 400, 0)
            laser.physics.setSpeed(400)
            laser.physics.setMotionAngle(self.spaceship.angle)
            laser.setTexture(self.laserTexture)
            laser.addAction(ActionFactory.wrapToScreen(800, 600))
            laser.addAction(
                ActionFactory.sequence(ActionFactory.delay(1),
                                       ActionFactory.fadeOut(0.5),
                                       ActionFactory.remove()))
            self.laserGroup.addEntity(laser)

        for laser in self.laserGroup.list():
            for rock in self.rockGroup.list():
                if (laser.isOverlapping(rock)):
                    laser.remove()
                    rock.remove()
                    explosion = Sprite()
                    explosion.setAnimation(self.explosionAnimation.clone())
                    explosion.setPosition(rock.x, rock.y)
                    # remove after animation complete
                    explosion.addAction(
                        ActionFactory.sequence(
                            ActionFactory.isAnimationFinished(),
                            ActionFactory.remove()))
                    self.group.addEntity(explosion)

        if (self.rockGroup.count == 0 and not self.messageWin.visible):
            self.messageWin.visible = True
            self.messageWin.addAction(ActionFactory.fadeIn(2))
Exemplo n.º 32
0
 def groups(self):
     return [Group.Group(group["_id"]) for group in self.__groups]
Exemplo n.º 33
0
        ln = input("What is the person's last name?\n")
        D = dict()
        D = {"First Name": fn, "Last Name": ln, "ID": None, "GroupNum": None}
        p1 = Person.Personn(first_name=fn, last_name=ln, attributes=D)
        list.append(p1)
        # D = {"First Name": None, "Last Name": None, "ID": None, "GroupNum": None}
        #  p1 = Person.Personn()                     # Test for all type of constructors....
        #  p1 = Person.Personn( first_name= fn, last_name= ln)
        #  P1 = Person.Personn( attributes)
        # p1  = Person.Personn( attributes = D )
        # checklist = [ "ID", "First Name", "Last Name" , "GroupNum"]
        #p2.validate( checklist)

    elif userInput == 2:
        # Create a group
        g1 = Group.Groupp()

        # Populate all existing person objects.
        for person in list:
            if (person.attributes["GroupNum"] is None):
                print(person.attributes["ID"], end="")
                print(" " + person.attributes["First Name"] + " " +
                      person.attributes["Last Name"])

        # Loop to add person to the groups.
        prompt = input(
            "Which person would you like to add to the new group? (-1 to finish adding people) : \n"
        )
        add = int(prompt)

        while add != -1:
Exemplo n.º 34
0
 def writable_for(self, user):
     return user in Group.lookup(
         self.editgroup or Config.default_edit_group,
         User.get_wheel_group())
Exemplo n.º 35
0
 def writable_for(self, user):
     return user in Group.lookup(self.editgroup or Config.default_edit_group,
                                 User.get_wheel_group())
        parser.error("I require five arguments")
    memberId = str(args[0])
    fullName = str(args[1])
    email = str(args[2])
    department = str(args[3])
    username = str(args[4])

    # Check validity of arguments
    if not Member.is_valid_lidnummer(memberId):
        parser.error("Not a valid member ID. Aborting...")
    if not Member.is_valid_full_name(fullName):
        parser.error("Not a valid full name. Aborting...")
    if not Member.is_valid_mail(email):
        parser.error("Not a valid email address. Aborting...")
    if not Member.is_valid_afdeling(department):
        parser.error("Not a valid department. Aborting...")
    if not Member.is_valid_username(username):
        parser.error("Not a valid username. Aborting...")
    newMember = Member.Member(l, s, int(memberId))
    if newMember.exists():
        helper.logger.error("Member %s already exists. Aborting..." % memberId)
        sys.exit()

    # Create out-of-band member
    newMember.create(fullName, email, department)
    newMember.make_user(username, 3)
    group = Group.Group(l, s, "type-outofband")
    group.add(newMember)
    helper.logger.info("Created out-of-band member %s (%s)." %
                       (fullName, memberId))
Exemplo n.º 37
0
 def readable_for(self, user):
     return user in Group.lookup(self.viewgroup or Config.default_view_group,
                                 User.get_wheel_group())