コード例 #1
0
    def _init_scene_from_data(self):
        simple_object = PlayerObject.PlayerObject()
        simple_object.pos = (128, 0, 32)
        simple_object.set_controller(self.player_controller)
        self.objects.append(simple_object)
        self.player_objects.append(simple_object)

        simple_object2 = Object.Object("Sample")
        simple_object2.reset_pos((32, 0, 32))
        server_control2 = ServerControl(simple_object2)
        simple_object2.insert_game_logic_component("ObjectControl",
                                                   server_control2)
        self.objects.append(simple_object2)

        simple_object3 = Object.Object("Apple")
        simple_object3.reset_pos((80, 0, 80))
        self.objects.append(simple_object3)

        simple_object4 = Object.Object("Sample")
        simple_object4.reset_pos((128, 0, 128))
        self.objects.append(simple_object4)

        ground1 = Object.Object("IceGround")
        ground1.reset_pos((256, 0, 256))
        self.objects.append(ground1)
コード例 #2
0
    def animate(self):
        self.playerImage = Object(self, Image('./res/image/idle/0.png'),
                                  (-100 - 700, 250), (800, 600))
        self.addObject(self.playerImage)
        self.titleImage = Object(self, Image('./res/image/title2.png'),
                                 (850, 80 - 480), (650, 400))

        def debugOn():
            if self.titleImage.isHover(): Scene.game.debug = True

        self.titleImage.onPress = debugOn
        self.addObject(self.titleImage)
        self.phase = 1
        yield None
        self.playerImage.location = (-100, 250)
        self.titleImage.location = (850, 80)
        host = threading.Thread(target=self.host, daemon=True).start
        join = threading.Thread(target=self.join, daemon=True).start
        self.hostButton = TitleButton(self, "HOST", host, (1320 + 600, 550))
        self.addObject(self.hostButton)
        self.joinButton = TitleButton(self, "JOIN", join, (1320 + 600, 650))
        self.addObject(self.joinButton)
        self.phase = 2
        yield None
        self.phase = 3
        yield None
        self.hostButton.location = (1320, 550)
        self.joinButton.location = (1320, 650)
        self.phase = 4
        yield None
コード例 #3
0
 def new_animation(self,
                   path,
                   layer=Constants.la['bg'],
                   origin=Constants.o['cc'],
                   frame_count=2,
                   frame_delay=500,
                   loop_type="LoopForever",
                   x=320,
                   y=240,
                   use_folder=True):
     """
     instantiates a new sprite
     :param path: filepath to the sprite relative from the SB folder path
     :param layer: SB Layer the sprite plays on
     :param origin: where the 'center' point of the sprite is
     :param frame_count: # of animation frames
     :param frame_delay: # delay between frames
     :param loop_type:  loop forever or just once?
     :param x: default coordinate x
     :param y: default coordinate y
     :param use_folder: determine whether or not to use the SB folder known by this class
     :return: animation instance
     """
     if use_folder:
         animation = Object.Animation(self.sb_folder + path, layer, origin,
                                      frame_count, frame_delay, loop_type,
                                      x, y)
     else:
         animation = Object.Animation(path, layer, origin, frame_count,
                                      frame_delay, loop_type, x, y)
     self.sprites.append(animation)
     self.current_sprite = animation
     return animation
コード例 #4
0
def handle_events():
    global Cursor_x, Cursor_y
    events = get_events()
    for event in events:
        if event.type == SDL_QUIT:
            game_framework.quit()
        elif event.type == SDL_MOUSEMOTION:  # 마우스 움직일 때
            Cursor_x, Cursor_y = event.x, main_state.WindowHeight - 1 - event.y
        elif event.type == SDL_KEYDOWN and event.key == SDLK_SPACE and main_state.O_Type == 1:
            if main_state.Cost >= 10:
                main_state.Cost -= 10
                main_state.Ally.append(
                    Object.Ally(main_state.O_Type, Cursor_x, Cursor_y))
        elif event.type == SDL_KEYDOWN and event.key == SDLK_SPACE and main_state.O_Type == 2:
            if main_state.Cost >= 20:
                main_state.Cost -= 20
                main_state.Ally.append(
                    Object.Ally(main_state.O_Type, Cursor_x, Cursor_y))
        elif event.type == SDL_KEYDOWN and event.key == SDLK_SPACE and main_state.O_Type == 3:
            if main_state.Cost >= 10:
                main_state.Cost -= 10
                main_state.Ally.append(
                    Object.Ally(main_state.O_Type, Cursor_x, Cursor_y))
        elif event.type == SDL_KEYDOWN and event.key == SDLK_ESCAPE:  # esc key 커서 복귀
            main_state.O_Type = 0
        elif event.type == SDL_KEYDOWN and event.key == SDLK_1:
            main_state.O_Type = 1
        elif event.type == SDL_KEYDOWN and event.key == SDLK_2:
            main_state.O_Type = 2
        elif event.type == SDL_KEYDOWN and event.key == SDLK_3:
            main_state.O_Type = 3
        elif (event.type, event.key) == (SDL_KEYDOWN, SDLK_RETURN):
            game_framework.pop_state()

    pass
