Exemplo n.º 1
0
	def __init__(self, tilesets, optional=None):
		self.tilesets = []
		self.pair = []
		self.pungs = []
		self.kongs = []
		self.chows = []
		self.knitted = []
		self.special = []
		self.tilecount = 0
		self.standardhand = False
		self.prevalentwind = ""
		self.seatwind = ""
		
		if optional is not None:
			#self.concealed is True if the hand is fully concealed, otherwise it's a list corresponding to the tilesets
			self.concealed = False if optional.get("concealed", None) is None else optional["concealed"]
			self.winningtile = False if optional.get("winning tile", None) is None else optional["winning tile"]
			self.flowers = 0 if optional.get("flowers", None) is None else optional["flowers"]
			self.prevalentwind = "E" if optional.get("prevalent wind", None) is None else optional["prevalent wind"]
			self.seatwind = "" if optional.get("seat wind", None) is None else optional["seat wind"]
			
		flat_list = []
		for sublist in tilesets:
			for item in sublist:
				flat_list.append(item)
		self.tilecount = len(flat_list)
	
		for i, tileset in enumerate(tilesets):
			if optional is not None and type(self.concealed) is list:
				self.tilesets.append(Tileset(tileset, self.concealed[i]))
			else:
				self.tilesets.append(Tileset(tileset))
			
		for tileset in self.tilesets:
			if tileset.type == "pair": self.pair.append(tileset)
			elif tileset.type == "pung": self.pungs.append(tileset)
			elif tileset.type == "kong": self.kongs.append(tileset)
			elif tileset.type == "chow": self.chows.append(tileset)
			elif tileset.type == "knitted": self.knitted.append(tileset)
			elif tileset.type == "special": self.special.append(tileset)
		
		standard_sets = self.kongs + self.pungs + self.chows + self.knitted
		self.standardhand = True if len(standard_sets) == 4 and len(self.pair) == 1 and len(self.special) == 0 else False
Exemplo n.º 2
0
def init():
    global goal_obstacles, allsprites, tileset, walls, obstacles, player, levelTime
    tileset = Tileset(levels[cur_level])
    walls = tileset.get_walls()
    obstacles = tileset.get_obstacles()
    player.set_walls(walls)
    player.set_obstacles(obstacles)
    player.move_to(48, 76)
    goal_obstacles = []
    for o in obstacles:
        if o.get_obs_type() == "Goal":
            goal_obstacles.append(o)
    allsprites = pygame.sprite.RenderPlain(obstacles)
    allsprites.add(player)
    levelTime = 60.0
Exemplo n.º 3
0
 def __init__(self, data):
     defaults = {
         'size': [32.0, 32.0],
         'x_offset': 0.0,
         'y_offset': 0.0,
         'tile_layer': 0,
         'tiles': [[]]
     }
     data = {**defaults, **data}
     self.tileset = Tileset(data['tileset'])
     self.name = data['name']
     self.tile_size = data['size']
     if isinstance(self.tile_size, (float, int)):
         self.tile_size = [self.tile_size, self.tile_size]
     self.offset = (data['x_offset'] * self.tile_size[0],
                    data['y_offset'] * self.tile_size[1])
     self.tile_layer_index = data['tile_layer']
     self.grid = TileGrid(data['tiles'])
Exemplo n.º 4
0
 def genWINDPIXMAPS():
     """prepare wind tiles"""
     tileset = Tileset(Preferences.windTilesetName)
     for wind in WINDS:
         for prevailing in False, True:
             pwind = PlayerWind(wind, tileset, prevailing)
             pMap = QPixmap(40, 40)
             pMap.fill(Qt.transparent)
             painter = QPainter(pMap)
             painter.setRenderHint(QPainter.Antialiasing)
             painter.scale(0.40, 0.40)
             pwind.paint(painter, QStyleOptionGraphicsItem())
             for child in pwind.childItems():
                 if isinstance(child, QGraphicsSvgItem):
                     painter.save()
                     painter.translate(child.mapToParent(0.0, 0.0))
                     child.paint(painter, QStyleOptionGraphicsItem())
                     painter.restore()
             WINDPIXMAPS[(wind, prevailing)] = pMap