コード例 #5
0
ファイル: Location.py プロジェクト: d86leader/Roguelike
class Location:
	def __init__(self, game):
		fighter_component = Fighter(hp=30, defense=2, power=5, death_function=self.player_death)
		self.player = Object(0, 0, '@', 'player', "white", game, blocks=True, fighter=fighter_component)
		self.objects = [self.player]
		self.map = Map(game, self)

	def player_death(self, player):
		player.char = '%'
		player.color = "red"
	 
	def monster_death(self, monster):
		monster.char = '%'
		monster.color = "red"
		monster.blocks = False
		monster.fighter = None
		monster.ai = None
		monster.name = 'remains of ' + monster.name
		monster.send_to_back()

	def player_move_or_attack(self, dx, dy):
		x = self.player.x + dx
		y = self.player.y + dy

		target = None
		for obj in self.objects:
			if obj.x == x and obj.y == y:
				target = obj
				break

		if target is not None:
			target.fighter.attack(target)
		else:
			self.player.move(dx, dy)
コード例 #6
0
    def __init__(self, showbase):

        #--------------------- SKY

        showbase.scene = Object(showbase, "ForestSky/ForestSky", 0.10, 0.10,
                                0.10, 0, 0, 0, 0, 0, 8.8, showbase.render)

        #--------------------- DECORATIONS

        showbase.dec = Object(showbase, "Shrubbery2/Shrubbery2", 0.01, 0.01,
                              0.01, 0, 0, 0, 7, 8, -0.5, showbase.render)

        for i in range(0, 4):
            showbase.dec = Object(showbase, "MushroomStalk/MushroomStalk",
                                  0.3 * i, 0.3 * i, 0.9, 0, 0, 0, 4 - i * 3,
                                  10 - i * 3, 0, showbase.render)

        for i in range(1, 3):
            showbase.dec = Object(showbase, "Tulip/Tulip", 8, 8, 8, 90, 0, 0,
                                  10 + i * i, 8 - i * i, -0.5, showbase.render)

        for i in range(1, 4):
            showbase.dec = Object(showbase, "Sunflower/Sunflower", 2.3 * i,
                                  2.2 * i, 2.5 * i, 180, 0, 0, 7.5 + i, 8 + i,
                                  -1.5, showbase.render)
コード例 #7
0
ファイル: main_state.py プロジェクト: Easyless/2DGP_Project
def enter():
    global Ally, Enemy, CursorImage, Cursor_M1, Cursor_M2, Cursor_W, BackGroundImage, Font, UI, Cost, Score, OverSound, BGM, ClearSound, PauseUI,\
        ClearImage, stage, KillCount, Cursor_Ig, Font2, AllclearSound, IsClear, ClearTimer
    BGM = pico2d.load_music('Sound\\main.ogg')
    ClearSound = pico2d.load_wav('Sound\\clear.wav')
    AllclearSound = pico2d.load_wav('Sound\\allclear.wav')
    BGM.repeat_play()
    OverSound = pico2d.load_wav('Sound\\gameover.wav')
    Cost = 50
    stage = 1
    KillCount = 0
    IsClear = False
    ClearTimer = 0
    Enemy = []
    Ally = [
        Object.Ally(0, WindowWidth / 2, WindowHeight / 2),
        Object.Ally(1, WindowWidth / 2 + 50, WindowHeight / 2 + 50),
        Object.Ally(1, WindowWidth / 2 + 50, WindowHeight / 2 - 50),
        Object.Ally(1, WindowWidth / 2 - 50, WindowHeight / 2 + 50),
        Object.Ally(1, WindowWidth / 2 - 50, WindowHeight / 2 - 50)
    ]  # 오브젝트 초기 할당
    CursorImage = load_image('image\\Cursor.png')
    Cursor_M1 = load_image('image\\Monster1.png')
    Cursor_M2 = load_image('image\\Monster2.png')
    Cursor_W = load_image('image\\Fake_cursor.png')
    Cursor_Ig = load_image('image\\ignite.png')
    BackGroundImage = load_image('image\\back.png')
    Font = load_font('MapleBold.ttf', 30)
    Font2 = load_font('MapleBold.ttf', 10)
    PauseUI = load_image('image\\UI\\PauseButton.png')
    ClearImage = load_image('image\\UI\\clear.png')

    pass
コード例 #8
0
ファイル: Main.py プロジェクト: denssle/WoWK
    def makeSomeTea(self):
        teapot01 = Object.Object('teapo01', 'teapot', self.world.odeWorld,
                                 self.world.space, 0, 10, 40)
        self.world.addToObjects(teapot01)

        teapot02 = Object.Object('teapo02', 'teapot', self.world.odeWorld,
                                 self.world.space, 0, 10, 80)
        self.world.addToObjects(teapot02)
コード例 #9
0
def modelParse(text):
    # The init setup is to stack an anchor Obj called 'Root', then set
    # the indent high. Whatever the initial indent, it will be lower, so
    # the anchor is unstacked and set as the current parent.
    treeRoot = Object.new(otype="Root",
                          oid="",
                          sClass="",
                          klass="",
                          oattrs={},
                          children=[])
    currentParent = treeRoot
    objStack = [StackItem(-99, currentParent)]
    indent = sys.maxsize
    for l in iter(text.splitlines()):
        initLen = len(l)
        lStripLine = l.strip()
        lStriplineLen = len(lStripLine)
        # if empty line...
        if (lStriplineLen == 0):
            continue
        newIndent = initLen - lStriplineLen

        DObj = modelLineParse(lStriplineLen, lStripLine)

        #print(str(newIndent))
        #print(str(DObj))

        # Add object to object model, adjusting
        # parents if necessary
        ## is Child
        if (newIndent > indent):
            objStack.append(StackItem(indent, currentParent))
            lastObj = currentParent.children[-1]
            if (not (lastObj.otype in containerNames)):
                implicitBox = Object.new(otype="VBox",
                                         oid="",
                                         sClass="",
                                         klass="",
                                         oattrs={},
                                         children=[])
                currentParent.children.append(implicitBox)
                lastObj = implicitBox
            currentParent = lastObj
            indent = newIndent

        ## revert to parents
        if (newIndent < indent):
            oldParent = StackItemEmpty
            while (True):
                oldParent = objStack.pop()
                if (oldParent.indent <= newIndent):
                    break
            currentParent = oldParent.obj
            indent = newIndent

        ## else is sibling. Now...
        currentParent.children.append(DObj)
    return treeRoot