Exemplo n.º 5
0
    def __init__(self, parent):
        super(TilesetSelector, self).__init__(parent)

        loadUi(self)
        self.kcfg_tilesetName = QLineEdit(self)
        self.kcfg_tilesetName.setVisible(False)
        self.kcfg_tilesetName.setObjectName('kcfg_tilesetName')

        self.tileScene = SceneWithFocusRect()
        self.tileView = FittingView()
        self.tileView.setScene(self.tileScene)
        self.tileset = Tileset(Internal.Preferences.tilesetName)
        self.uiTiles = [UITile('w' + s.char.lower()) for s in Wind.all4]
        self.board = Board(2, 2, self.tileset)
        self.board.showShadows = True
        self.tileScene.addItem(self.board)
        self.tileView.setParent(self.tilesetPreview)
        layout = QHBoxLayout(self.tilesetPreview)
        layout.addWidget(self.tileView)
        for idx, offsets in enumerate([(0, 0), (0, 1), (1, 0), (1, 1)]):
            self.uiTiles[idx].setBoard(self.board, *offsets)
            self.uiTiles[idx].focusable = False
        self.setUp()
Exemplo n.º 6
0
 def setupUi(self):
     """prepare scene"""
     # pylint: disable=too-many-statements
     self.windTileset = Tileset(Internal.Preferences.windTilesetName)
Exemplo n.º 7
0
 def setupUi(self):
     """create all other widgets
     we could make the scene view the central widget but I did
     not figure out how to correctly draw the background with
     QGraphicsView/QGraphicsScene.
     QGraphicsView.drawBackground always wants a pixmap
     for a huge rect like 4000x3000 where my screen only has
     1920x1200"""
     # pylint: disable=too-many-statements
     self.setObjectName("MainWindow")
     centralWidget = QWidget()
     self.centralView = FittingView()
     layout = QGridLayout(centralWidget)
     layout.setContentsMargins(0, 0, 0, 0)
     layout.addWidget(self.centralView)
     self.setCentralWidget(centralWidget)
     self.centralView.setFocusPolicy(Qt.StrongFocus)
     self.background = None  # just for pylint
     self.windTileset = Tileset(Internal.Preferences.windTilesetName)
     self.adjustMainView()
     self.actionScoreGame = self.kajonggAction("scoreGame", "draw-freehand",
                                               self.scoringScene, Qt.Key_C)
     self.actionPlayGame = self.kajonggAction("play", "arrow-right",
                                              self.playGame, Qt.Key_N)
     self.actionAbortGame = self.kajonggAction("abort", "dialog-close",
                                               self.abortAction, Qt.Key_W)
     self.actionAbortGame.setEnabled(False)
     self.actionQuit = self.kajonggAction("quit", "application-exit",
                                          self.close, Qt.Key_Q)
     self.actionPlayers = self.kajonggAction("players", "im-user",
                                             self.slotPlayers)
     self.actionRulesets = self.kajonggAction("rulesets",
                                              "games-kajongg-law",
                                              self.slotRulesets)
     self.actionChat = self._kajonggToggleAction("chat",
                                                 "call-start",
                                                 shortcut=Qt.Key_H,
                                                 actionData=ChatWindow)
     self.actionChat.setEnabled(False)
     self.actionAngle = self.kajonggAction("angle", "object-rotate-left",
                                           self.changeAngle, Qt.Key_G)
     self.actionAngle.setEnabled(False)
     self.actionScoreTable = self._kajonggToggleAction(
         "scoreTable",
         "format-list-ordered",
         Qt.Key_T,
         actionData=ScoreTable)
     self.actionScoreTable.setEnabled(False)
     self.actionExplain = self._kajonggToggleAction(
         "explain",
         "applications-education",
         Qt.Key_E,
         actionData=ExplainView)
     self.actionExplain.setEnabled(False)
     self.actionFullscreen = self._kajonggToggleAction("fullscreen",
                                                       "view-fullscreen",
                                                       shortcut=Qt.Key_F +
                                                       Qt.ShiftModifier)
     self.actionFullscreen.toggled.connect(self.fullScreen)
     self.actionAutoPlay = self.kajonggAction("demoMode",
                                              "arrow-right-double", None,
                                              Qt.Key_D)
     self.actionAutoPlay.setCheckable(True)
     self.actionAutoPlay.setEnabled(True)
     self.actionAutoPlay.toggled.connect(self._toggleDemoMode)
     self.actionAutoPlay.setChecked(Internal.autoPlay)
     QMetaObject.connectSlotsByName(self)
Exemplo n.º 8
0
 def set_tileset(self, path):
     try:
         newtileset = Tileset(path)
         self.tileset = newtileset
     except Exception as e:
         print(f'error creating tileset: {e}')
Exemplo n.º 9
0
    def start_element(self, name, attributes):
        if name == 'map':
            self.columns = int(attributes.get('width', None))
            self.lines = int(attributes.get('height', None))
            self.tile_width = int(attributes.get('tilewidth', None))
            self.tile_height = int(attributes.get('tileheight', None))
        elif name == 'image':  # criar um tileset
            # É possível usar mais de um conjunto de peças, mas eles devem ter tamanhos e peças idênticos.
            # chaves de cores transparentes.
            source = attributes.get('source', None)
            transp = attributes.get('trans', None)

            if self.tileset is None:
                self.tileset = Tileset(self.tile_width, self.tile_height)

            self.tileset.add_set(source, ("0x" + str(transp)))
        elif name == 'property':  # armazena propriedades adicionais.
            # adicionar às propriedades do item ou da camada, dependendo da tag pai em que estamos
            if self.in_item:
                self.items[-1].properties[attributes.get(
                    'name', None)] = attributes.get('value', None)
            else:
                self.properties[self.layers][attributes.get(
                    'name', None)] = attributes.get('value', None)
        elif name == 'layer':  # começando a contagem
            self.line = 0
            self.column = 0
            self.layers += 1
            self.properties.append({})
            self.in_item = False
        elif name == 'tile':  # obter informações de cada bloco e colocar no mapa
            # ID do arquivo para fazer referência ao conjunto de blocos
            gid = int(attributes.get('gid', None)) - 1

            if gid < 0:
                gid = 0

            self.cur_row.append(self.tileset.tiles[gid])
            self.column += 1

            if self.column >= self.columns:
                self.line += 1
                self.column = 0
                self.cur_layer.append(self.cur_row)
                self.cur_row = []

            if self.line >= self.lines:
                self.image.append(self.cur_layer)
                self.cur_layer = []
        elif name == 'object':
            # áreas de objetos podem ser pintadas em azulejo ou especificadas manualmente, como no mapa de amostra
            self.in_item = True

            x = int(attributes.get('x', None)) / self.tile_width
            y = int(attributes.get('y', None)) / self.tile_height

            if attributes.get(
                    'type', None
            ) == 'block':  # impede que itens entrem em quadrados contidos
                width = int(attributes.get('width', None)) / self.tile_width
                height = int(attributes.get('height', None)) / self.tile_height

                self.blocking.append(Rect(x, y, width, height))

            if attributes.get('type', None) == 'boulder':  # empurrável
                self.items.append(
                    item.Item(
                        sprites.Sprite('sprites/rock.png', 32, 64,
                                       (0, 198, 198)), Rect(x, y, 1, 1),
                        'boulder'))

            if attributes.get('type', None) == 'girl':
                self.items.append(
                    item.Item(
                        sprites.Sprite('sprites/girl.png', 32, 64,
                                       (0, 198, 198)), Rect(x, y, 1, 1),
                        'person'))

            if attributes.get('type', None) == 'boy':
                self.items.append(
                    item.Item(
                        sprites.Sprite('sprites/boy.png', 32, 64,
                                       (0, 198, 198)), Rect(x, y, 1, 1),
                        'person'))