コード例 #10
0
def addSprite(item, sprite):  #add a sprite at the end of the sprite list
    assertItem(
        item
    )  #PERFORMANCE  --> comment this line to increase performances (use carefully)
    Object.assertDatas(
        sprite
    )  #PERFORMANCE  --> comment this line to increase performances (use carefully)
    item["sprites"].append(sprite)  #add sprite at the list
    return 0
コード例 #11
0
ファイル: Frames.py プロジェクト: hslee1539/household-ledger
 def __init__(self):
     """ 이녀석의 드로우는 engine.g로 하면 안됩니다. 컨트롤 박스의 secondCanvas이용"""
     self.다시쓰기 = Object.iButton(Point(0, 0), Point(100, 100), Color.c1,
                                "컨트롤박스_조회.다시쓰기", "icon_rewrite.png")
     self.찾기 = Object.iButton(Point(100, 0), Point(100, 100), Color.c1,
                              "컨트롤박스_조회.찾기", "icon_find.png")
     self.삭제 = Object.iButton(Point(200, 0), Point(100, 100), Color.c1,
                              "컨트롤박스_조회.삭제", "icon_delete.png")
     self.다시쓰기ment = "수정을 하시겠습니까?"
     self.찾기ment = "구현중입니다"
     self.삭제ment = "삭제를 하시겠습니까?"
コード例 #12
0
ファイル: ObjectTest.py プロジェクト: jcemelanda/FretsOnFire
    def testMultipleManagers(self):
        m1 = Object.Manager(1000)
        m2 = Object.Manager(2000)

        o1 = TestObject(manager=m1)
        o2 = TestObject(manager=m2)

        m1.applyChanges(m2.id, m2.getChanges())
        m2.applyChanges(m1.id, m1.getChanges())

        assert len(m1.objects) == 2
        assert len(m2.objects) == 2
コード例 #13
0
ファイル: main_state.py プロジェクト: Easyless/2DGP_Project
def update():
    global timer, stage, IsClear, ClearTimer, KillCount, BGM, ClearSound, AllclearSound
    isHQExist = False
    for ally in Ally:
        ally.Update(Enemy)
        if ally.Type == 0:
            isHQExist = True
    if not isHQExist:
        BGM.stop()
        OverSound.play()
        return game_framework.push_state(over_state)
    for enemy in Enemy:
        enemy.Update(Ally, WindowWidth, WindowHeight)
    if len(Enemy) < 30 and not IsClear:
        if timer % 300 - (stage * 20) == 0:  # 시간마다 적 추가
            if stage == 1:  # 스테이지별 나오는 몬스터 변경
                Enemy.append(Object.Enemy(1))
            elif stage == 2:
                Enemy.append(Object.Enemy(random.randint(1, 2)))
            elif stage == 3:
                Enemy.append(Object.Enemy(2))
            elif stage == 4:
                Enemy.append(Object.Enemy(random.randint(2, 3)))
            else:
                Enemy.append(Object.Enemy(3))
        timer += 1
        # Enemy.append(Object.Enemy(random.randint(1, 2)))

    if KillCount >= stage * 5:
        IsClear = True
        KillCount -= 50
        stage += 1
        if stage == 6:
            BGM.stop()
            AllclearSound.play()
            return game_framework.push_state(over_state)
        BGM.stop()
        ClearSound.play()
        for enemy in Enemy:
            enemy.Frame = 0
            enemy.state = 3

    if IsClear:
        ClearTimer += 1
        if ClearTimer > 600:
            IsClear = False
            ClearTimer = 0
            KillCount = 0
            game_framework.push_state(maintain_state)

    delay(0.01)
    pass
コード例 #14
0
ファイル: Frames.py プロジェクト: hslee1539/household-ledger
    def __init__(self):
        self.창바라인 = Object.Box(Point(396, 196), Point(608, 308), Color.c4,
                               "경고창.창바")
        self.창바 = Object.Label(Point(400, 200), Point(600, 300), Color.c2,
                               "경고창.창바", Text("m12버전입니다.", None))
        self.제목바 = Object.Label(Point(400, 200), Point(600, 100), Color.c3,
                                "경고창.제목창", Text("알림", None, "24 bold"))
        self.확인버튼 = Object.iButton(Point(800, 400), Point(100, 100), Color.c6,
                                   "경고창.확인버튼", "icon_yes.png")
        self.취소버튼 = Object.iButton(Point(900, 400), Point(100, 100), Color.c6,
                                   "경고창.취소버튼", "icon_no.png")

        self.__sw = 0