Exemplo n.º 10
0
    levels_text.append("Level 1\n\nToday a freak meteor hit an orbiting space station and caused\nit to fall out of orbit. We have calculated that it will hit Boxopolis and we need\nyour help to find our best astronaut and our rocket ship. We only have\n60 seconds to get our astronaut into space before the space station is too\nclose to stop.")
    levels_text.append("Level 2\n\nThe neighboring nation of Grasslandia has just declared war on\nBoxopolis, their army is already on their way to our capital and we need you to help\nus assemble our army. We need you to find our military airships, our troops\nand the general. Their army is approaching quickly so you only have\n60 seconds before they reach our capital.")
    levels_text.append("Level 3\n\nOur scientists have recent discovered a deadly disease that has\nbeen spreading through the population of Boxopolis. Our scientists have found a\ncure, but don't have the materials necessary to produce enough for the rest of the\npopulation.It is up to you to find the materials they need. The disease is spreading\nquickly so you only have 60 seconds to help the scientists with their cure.")
    levels_text.append("Level 4\n\nThe ambassador from the local neighboring country of Bearland was on his\nway to our capital to discuss our relations as countries. His motorcade was\nlost and we need your help to find him, find our diplomat and find the materials for\nthe meeting. Relations between Bearland and Boxopolis are rocky at best and if\nthis meeting doesn't happen soon they will declare war. You only\nhave 60 seconds before they declare war.")
    levels_text.append("Level 5\n\nThe Capitol of Boxopolis is being attacked by a wild dinosaur. Our leader\nhas determined that the best way to fight this dinosaur is to use our own giant\ndinosaurs along with our fearless general in his plane. We need you to find the\ndinosaur, the plane and our general. Our capitol city is being destroyed quickly\nso you only have 60 seconds before the city is destroyed.")
    levels_text.append("Level 6\n\nOur espionage teams have recovered information that points to you being\nabducted and taken to the mad doctor's office. Our leader has a plan, but he\nneeds your help before he can put his plan into action. He needs to gather our army,\nbuilding materials and the Special Forces unit to help our leader keep you hidden\nand safe. This information doesn't point to when you will be abducted\nso our leader has decided that if you don't come back within\n60 seconds you will be presumed abducted.")
    levels_text.append("Level 7\n\nA great fire approaches the capitol city. We need your help to find our\nfire brigade to help put out the fire and our armed forces to supplement our\nfire brigade. The fire comes closer every second so you only have 60 seconds\nto put out the fire.")
    levels_text.append("Level 8\n\nOur scientists have found a meteor hurtling towards Boxopolis and we only\nhave a short amount of time to stop it. We need you to find and bring back\nour best astronauts, our rocket and something to break the meteor with. The meteor\nis getting closer at a rapid pace so you only have 60 seconds before the meteor is\ntoo close to do anything about.")
    levels_text.append("Level 9\n\nLooks like the army ants are on the move. We need to be ready in case they\nattack. They move quickly so you only have 60 seconds to find supplies of\nfood, fortification materials, and extra vehicles in case civilians need to be\nevacuated.")
    levels_text.append("Level 10\n\nThe army ants attacked and we are defenseless. We need you to do everything\nin your power to help save the capitol of Boxopolis. We need every service\nperson and vehicle we can find. We need you to find the Fire brigade, our General,\nthe Special Forces unit, the air units and our army. Good luck, you only have\n60 seconds.")
    
    levelTime = 60.0
    state = START_MENU
    goal_obstacles = []
    screen = pygame.display.set_mode((1024, 768), HWSURFACE|DOUBLEBUF)
    tileset = Tileset("../assets/maps/Level1.tmx")
    walls = []
    obstacles = []
    player = Player((32, 32), 1, lambda o: collide_obstacle(o))
    clock = pygame.time.Clock()
    
    

    allsprites = pygame.sprite.RenderPlain(obstacles)
    allsprites.add(player)
    font = pygame.font.Font(None,36)
    
    init()

    start_bg, start_rect = resources.load_image("../assets/images/bg/start.bmp")
    win_bg, win_rect = resources.load_image("../assets/images/bg/win.bmp")
Exemplo n.º 11
0
from Objects.map import Map
from names import Names
import pygame
from tileset import Tileset
from date import Date
from Objects.university import University

# Important global variables

# Object that generates human names
names = Names()
# Our pygame object
pygame = pygame
# Tileset of game graphics
tileset = Tileset(pygame, './Resources/city_tiles.png', 8, 21)
# Standard size of one tile
tile_size = 8
# How much we scale each tile
tile_scale = 2
# Current date
date = Date()
# The University
university = University()

import admissions

admissions.first_students()

from Objects.program import *

programs = {
Exemplo n.º 12
0
 def tilesetName(self, name):
     """the name of the current tileset"""
     self.tileset = Tileset(name)
Exemplo n.º 13
0
    def setupUi(self):
        """create all other widgets
        we could make the scene view the central widget but I did
        not figure out how to correctly draw the background with
        QGraphicsView/QGraphicsScene.
        QGraphicsView.drawBackground always wants a pixmap
        for a huge rect like 4000x3000 where my screen only has
        1920x1200"""
        # pylint: disable=R0915
        self.setObjectName("MainWindow")
        centralWidget = QWidget()
        scene = MJScene()
        self.centralScene = scene
        self.centralView = FittingView()
        layout = QGridLayout(centralWidget)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.centralView)
        self.tileset = None  # just for pylint
        self.background = None  # just for pylint
        self.tilesetName = Preferences.tilesetName
        self.windTileset = Tileset(Preferences.windTilesetName)

        self.discardBoard = DiscardBoard()
        self.discardBoard.setVisible(False)
        scene.addItem(self.discardBoard)

        self.selectorBoard = SelectorBoard()
        self.selectorBoard.setVisible(False)
        scene.addItem(self.selectorBoard)

        self.setCentralWidget(centralWidget)
        self.centralView.setScene(scene)
        self.centralView.setFocusPolicy(Qt.StrongFocus)
        self.adjustView()
        self.actionScoreGame = self.__kajonggAction("scoreGame",
                                                    "draw-freehand",
                                                    self.scoreGame, Qt.Key_C)
        self.actionPlayGame = self.__kajonggAction("play", "arrow-right",
                                                   self.playGame, Qt.Key_N)
        self.actionAbortGame = self.__kajonggAction("abort", "dialog-close",
                                                    self.abortAction, Qt.Key_W)
        self.actionAbortGame.setEnabled(False)
        self.actionQuit = self.__kajonggAction("quit", "application-exit",
                                               self.close, Qt.Key_Q)
        self.actionPlayers = self.__kajonggAction("players", "im-user",
                                                  self.slotPlayers)
        self.actionRulesets = self.__kajonggAction("rulesets",
                                                   "games-kajongg-law",
                                                   self.slotRulesets)
        self.actionChat = self.__kajonggToggleAction("chat",
                                                     "call-start",
                                                     shortcut=Qt.Key_H,
                                                     actionData=ChatWindow)
        game = self.game
        self.actionChat.setEnabled(
            bool(game) and bool(game.client)
            and not game.client.hasLocalServer())
        self.actionChat.setChecked(
            bool(game) and bool(game.client)
            and bool(game.client.table.chatWindow))
        self.actionScoring = self.__kajonggToggleAction(
            "scoring",
            "draw-freehand",
            shortcut=Qt.Key_S,
            actionData=ScoringDialog)
        self.actionScoring.setEnabled(False)
        self.actionAngle = self.__kajonggAction("angle", "object-rotate-left",
                                                self.changeAngle, Qt.Key_G)
        self.actionAngle.setEnabled(False)
        self.actionFullscreen = KToggleFullScreenAction(
            self.actionCollection())
        self.actionFullscreen.setShortcut(Qt.CTRL + Qt.Key_F)
        self.actionFullscreen.setShortcutContext(Qt.ApplicationShortcut)
        self.actionFullscreen.setWindow(self)
        self.actionCollection().addAction("fullscreen", self.actionFullscreen)
        self.actionFullscreen.toggled.connect(self.fullScreen)
        self.actionScoreTable = self.__kajonggToggleAction(
            "scoreTable",
            "format-list-ordered",
            Qt.Key_T,
            actionData=ScoreTable)
        self.actionExplain = self.__kajonggToggleAction(
            "explain",
            "applications-education",
            Qt.Key_E,
            actionData=ExplainView)
        self.actionAutoPlay = self.__kajonggAction("demoMode",
                                                   "arrow-right-double", None,
                                                   Qt.Key_D)
        self.actionAutoPlay.setCheckable(True)
        self.actionAutoPlay.toggled.connect(self.__toggleDemoMode)
        self.actionAutoPlay.setChecked(Internal.autoPlay)
        QMetaObject.connectSlotsByName(self)