コード例 #15
0
 def getLower(self):
     self.str1 = self.e1.get()
     self.str2 = self.e2.get()
     o1 = Object(self.str1)
     o2 = Object(self.str2)
     o1.getLower()
     o2.getLower()
コード例 #16
0
 def getSorted(self):
     self.str1 = self.e1.get()
     self.str2 = self.e2.get()
     o1 = Object(self.str1)  #only 1 arg passed
     o2 = Object(self.str2)
     o1.getSorted()
     o2.getSorted()
コード例 #17
0
ファイル: pb.py プロジェクト: Cypher-0/projet-IPI
def show():
    global pb0, SCREEN_WIDTH, SCREEN_HEIGHT

    #on clear la console et on réinitialise le curseur
    sys.stdout.write("\033[1;1H")
    sys.stdout.write("\033[2J")

    #affichage des different element
    Object.show(pb0)

    #deplacement curseur
    sys.stdout.write("\033[0;0H\n")

    return 0
コード例 #18
0
def setSprite(item, index):  #set which sprite to be displayed on screen
    assertItem(
        item
    )  #PERFORMANCE  --> comment this line to increase performances (use carefully)
    assert type(
        index
    ) is int  #PERFORMANCE  --> comment this line to increase performances (use carefully)
    assert index >= 0 and index < len(
        item["sprites"]
    ), "Index out of range. It have to be in [0;%r] and current try is : %r" % (
        len(item["sprites"]), index)
    #PERFORMANCE  --> comment this line (upper) to increase performances (use carefully)
    Object.setDatas(item, item["sprites"][index])
    return 0
コード例 #19
0
ファイル: main_state.py プロジェクト: Easyless/2DGP_Project
def handle_events():
    global Cursor_x, Cursor_y
    global O_Type
    global Cost
    global KillCount
    events = get_events()
    for event in events:
        if event.type == SDL_QUIT:  # 창 닫기
            game_framework.quit()
        elif event.type == SDL_MOUSEMOTION:  # 마우스 움직일 때
            Cursor_x, Cursor_y = event.x, WindowHeight - 1 - event.y
        elif event.type == SDL_MOUSEBUTTONDOWN:
            if WindowWidth - 75 <= Cursor_x <= WindowWidth - 25:
                if WindowHeight - 75 <= Cursor_y <= WindowHeight - 25:
                    game_framework.push_state(pause_state)
        elif event.type == SDL_KEYDOWN and event.key == SDLK_SPACE and O_Type == 1:
            if IsClear is False:
                if Cost >= 20:
                    Cost -= 20
                    Ally.append(Object.Ally(O_Type, Cursor_x, Cursor_y))
        elif event.type == SDL_KEYDOWN and event.key == SDLK_SPACE and O_Type == 2:
            if IsClear is False:
                if Cost >= 30:
                    Cost -= 30
                    Ally.append(Object.Ally(O_Type, Cursor_x, Cursor_y))
        elif event.type == SDL_KEYDOWN and event.key == SDLK_SPACE and O_Type == 3:
            if IsClear is False:
                if Cost >= 20:
                    Cost -= 20
                    Ally.append(Object.Ally(O_Type, Cursor_x, Cursor_y))
        elif event.type == SDL_KEYDOWN and event.key == SDLK_SPACE and O_Type == 4:
            if IsClear is False:
                if Cost >= 30:
                    Cost -= 30
                    Ally.append(Object.Ally(O_Type, Cursor_x, Cursor_y))
        elif event.type == SDL_KEYDOWN and event.key == SDLK_ESCAPE:  # esc key 커서 복귀
            O_Type = 0
        elif event.type == SDL_KEYDOWN and event.key == SDLK_1:
            O_Type = 1
        elif event.type == SDL_KEYDOWN and event.key == SDLK_2:
            O_Type = 2
        elif event.type == SDL_KEYDOWN and event.key == SDLK_3:
            O_Type = 3
        elif event.type == SDL_KEYDOWN and event.key == SDLK_4:
            O_Type = 4
        elif event.type == SDL_KEYDOWN and event.key == SDLK_k:
            KillCount += 10
        elif event.type == SDL_KEYDOWN and event.key == SDLK_l:
            Cost += 50
コード例 #20
0
def pack_txt_in_bucket(host, bucket_name, object_name):
    txt_names = get_txt_names(host, bucket_name)
    archive_converted_name = object_name + "_converted" + ".tgz"
    archive_converted_path = f"{UPLOAD_DIR}/{archive_converted_name}"
    # Download and pack the archive
    with tarfile.open(archive_converted_path, "w") as archive_converted:
        for txt_name in txt_names:
            Object.download(host, bucket_name, txt_name)
            txt_path = f"{DOWNLOAD_DIR}/{txt_name}"
            archive_converted.add(txt_path, arcname=f"{txt_name}")
            os.remove(txt_path)
    Object.upload(host, bucket_name, archive_converted_name)
    os.remove(archive_converted_path)

    return "Success"
コード例 #21
0
    def __init__(self, scenarioData, viewId, viewAttributes, viewImages):
        super(Custom, self).__init__(scenarioData, viewAttributes, viewId)

        self.objectList = []
        for imageId in viewImages:
            images = viewImages[imageId].pop("image")
            imageAttributes = viewImages[imageId]

            if (imageAttributes["className"] == "Text"):
                newObject = Object.Text(self, images[0], imageAttributes,
                                        imageId)
            else:
                newObject = Object.Object(self, imageId, images,
                                          imageAttributes)
            self.objectList.append(newObject)