Exemplo n.º 14
0
    def __init__(self, file_name):
        self.file_name = file_name
        self.tileset = Tileset()
        self.layers = []

        # Reading from file
        lines = None
        file = open(file_name, 'r')
        lines = file.read()
        file.close()
        lines = lines.splitlines()

        current_layer = Layer()
        in_a_layer = False
        in_a_tile = False
        is_tile_set_loaded = False

        # Parse file line by line
        for line in lines:
            if not line or line.isspace():
                continue

            # Load tileset
            if not is_tile_set_loaded and line.split(
                    '=')[0].strip() == 'tileset_file':
                self.tileset.load(TILESET_FOLDER + line.split('=')[1].strip())
                is_tile_set_loaded = True
                continue

            if line.strip() == '{':
                in_a_layer = True
                continue
            elif line.strip() == '}':
                self.layers.append(current_layer)
                current_layer = Layer()
                in_a_layer = False
                continue

            if not in_a_layer:
                continue

            if line.strip() == '[':
                in_a_tile = True
                continue
            elif line.strip() == ']':
                in_a_tile = False
                continue

            if not in_a_tile:
                # We are not in a tile but in a layer,
                # so let's parse in the properties of the layer
                parts = line.strip().split('=')

                if len(parts) != 2:
                    continue

                current_layer.set_property(parts[0].strip(), parts[1].strip())
                continue

            # Parse in a tilerow
            tile_row = [
                int(val.strip()) for val in line.strip().split(',') if val
            ]
            current_layer.tiles.append(tile_row)
Exemplo n.º 15
0
from tileset import Tileset, createTilesFromImage
import detect

path = 'data/test_random'
image_filename = 'stitch.png'

createTilesFromImage(path, image_filename)

tiles = Tileset(path,
                3,
                2,
                1024,
                1024,
                13.02,
                detection_method=detect.random,
                ext='.png')

tiles.plotHistogram('diameter')
tiles.plotDensity(1, 200)
tiles.plotRadius(1, 200)
Exemplo n.º 16
0
from tileset import Tileset
import detect

path = 'data/tiles/originals'
prep_path = 'data/images/tiled/prepped'

tiles = Tileset(path,
                cols=4,
                rows=3,
                tilew=1024,
                tileh=1024,
                scale=9.767,
                detection_method=detect.tiled)
tiles = tiles.prepTiles(prep_path, 5)

tiles.displayTileRegion(0, 3, 0, 2)
tiles.plotDensity(1, 400)

print('Yield:', round(tiles.getYield() * 100, 2), '%')

tiles.displayTileRegion(0, 3, 0, 2)

tiles.plotHistogram('diameter', bins=100)
tiles.plotBlobRegion(property='radius', colormap='viridis')

tiles.plotHistogram('distance', bins=50)
tiles.plotBlobRegion(property='distance')

tiles.plotRadialHistogram(bins=30, fontsize=10)
tiles.plotBlobRegion(property='angle')