コード例 #22
0
	def read_images(self, file):
		image_num = int(file.readline().strip().split(' ')[1])

		for i in range(image_num):
			image = Object()
			file.readline()
			image_id = int(file.readline().strip().split(' ')[1])
			image.init('Image', file_name = ResourceManager.instance().image_path_list[image_id])
			image.rotate(float(file.readline().strip().split(' ')[1]))
			image.scale(*map(float, file.readline().strip().split(' ')[1:]))
			image.translate(*map(int, file.readline().strip().split(' ')[1:]))
			self.all_object_list.add(image)
コード例 #23
0
 def ExportUsers(self):
     """Export all of the users."""
     print >> sys.stderr, "Describing users..."
     whereClause = "where o.username %s" % self.schemasClause
     self.ExportObjects(
         Object.ObjectIterator(self.environment, "AllUsers",
                               Statements.USERS, whereClause, Object.User))
コード例 #24
0
    def check_answer(self, mes, bot, update, quest):

        if any(mes in s for s in quest[1]):
            obj = Object.get_object(self.objects, self.quest_for_check[2])
            logging.debug("ANSWER IN DICT")
            if str(mes) == quest[0]:
                bot.sendMessage(chat_id=update.message.chat_id, text='✅Правильно')
                self.db.insert_answers(self.con, update, obj.name, 1, 0)

                self.ask_question(bot, update, obj)
            else:

                inc_answ = self.db.add_incorrect_answer(self.con, update)

                if inc_answ[0][0] == len(quest[1]) - 2:
                    bot.sendMessage(chat_id=update.message.chat_id,
                                    text='❌Неправильно\n ‼ На самом деле правильный ответ: ' + quest[0])
                    self.ask_question(bot, update, obj)

                else:
                    self.db.insert_answers(self.con, update, obj.name, 0, 1)

                    r.shuffle(quest[1])
                    ques = []
                    ques.append(quest[1])
                    ques.append(['Вернуться назад'])
                    bot.sendMessage(chat_id=update.message.chat_id, text='❌Неправильно, попробуй еще',
                                    reply_markup=ReplyKeyboardMarkup(ques, one_time_keyboard=False,
                                                                     resize_keyboard=True))

        logging.info('%s,%s' % (update.message.from_user.first_name, mes))
コード例 #25
0
ファイル: place_objects.py プロジェクト: Akhier/Py-TutMut
def place_pack(monster):
    (min, max) = packs[monster.name]
    cur_x = monster.x
    cur_y = monster.y
    failures = 0
    monsters_to_place = settings.RNG.get_int(min, max) - 1
    while monsters_to_place > 0:
        x = cur_x + settings.RNG.get_int(-1, 1)
        y = cur_y + settings.RNG.get_int(-1, 1)
        if not Object.is_blocked(x, y):
            packmonster = copy.deepcopy(monster)
            packmonster.x = x
            packmonster.y = y
            settings.objects.append(packmonster)
            cur_x = x
            cur_y = y
            monsters_to_place -= 1
            failures = 0
        else:
            failures += 1
            if failures > 10:
                cur_x = monster.x
                cur_y = monster.y
            if failures > 30:
                monsters_to_place -= 1
コード例 #26
0
ファイル: Player.py プロジェクト: elyshaffir/Textventure
    def save(self, filename):
        path = 'saves/' + filename + '/inv'
        if not os.path.exists(path):
            os.makedirs(path)
        else:
            shutil.rmtree(path)
            os.makedirs(path)
        path += '/'
        for obj in self.inv:
            obj1 = Object.Object(name=obj.name,
                                 info=obj.info,
                                 usages=obj.usages,
                                 image=obj.image_n,
                                 w=obj.w,
                                 h=obj.h)
            obj1.image = None
            self.save_by_name(path + obj1.name, obj1)

        path = 'saves/' + filename + '/rms'
        if not os.path.exists(path):
            os.makedirs(path)
        else:
            shutil.rmtree(path)
            os.makedirs(path)
        path += '/'
        self.room.save(path, True)
コード例 #27
0
    def object_handler(self, bot, update):

        mes = update.message.text
        self.stat(bot, update)

        tmp_obj = Object.get_object(self.objects, mes)
        if tmp_obj:
            obj = tmp_obj
            self.ask_question(bot, update, obj)

        self.quest_for_check = self.db.select_ques_for_user(self.con, update)
        # print(self.quest_for_check)

        if update.message.text == 'Вернуться назад':
            self.db.delete_row(self.con, update)
            #    print('type keyboard', type(self.reply_keyboard))
            #   print('reply_keyboard', self.reply_keyboard)
            self.question = None
            bot.sendMessage(chat_id=update.message.chat_id, text="Возращаю",
                            reply_markup=ReplyKeyboardMarkup(self.reply_keyboard, one_time_keyboard=True,
                                                             resize_keyboard=True))

        try:
            logging.debug(self.quest)
        except AttributeError:
            pass

        self.check_answer(mes, bot, update, self.quest_for_check)
コード例 #28
0
ファイル: Optics.py プロジェクト: SourKream/Summer-15
    def setData(self, shape_tuple, dist, ind):
        #self.data = data
        (m, n) = shape_tuple
        self.distance = dist
        self.ind = ind
        self.listOfObjects = []
        self.queue = pq.PriorityQueue()
        for i in range(0, m):
            x = Obj.Object()
            x.setIndex(i)
            core = -1
            neighbors = []
            counter = 0
            for dist in self.distance[i]:
                if (dist > self.epsilon):
                    break
                if (len(neighbors) <= self.minPts):
                    core = dist
                neighbors.append((self.ind[counter], dist))
                counter = counter + 1

            if (core != -1):
                if (len(neighbors) >= self.minPts):
                    x.setCoreDistance(core)
                x.setNeighbors(neighbors)
            self.listOfObjects.append(x)
コード例 #29
0
ファイル: Frames.py プロジェクト: hslee1539/household-ledger
 def __init__(self):
     """ 이녀석 드로우는 engine.g로 하면 안됨. 꼭 secondCanvas로 받아라"""
     self.새로만들기 = Object.iButton(Point(0, 0), Point(100, 100), Color.c1,
                                 "컨트롤박스_추가.새로만들기", "icon_new.png")
     self.저장 = Object.iButton(Point(100, 0), Point(100, 100), Color.c1,
                              "컨트롤박스_추가.저장", "icon_save.png")
     self.삭제 = Object.iButton(Point(200, 0), Point(100, 100), Color.c1,
                              "컨트롤박스_추가.삭제", "icon_delete.png")
     self.새로만들기ment = "새로 만들겠습니까?"
     self.새로만들기에러ment = "수정을 그만두고 새로 만들겠습니까?"
     self.저장ment = "저장을 하시겠습니까?"
     self.저장_다시쓰기ment = "수정 전 데이타는 삭제 되지 않습니다.\n원할 경우 먼저 삭제를 하고 저장하세요.\n삭제하지 않고 저장하겠습니까?"
     self.삭제ment = "수정전 데이타를 삭제하시겠습니까?\n(작성중인 것은 없어지지 않습니다.)"
     self.삭제에러ment = "삭제 할 것이 없습니다.\n조회 항목에서 수정버튼을 눌렀을때 해당됩니다."
     self.삭제완료ment = "삭제가 되었습니다."
     self.취소ment = "데이타 수정이 취소되었습니다.\n(작성중인것은 삭제되고, 데이타는 복원됩니다.)"
コード例 #30
0
 def getSubstr(self):
     self.str1 = self.e1.get()
     self.str2 = self.e2.get()
     startIdx = self.e3.get()
     endIdx = self.e4.get()
     o1 = Object(self.str1, startIdx, endIdx)  #3 args passed
     o2 = Object(self.str2, startIdx, endIdx)
     o1.getSubstring()
     o2.getSubstring()
コード例 #31
0
ファイル: HUD.py プロジェクト: tr1et/pygame-hittheblock
    def read_gauge(self, file):
        gauge_num = int(file.readline().strip().split(" ")[1])

        for i in range(gauge_num):
            gauge_type = file.readline().strip().replace("#", "")
            gauge_id = int(file.readline().strip().split(" ")[1])
            gauge = Object()
            gauge.init("Image", file_name=ResourceManager.image_path_list[gauge_id], alpha=True)
            gauge.translate(*map(int, file.readline().strip().split(" ")[1:]))
            gauge.rotate(float(file.readline().strip().split(" ")[1]))
            gauge.scale(*map(float, file.readline().strip().split(" ")[1:]))
            self.all_object_list.add(gauge)
            self.gauge_list.update({gauge_type: gauge})
コード例 #32
0
ファイル: HUD.py プロジェクト: tr1et/pygame-hittheblock
    def read_bar(self, file):
        bar_num = int(file.readline().strip().split(" ")[1])

        for i in range(bar_num):
            bar_type = file.readline().strip().replace("#", "")
            bar_id = int(file.readline().strip().split(" ")[1])
            bar = Object()
            bar.init("Image", file_name=ResourceManager.image_path_list[bar_id], alpha=True)
            bar.translate(*map(int, file.readline().strip().split(" ")[1:]))
            bar.rotate(float(file.readline().strip().split(" ")[1]))
            bar.scale(*map(float, file.readline().strip().split(" ")[1:]))
            self.all_object_list.add(bar)
            self.bar_list.update({bar_type: bar})
コード例 #33
0
def modelLineParse(lineLen, line):
    # Parse an object definition
    # whitespace should be previously stripped
    #NB: Python has no proper reverse search, but thats ok.
    ## Text
    end = lineLen
    start = line.find("|")
    oStr = ""
    if (start != -1):
        oStr = line[start + 1:end]
        end = start

    ## Class
    start = line.find(".", 0, end)
    oClass = ""
    if (start != -1):
        oClass = line[start + 1:end]
        end = start

    ## Struct class
    start = line.find("*", 0, end)
    sClass = ""
    if (start != -1):
        sClass = line[start + 1:end]
        end = start

    ## Id
    start = line.find("#", 0, end)
    oId = ""
    if (start != -1):
        oId = line[start + 1:end]
        end = start

    ## Type
    oType = line[:end]

    # couple of tweaks which affect attributes
    #! include selection? But not as general as these? Yet...
    oAttrs = {}
    if (oType[0] == "+"):
        oType = oType[1:]
        oAttrs["expand"] = "True"

    # str as an attribute as it niether key nor group?
    if (oStr):
        #? if (oStr[0] == "!"):
        #    oStr = oStr[1:]
        #    oAttrs["select"] = "True"
        oAttrs["text"] = oStr

    obj = Object.new(otype=oType,
                     oid=oId,
                     sClass=sClass,
                     klass=oClass,
                     oattrs=oAttrs,
                     children=[])
    #print(str(obj))

    return obj
コード例 #34
0
 def ExportTriggers(self):
     """Export all of the triggers."""
     print >> sys.stderr, "Describing triggers..."
     self.ExportObjects(
         Object.ObjectIterator(self.environment, "AllTriggers",
                               Statements.TRIGGERS,
                               "where o.owner %s" % self.schemasClause,
                               Object.Trigger))
コード例 #35
0
 def ExportViews(self):
     """Export all of the views."""
     print >> sys.stderr, "Describing views..."
     self.ExportObjects(
         Object.ObjectIterator(self.environment, "AllViews",
                               Statements.VIEWS,
                               "where o.owner %s" % self.schemasClause,
                               Object.View))
コード例 #36
0
ファイル: map_generator.py プロジェクト: desophos/roguelike
def place_objects(room):
    # make sure we don't accidentally change these
    from monster_list import bestiary
    from item_list import all_items

    #choose random number of monsters
    num_monsters = libtcod.random_get_int(0, 0, MAX_ROOM_MONSTERS)

    for i in range(num_monsters):
        #choose random spot for this monster
        x = libtcod.random_get_int(0, room.x1 + 1, room.x2 - 1)
        y = libtcod.random_get_int(0, room.y1 + 1, room.y2 - 1)

        #only place it if the tile is not blocked
        if not Object.is_blocked(x, y):
            # 80% chance of getting an orc
            if libtcod.random_get_int(0, 0, 100) < 80:
                #create an orc
                monster = bestiary["Orc"](x=x, y=y)
            else:
                #create a troll
                monster = bestiary["Troll"](x=x, y=y)

            g.actors.append(monster)

    #choose random number of items
    num_items = libtcod.random_get_int(0, 0, MAX_ROOM_ITEMS)

    for i in range(num_items):
        #choose random spot for this item
        x = libtcod.random_get_int(0, room.x1 + 1, room.x2 - 1)
        y = libtcod.random_get_int(0, room.y1 + 1, room.y2 - 1)

        #only place it if the tile is not blocked
        if not Object.is_blocked(x, y):
            dice = libtcod.random_get_int(0, 0, 100)
            if dice < 50:
                #create a healing potion (50% chance)
                item = all_items["HealingPotion"](x, y)
            else:
                # create a mana potion (50% chance)
                item = all_items["ManaPotion"](x, y)

            g.items.append(item)
            item.send_to_back()  # items appear below other objects
コード例 #37
0
ファイル: place_objects.py プロジェクト: Akhier/Py-TutMut
def place_objects(rect):
    max_monster = from_dungeon_level([[2, 1], [3, 4], [5, 6]])

    monster_chances = {}
    for key in monsters:
        monster_chances[key] = \
            from_dungeon_level(monsters[key].placement_range)

    max_items = from_dungeon_level([[1, 1], [2, 4]])

    item_chances = {}
    for key in items:
        item_chances[key] = from_dungeon_level(items[key].placement_range)

    num_monsters = settings.RNG.get_int(0, max_monster)

    for i in range(num_monsters):
        x = settings.RNG.get_int(rect.x1 + 1, rect.x2 - 1)
        y = settings.RNG.get_int(rect.y1 + 1, rect.y2 - 1)

        if not Object.is_blocked(x, y):
            choice = random_choice(monster_chances)
            monster = copy.deepcopy(monsters[choice])
            monster.x = x
            monster.y = y
            if choice in packs:
                place_pack(monster)
            settings.objects.append(monster)

    num_items = settings.RNG.get_int(0, max_items)

    for i in range(num_items):
        x = settings.RNG.get_int(rect.x1 + 1, rect.x2 - 1)
        y = settings.RNG.get_int(rect.y1 + 1, rect.y2 - 1)

        if not Object.is_blocked(x, y):
            choice = random_choice(item_chances)
            item = copy.deepcopy(items[choice])
            item.x = x
            item.y = y
            settings.objects.append(item)
            item.send_to_back()
            item.always_visible = True
コード例 #38
0
	def __init__(self, file_path):
		super(MainMenu, self).__init__()

		self.all_object_list = pygame.sprite.LayeredUpdates()
		self.background = Object()
		self.button_list = []
		self.sound_list = dict()
		self.is_mouse_hover = False
		self.current_button = None

		# Load menu's resources
		self.read_menu(file_path)
コード例 #39
0
	def __init__(self, file_path):
		super(SelectMenu, self).__init__()

		self.all_object_list = pygame.sprite.LayeredUpdates()
		self.background = Object()
		self.button_list = []
		self.sound_list = dict()
		self.is_mouse_hover = False
		self.current_button = None
		self.logo_list = []
		self.name_list = []
		self.formation_list = []
		self.Team1 = 0
		self.Formation1 = 0
		self.Team2 = 0
		self.Formation2 = 0
		self.select_team = []

		# Load menu's resources
		self.read_menu(file_path)
コード例 #40
0
ファイル: Location.py プロジェクト: d86leader/Roguelike
	def __init__(self, game):
		fighter_component = Fighter(hp=30, defense=2, power=5, death_function=self.player_death)
		self.player = Object(0, 0, '@', 'player', "white", game, blocks=True, fighter=fighter_component)
		self.objects = [self.player]
		self.map = Map(game, self)
コード例 #41
0
ファイル: master.py プロジェクト: lupo72/fumiko-pyg
def drawObjects(ALL_OBJECTS):
	for Object in ALL_OBJECTS:
		Object.draw(DISPLAYSURF)
コード例 #42
0
class MainMenu(State):
	def __init__(self, file_path):
		super(MainMenu, self).__init__()

		self.all_object_list = pygame.sprite.LayeredUpdates()
		self.background = Object()
		self.button_list = []
		self.sound_list = dict()
		self.is_mouse_hover = False
		self.current_button = None

		# Load menu's resources
		self.read_menu(file_path)

	def init(self, **kwargs):
		# Set first chosen button
		self.current_button = self.button_list[0]
		self.current_button.turn_on_highlight()

		# Set background music
		pygame.mixer.stop()
		self.sound_list['mainMenu'].play().set_endevent(pygame.constants.USEREVENT)

	def process_key_press(self, key):
		pass

	def process_events(self, event):
		if event.type == pygame.USEREVENT:
			self.sound_list['mainMenu'].play()
		elif event.type == pygame.KEYDOWN:
			if event.key == pygame.K_UP:
				button = self.button_list[(self.button_list.index(self.current_button) - 1) % len(self.button_list)]
				self.choose_button(button)
			elif event.key == pygame.K_DOWN:
				button = self.button_list[(self.button_list.index(self.current_button) + 1) % len(self.button_list)]
				self.choose_button(button)
		elif event.type == pygame.KEYUP:
			if event.key == pygame.K_RETURN:
				self.sound_list['enterSfx'].play()
				self.current_button.do_click()
		elif event.type == pygame.MOUSEBUTTONUP:
			if self.is_mouse_hover is True:
				self.current_button.do_click()

	def update(self):
		self.process_raycast()

	def draw(self, screen):
		self.all_object_list.draw(screen)

	#---------------------------------------LOGIC PROCESSING SECTION-----------------------------------------------
	def process_raycast(self):
		mouse_pos = pygame.mouse.get_pos()

		button = next((button for button in self.button_list if button.collide_point(list(map(operator.sub, mouse_pos, button.get_pos())))), None)

		if button is not None:
			self.is_mouse_hover = True
			self.choose_button(button)
		else:
			self.is_mouse_hover = False

	def choose_button(self, button):
		if self.current_button is not button:
			self.sound_list['menuSfx'].play()
			self.current_button.turn_off_highlight()
			self.current_button = button
			self.current_button.turn_on_highlight()

	#----------------------------------------READ FILE SECTION-----------------------------------------------------
	def read_menu(self, file_path):
		with open(file_path) as file:
			self.read_background(file)
			self.read_images(file)
			self.read_buttons(file)
			self.read_sound(file)

	def read_background(self, file):
		# Read background
		file.readline()
		image_id = int(file.readline().strip().split(' ')[1])
		self.background.init('Image', file_name = ResourceManager.instance().image_path_list[image_id])
		self.background.scale_to(SCREEN_WIDTH, SCREEN_HEIGHT)
		self.background.set_layer(-1)
		self.all_object_list.add(self.background)

	def read_images(self, file):
		image_num = int(file.readline().strip().split(' ')[1])

		for i in range(image_num):
			image = Object()
			file.readline()
			image_id = int(file.readline().strip().split(' ')[1])
			image.init('Image', file_name = ResourceManager.instance().image_path_list[image_id])
			image.rotate(float(file.readline().strip().split(' ')[1]))
			image.scale(*map(float, file.readline().strip().split(' ')[1:]))
			image.translate(*map(int, file.readline().strip().split(' ')[1:]))
			self.all_object_list.add(image)

	def read_buttons(self, file):
		from Button import Button
		button_num = int(file.readline().strip().split(' ')[1])

		for i in range(button_num):
			button = Button()
			button_type = file.readline().strip().replace('#', '').lower()
			image_id = list(map(int, file.readline().strip().split(' ')[1:]))
			button.init(ResourceManager.instance().image_path_list[image_id[0]], ResourceManager.instance().image_path_list[image_id[1]])
			button.rotate(float(file.readline().strip().split(' ')[1]))
			button.scale(*map(float, file.readline().strip().split(' ')[1:]))
			button.translate(*map(int, file.readline().strip().split(' ')[1:]))
			button.set_type(button_type)
			self.button_list.append(button)
			self.all_object_list.add(self.button_list)

	def read_sound(self, file):
		sound_num = int(file.readline().strip().split(' ')[1])

		for i in range(sound_num):
			sound_type = file.readline().strip().replace('#', '')
			sound_id = int(file.readline().strip().split(' ')[1])
			sound = pygame.mixer.Sound(ResourceManager.instance().sound_path_list[sound_id])
			self.sound_list.update({sound_type: sound})
コード例 #43
0
ファイル: Pyramid.py プロジェクト: mvanderkolff/navi-misc
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
from Box import Box
import Object
import Blender

try:
    pyramidMaterial = Blender.Material.Get('Pyramid')
except NameError:
    pyramidMaterial = Object.createTexture('Ground', '/usr/share/bzedit/pyrwall.png')

# FIXME - flipz
class Pyramid(Box):
    type = 'pyramid'

    verts = [( 1,  1, 0),
             (-1,  1, 0),
             (-1, -1, 0),
             ( 1, -1, 0),
             ( 0,  0, 1),
            ]

    faces = [(0, 4, 3),    # X+
             (2, 4, 1),    # X-
             (1, 4, 0),    # Y+