예제 #1
0
 def __init__(self, parent = None):
     Text.__init__(self, parent)
     self.autosize = True
     self.bgColor = color.paper
     self.fontColor = color.black
     self.border = 30, 15
     self.align = 'C'
     self.visible = False
예제 #2
0
파일: button.py 프로젝트: DuhPhd/Arkanoid
 def __init__(self, *args, **kwargs):
     kwargs['color'] = BUTTON_FONTCOLOR
     kwargs['fontsize'] = BUTTON_FONTSIZE
     kwargs['fontname'] = BUTTON_FONTNAME
     Text.__init__(self, *args, **kwargs)
     self.highlighted = False
     self.angle = 0
     self.scale = 1
     self.rotdir = BUTTON_SPEED # speed and direction of rotation
예제 #3
0
    def run(self):
        if self.args['--debug']:
            if self.nostem:
                with open(self.nostem) as f:
                    nostem_words = set(f.read().splitlines())
            else:
                nostem_words = []

            for term in self.terms:
                if not term in nostem_words and term != Text.show_stem(term):
                    self.debug.print_debug(self, u'{0} will be stemmed to {1}'.format(term, Text.show_stem(term)))
                else:
                    self.debug.print_debug(self, u'{0} will not be stemmed'.format(term))

            if self.action == 'group':
                for term in self.second_terms:
                    if not term in nostem_words:
                        self.debug.print_debug(self, u'{0} will be stemmed to {1}'.format(term, Text.show_stem(term)))
                    else:
                        self.debug.print_debug(self, u'{0} will not be stemmed'.format(term))

        file_list = listdir(self.in_dir)

        for file_name in file_list:
            if file_name.endswith(".txt"):
                self.plot(file_name)
예제 #4
0
 def adopt(self, at_time=None):
     from text import Text
     if at_time is None:
         at_time = datetime.utcnow()
     if not self.is_adopt_polling():
         return
     for selection in self.selections:
         selected = selection.selected
         if selected is None or selected == Text.HEAD:
             continue
         if not selected in selection.page.variants:
             continue
         source_text = selection.page.variant_at(selected,
                                                 self.adopt_poll.begin_time)
         dest_text = Text.create(selection.page,
                                 Text.HEAD,
                                 source_text.user,
                                 selection.page.head.title,
                                 source_text.text,
                                 parent=source_text,
                                 wiki=source_text.wiki)
         dest_text.create_time = at_time
     self.adopted = True
     meta.Session.commit()
     self.adopt_poll.end(at_time)
     meta.Session.flush()
예제 #5
0
파일: game.py 프로젝트: LordHamu/RunNGun
 def add_button(self, button_text, x, y, w, h, ic, ac, action=None):
     button_rect = pygame.Rect(x,y,w,h)
     button_surface = pygame.Surface((w,h))
     
     self.ui_list.append({'title':button_text, 'type':'button', 'ac':ac, 'ic':ic, 'action':action, 'rectangle':button_rect})
     textSurf, textRect = Text.text_objects(button_text, constants.smallText, constants.BLACK)
     textRect.center = ( (x+(w/2)), (y+(h/2)) )
     self.ui_list.append({'title':button_text,'type':'button_text','surface':textSurf, 'rectangle':textRect})
예제 #6
0
 def __init__(self, parent = None):
     Text.__init__(self, parent)
     PressBase.__init__(self)
     self.tabStop = 1000
     self.blind = False        
     self.margin = 0, 0, 0, 0
     
     self.index = -1
     self.__data = List()
     self.autoRemove( self.data.bind('Change', self.invoke, 'Data Changed', postevent = False) )
     
     self.menuStyle = None
     self.itemStyle = None
     
     self.changeEvent('index', self.__onChangeSelect, postevent = False, sync = True)
     self.changeEvent('text', self.__onTextChanged, postevent = False, sync = True)
     self.bind('Data Changed', self.__onDataChanged, postevent = False)
     self.bind('Click', self.__onCombolist)
예제 #7
0
class Anchor(object):

    def __init__(self, anc_way, settings={}):
        if anc_way == 'text':
            from text import Text as Record
        self.anchor = Record(settings)

    def has(self, filename):
        """Check encrypt file name."""
        return self.anchor.has(filename)

    def load_cur(self, filename):
        """Load current encrypted filename"""
        return self.anchor.load_cur(filename)

    def change(self, org, dst):
        """Change anchor"""
        self.anchor.change(org, dst)
예제 #8
0
파일: menu.py 프로젝트: LordHamu/RunNGun
 def draw_menu(self):
     menu = []
     #add the menu options
     for x in range(len(self.level_list)):
         text = self.level_list[x]
         TextSurf, TextRect = Text.text_objects(text, constants.menuText,
                                                constants.WHITE)
         TextRect.center = ((constants.DWIDTH / 4), (100+(x*50)))
         menu.append({'title': text, 'type':'menu',
                      'surface':TextSurf, 'rectangle': TextRect})
     #add the menu icon
     #IconRect = Rect((constants.DWIDTH*.75), (constants.DHEIGHT/4), 100, 100)
     #menu.append({'type':'icon', 'title':'Level_Icon', 'rectangle':IconRect})
     return menu
예제 #9
0
    def plot(self, file_name):
        self.debug.print_debug(self, u'Loading ' + file_name)
        textplot = Text.from_file(join(self.in_dir, file_name), self.debug, nostem=self.nostem)

        self.debug.print_debug(self, u'Plotting ' + file_name)
        if self.action == 'single':
            graph = textplot.plot_terms(self.terms, self.caption)

        elif self.action == 'group':
            graph = textplot.plot_terms_two_groups(self.terms, self.term_name, self.second_terms,self.second_term_name, self.caption)

        elif self.action == 'hist':
            graph = textplot.plot_terms_histogram(self.terms, self.caption, 5000)
        elif self.action == 'rawcount':
            graph = textplot.plot_terms_raw_count(self.terms, self.caption, 5000)

        self.debug.print_debug(self, u'Saving ' + file_name.replace('.txt', '.png'))
        graph.savefig(join(self.in_dir, file_name.replace('.txt', '.png')))

        graph.close()
예제 #10
0
    def plot(self, file_name):
        self.debug.print_debug(self, u'Loading ' + file_name)

        textplot = Text.from_file(join(self.in_dir, file_name), self.debug, nostem=self.nostem)

        self.debug.print_debug(self, u'Plotting ' + file_name)

        if self.action == 'single':
            graph = textplot.plot_terms(self.terms, self.caption)

        elif self.action == 'group':
            graph = textplot.plot_terms_two_groups(self.terms, self.term_name, self.second_terms,self.second_term_name, self.caption)

        elif self.action == 'hist':
            graph = textplot.plot_terms_histogram(self.terms, self.caption, self.words)

        elif self.action == 'rawcount':
            graph = textplot.plot_terms_raw_count(self.terms, self.caption, self.words)

        elif self.action == 'overlap':
            graph = textplot.plot_kde_overlap(self.terms)

        elif self.action == 'search':
            newterms = textplot.anchored_scores(self.terms[0])

            count = 0
            self.debug.print_(self, u'Top twenty correlated terms (with more than one occurrence) for {0}: '.format(self.terms[0]))

            for item in newterms:
                if len(textplot.terms[item]) > 1 and item != textplot.stem(self.terms[0]):
                    if count > self.max:
                        break

                    self.debug.print_(self, item)
                    count += 1

        if self.action != 'search':
            self.debug.print_debug(self, u'Saving ' + file_name.replace('.txt', '.png'))

            graph.savefig(join(self.in_dir, file_name.replace('.txt', '.png')))
            graph.close()
예제 #11
0
def fridge_point_click():
    click_time = datetime.datetime.now()
    try:
        user = users.get_current_user()
        if (not user):
            return json.dumps(
                {"error": True, "errorMessage": "User not logged in."})

        current_fridge_entity = get_current_fridge_entity()

        if (current_fridge_entity.state == 1):
            total_points = increment_user_point(user, current_fridge_entity)

            if (total_points is not None):
                return json.dumps({"error": False, "points": total_points})
            else:
                return json.dumps({"error": True,
                                   "errorMessage": Text.get(Text.ALREADY_GOT_POINT),
                                   "time": str(click_time)})
        else:
            return json.dumps(
                {"error": True, "errorMessage": "Fridge is closed :("})
    except Exception as e:
        return process_exception(e)
        r = int(r/len(color_list[2]))
        g = int(g / len(color_list[2]))
        b = int(b / len(color_list[2]))
        color_list[2] = [r, g, b]
    else:
        continue

picture = Image.new("RGB", (400, 1000), "white")

for text_info in first_list:
    text = Text(text_info[0], text_info[1]*5, tuple(text_info[2]), "Fonts/Capture_it.ttf", 255)

for text in Text.text_object_list:
    text.calculate_length(picture)

Text.order_list()
for text in Text.ordered_list:
    text.findPlace_halfPyramid()

how_high = Text.ordered_list[-1].y + Text.ordered_list[-1].size
how_wide = Text.ordered_list[0].length

picture = Image.new("RGB", (how_wide, how_high), "white")

for text in Text.ordered_list:
    picture = text.place(picture)

title = Text("Porn_Stars", 40, (255, 0, 0), "Fonts/Capture_it.ttf", 255)
title.calculate_length(picture)
title.x = how_high - title.length
title.y = 0
예제 #13
0
파일: star.py 프로젝트: coltonjcox30/cs1410
 def __init__(self, width, height):
     self.mWidth = width
     self.mHeight = height
     self.mColor = (255, 255, 255)
     self.mText = Text("", width / 2, 425)
     return
예제 #14
0
import unittest
from filter import Filter
from text import Text

filter = Filter()
text = Text()


class TextTestSuite(unittest.TestCase):
    def setUp(self):
        self.case = []

        self.case.append({
            'text': 'hello boy just hello',
            'target': 'simple hello boy',
            'cross': {
                'hello': 1,
                'boy': 1,
            }
        })

        self.case[0]['frequency'] = filter.frequency(self.case[0]['text'])

    def test_text_search_fail(self):
        self.assertEqual(text.search(), {})

    def test_text_search_ocurrencies(self):
        self.assertEqual(
            text.search(self.case[0]['frequency'], self.case[0]['target']),
            self.case[0]['cross'])
예제 #15
0
 def set_text(self, text):
     """
     """
     self.box.remove(self.text)
     self.text = Text(config.category_overlay_font, text)
     self.box.add(self.text)
예제 #16
0
import pygame

from game import Gui
from control import Control

from text import Text

pygame.init()
widtWindow = 768
heigWindow = 512
window = pygame.display.set_mode((widtWindow, heigWindow))
pygame.display.set_caption("ПОБЕДА")

controler = Control()
images = Gui()
score = Text((0, 255, 255), "impact.ttf", 50)


def showVictory():
    victoryWindow = pygame.image.load("image/victory.png")
    victoryWindow = pygame.transform.scale(victoryWindow, (1280, 720))

    window.blit(victoryWindow, (0, 0))
예제 #17
0
# Instantiate all objects and append into object lists drawables and blocks
drawables = []
blocks = []

newBall = Ball(10, 350, (255, 0, 0))
newBlock1 = Block(300, 320, (0, 0, 255))
newBlock2 = Block(300, 330, (0, 0, 255))
newBlock3 = Block(300, 340, (0, 0, 255))
newBlock4 = Block(310, 320, (0, 0, 255))
newBlock5 = Block(310, 330, (0, 0, 255))
newBlock6 = Block(310, 340, (0, 0, 255))
newBlock7 = Block(320, 320, (0, 0, 255))
newBlock8 = Block(320, 330, (0, 0, 255))
newBlock9 = Block(320, 340, (0, 0, 255))
newText = Text('Score: 0', 0, 0, (0, 0, 0))
resetText = Text('Press r to reset ball', 250, 0, (0, 0, 0))
quitText = Text('Press q to quit game', 250, 10, (0, 0, 0))

drawables.append(newBall)
drawables.append(newBlock1)
drawables.append(newBlock2)
drawables.append(newBlock3)
drawables.append(newBlock4)
drawables.append(newBlock5)
drawables.append(newBlock6)
drawables.append(newBlock7)
drawables.append(newBlock8)
drawables.append(newBlock9)
drawables.append(newText)
drawables.append(resetText)
예제 #18
0

  # yaml config file
  cfg = yaml.safe_load(open("../config.yaml"))

  # grid
  pixel_size = (20, 20)

  # init pygame
  pygame.init()

  # init display
  screen = pygame.display.set_mode(cfg['game']['screen_size'])

  # collection of game colors
  text = Text(screen)


  # level creation
  levels = [LevelThings(screen, cfg['game']['screen_size']), Level_01(screen, cfg['game']['screen_size'])]

  # choose level
  level = levels[0]

  # game logic with dependencies
  game_logic = ThingsGameLogic(level, levels, text)

  # add clock
  clock = pygame.time.Clock()

예제 #19
0
import pygame, sys
from pygame.locals import *
from animated_sprite import AnimatedSprite
from sprite_config import SpriteConfig
from text import Text
pygame.init()

KIRBY_SPRITE_SHEET = pygame.image.load("kirby_sprite_sheet_with_gun_fixed.png")
ZOMBIE_SPRITE_SHEET = pygame.image.load('zombie_spritesheet_2.png')
# KIRBY_SPRITE_SHEET.set_colorkey((255, 255, 255), pygame.RLEACCEL)
# KIRBY_SPRITE_SHEET = KIRBY_SPRITE_SHEET.convert_alpha()
CLOCK = pygame.time.Clock()
FPS = 30
TIME = 0
T = Text()

K_WIDTH = KIRBY_SPRITE_SHEET.get_width()
K_HEIGHT = KIRBY_SPRITE_SHEET.get_height()
Z_WIDTH = ZOMBIE_SPRITE_SHEET.get_width()
Z_HEIGHT = ZOMBIE_SPRITE_SHEET.get_height()

WIDTH = 400
HEIGHT = 400
UI_SIZE = 50
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
SCREEN.fill((255, 255, 255))
SCREEN.blit(KIRBY_SPRITE_SHEET, (0, 0))

###image configurations
attack = SpriteConfig(
예제 #20
0
    def __init__(self, *args, **kwargs):
        """Creates a cell object

        :param: Text can be Text object or string

        :param header: A flag to indicate if the cell should be treated as
            a header cell. Depending on the ouput format cells may be rendered
            differently e.g. with bold text.
        :type header: bool

        :param span: The number of columns this cell should span. If not
            specified it will span 1 column only. Note that if the renderer
            does not support column spanning this option will be ignored.
        :type span: int

        :param align: A flag to indicate if special alignment should
            be given to cells if supported in the output renderer.
            Valid options are: None, 'left', 'right', 'center'
        :type align: basestring

        :param wrap_slash: Whether to replace slashes with the slash plus the
            html <wbr> tag which will help to e.g. wrap html in small cells if
            it contains a long filename. Disabled by default as it may cause
            side effects if the text contains html markup. Only affects
            to_html calls.
        :type wrap_slash: bool

        We pass the kwargs on to the base class after first removing the
        kwargs that we explicitly expect here so an exception is raised
        if invalid keywords were passed. See:

        http://stackoverflow.com/questions/13124961/
        how-to-pass-arguments-efficiently-kwargs-in-python
        """
        # First check if we get a header keyword arg. If we do we will
        # Format each cell with important_text, th or whatever is appropriate.
        self.header_flag = False
        if 'header' in kwargs:
            self.header_flag = kwargs['header']
            # dont pass the kw on to the base class as we handled it here
            kwargs.pop('header')

        # Also check for column spanning
        self.span = 1
        if 'span' in kwargs:
            self.span = kwargs['span']
            # dont pass the kw on to the base class as we handled it here
            kwargs.pop('span')

        # Also check if align parameter is called before calling the ABC
        self.align = None
        if 'align' in kwargs:
            if kwargs['align'] in [None, 'left', 'right', 'center']:
                self.align = kwargs['align']
            # dont pass the kw on to the base class as we handled it here
            kwargs.pop('align')

        # Check if slashes should be wrapped for html
        self.wrap_slash = False
        if 'wrap_slash' in kwargs:
            self.wrap_slash = kwargs['wrap_slash']
            # don't pass the kw on to the base class as we handled it here
            kwargs.pop('wrap_slash')

        super(Cell, self).__init__(**kwargs)

        # Special case for when we want to put a nested table in a cell
        # We don't use isinstance because of recursive imports with table
        class_name = args[0].__class__.__name__
        if class_name in ['BulletedList', 'Table', 'Message']:
            self.content = args[0]
        else:
            self.content = Text(*args)
예제 #21
0
    def ShowBurning(self, status="burning.."):
        """show burning info"""

        t = Text(status, 24, 500, 35, ORANGE)
        burninfo = t.Show()
        self.image.blit(burninfo, (0, 90))
예제 #22
0
 def test_find_one_char_key(self):
     crypto_ch3_feed = ByteArray.from_hex("1b37373331363f78151b7f2b783431333d"
                                          "78397828372d363c78373e783a393b3736")
     crypto_ch3_solution = "Pbbxvat ZP'f yvxr n cbhaq bs onpba".decode("rot13") # no plain-text for u
     found = crypto_ch3_feed ^ Text.find_one_char_key(crypto_ch3_feed)
     self.assertEqual(found, crypto_ch3_solution)
예제 #23
0
 def test_byte_array_to_lower(self):
     self.assertEqual(Text.byte_array_to_lower(ByteArray(HELLO_WORLD)),
                      HELLO_WORLD.lower())
예제 #24
0
        if (drawable.getVisibility()):

            # Check if drawable is Block to check for collision with ball
            if (isinstance(drawable, Block)):
                ballObject = drawables[2]
                ball_rect = ballObject.get_rect()
                block_rect = drawable.get_rect()

                # Check if Block object intersects with ball objeect
                if (intersect(ball_rect, block_rect)):

                    # Handle intersection (collision) between ball and block
                    drawable.setVisibility(False)
                    # Increment score by 1 per collision
                    score += 1
                    drawables[3] = Text(10, 10, "Score: " + str(score),
                                        colorWhite, 24)
                else:
                    # Drawable Block did not intersect with ball
                    drawable.draw(surface)
            else:
                # Drawable is not a Block, draw w/o checking for collision
                drawable.draw(surface)

    pygame.display.update()

    # Handle game events
    for event in pygame.event.get():
        # Quit Game
        if (event.type
                == pygame.QUIT) or (event.type == pygame.KEYDOWN
                                    and event.__dict__['key'] == pygame.K_q):
예제 #25
0
파일: playfair.py 프로젝트: zgthompson/sp14
 def __init__(self, text, key):
     super(Playfair, self).__init__(text)
     self.key = self.create_key( Text.only_letters(key) )
     self.text = self.text.replace('j', 'i')
예제 #26
0
    def __init__(self):
        self.player_name = 'PL1'

        self.WHITE = (255, 255, 255)
        self.GREEN = (78, 255, 87)
        self.YELLOW = (241, 255, 0)
        self.BLUE = (80, 255, 239)
        self.PURPLE = (203, 0, 255)
        self.RED = (237, 28, 36)

        self.BASE_PATH = abspath(dirname(__file__)) + '/assets'
        self.IMAGE_PATH = self.BASE_PATH + '/images/'
        self.SOUND_PATH = self.BASE_PATH + '/sounds/'
        self.DATA_PATH = self.BASE_PATH + '/data/'

        self.high_score_datafile = self.DATA_PATH + 'highscores.json'

        self.tick_rate = 60

        # Screen settings.
        self.screen_width = 1200
        self.screen_height = 800
        self.bg_color = (49, 51, 53)

        # Text Settings
        self.text_color = (255, 255, 255)
        self.alt_text_color = (0, 255, 0)
        self.font_size = 48

        self.titleText = Text(None, 50, 'Space Invaders', self.WHITE, 164, 155)
        self.titleText2 = Text(None, 25, 'Press any key to continue', self.WHITE,
                               201, 225)
        self.gameOverText = Text(None, 50, 'Game Over', self.WHITE, 250, 270)
        self.nextRoundText = Text(None, 50, 'Next Round', self.WHITE, 240, 270)
        self.enemy1Text = Text(None, 25, '   =   10 pts', self.GREEN, 368, 270)
        self.enemy2Text = Text(None, 25, '   =  20 pts', self.BLUE, 368, 320)
        self.enemy3Text = Text(None, 25, '   =  30 pts', self.PURPLE, 368, 370)
        self.enemy4Text = Text(None, 25, '   =  ?????', self.RED, 368, 420)

        # Button settings
        self.btn_color = (0, 255, 0)
        self.btn_w = 200
        self.btn_h = 50

        # Bunker settings
        self.bunker_size_h = 10
        self.bunker_size_w = 15
        self.bunker_color = (0, 255, 0)
        self.destruction_factor = 2
        self.bunker_rows = 5
        self.bunker_cols = 9

        # Ship settings.
        self.ship_image = self.IMAGE_PATH + 'spaceship.png'
        self.ship_explosions = [self.IMAGE_PATH +
                                'ship_explosion1.png',
                                self.IMAGE_PATH + 'ship_explosion2.png',
                                self.IMAGE_PATH + 'ship_explosion3.png',
                                self.IMAGE_PATH + 'ship_explosion4.png',
                                self.IMAGE_PATH + 'ship_explosion5.png',
                                self.IMAGE_PATH + 'ship_explosion6.png',
                                self.IMAGE_PATH + 'ship_explosion7.png',
                                self.IMAGE_PATH + 'ship_explosion8.png']
        self.ship_explosion_time = 200
        self.ship_limit = 3

        # Bullet settings.
        self.bullet_width = 5
        self.bullet_height = 15
        self.bullet_color = 255, 48, 65
        self.bullets_allowed = 3

        # Alien Lazer setting
        self.laser_width = 5
        self.laser_height = 10
        self.laser_color = 65, 48, 255
        self.lasers_allowed = 1
        self.laser_stamp = None
        self.laser_time = 1000

        # Alien settings.
        self.ufo_image = self.IMAGE_PATH + 'UFO.png'

        self.alien_explosions = {
            'classic': [self.IMAGE_PATH + 'purple_explosion1.png',
                        self.IMAGE_PATH + 'purple_explosion2.png',
                        self.IMAGE_PATH + 'purple_explosion3.png',
                        self.IMAGE_PATH + 'purple_explosion4.png'],
            'ghost': [self.IMAGE_PATH + 'blue_explosion1.png',
                      self.IMAGE_PATH + 'blue_explosion2.png',
                      self.IMAGE_PATH + 'blue_explosion3.png',
                      self.IMAGE_PATH + 'blue_explosion4.png'],
            'creeper': [self.IMAGE_PATH + 'green_explosion1.png',
                        self.IMAGE_PATH + 'green_explosion2.png',
                        self.IMAGE_PATH + 'green_explosion3.png',
                        self.IMAGE_PATH + 'green_explosion4.png']
        }
        self.alien_classic1 = self.IMAGE_PATH + 'alien-classic-frame1.png'
        self.alien_classic2 = self.IMAGE_PATH + 'alien-classic-frame2.png'
        self.alien_creep1 = self.IMAGE_PATH + 'alien-creep-frame1.png'
        self.alien_creep2 = self.IMAGE_PATH + 'alien-creep-frame2.png'
        self.alien_ghost1 = self.IMAGE_PATH + 'alien-ghost-frame1.png'
        self.alien_ghost2 = self.IMAGE_PATH + 'alien-ghost-frame2.png'
        self.alien_squid1 = self.IMAGE_PATH + 'alien-squid-frame1.png'
        self.alien_squid2 = self.IMAGE_PATH + 'alien-squid-frame2.png'
        self.alien_image_names = {
            'classic': [self.alien_classic1, self.alien_classic2],
            'ghost': [self.alien_ghost1, self.alien_ghost2],
            'creeper': [self.alien_creep1, self.alien_creep2]
        }
        # time in ms
        self.alien_animate_time = 1000
        self.alien_animate_expl_time = 50

        self.fleet_drop_speed = 10
        self.alien_points = {
            'classic': 10,
            'ghost': 20,
            'creeper': 40
        }
        self.ufo_point_values = [100, 200, 300]
        self.last_ufo = None
        self.ufo_spawn_time = 10000
        self.num_alien_rows = 5
        # fleet_direction of 1 represents right, -1 represents left.
        self.fleet_direction = 1

        # init speed settings
        # Windows
        # self.ship_speed_factor = 1.5
        # self.bullet_speed_factor = 3
        # self.laser_speed_factor = 3
        # self.alien_speed_factor = 1
        # self.base_alien_speed = 1.5

        # MAC
        self.ship_speed_factor = 7
        self.bullet_speed_factor = 15
        self.laser_speed_factor = 10
        self.alien_speed_factor = 5
        self.base_alien_speed = 5
        self.alien_speed_limit = None
        self.alien_base_limit = None
        self.ufo_speed = None

        # How quickly the game speeds up.
        self.speedup_scale = 1.1
        # How quickly the alien point values increase.
        self.score_scale = 1.5

        self.initialize_dynamic_settings()
예제 #27
0
from picture import Picture
from line import Line
from rectangle import Rectangle
from text import Text

if __name__ == "__main__":
    graphic = Picture()
    graphic.add(Line())
    graphic.add(Rectangle())

    graphic_sub = Picture()
    graphic_sub.add(Text())
    graphic_sub.add(Line())
    graphic_sub.add(Rectangle())

    graphic.add(graphic_sub)
    graphic.add(Line())

    graphic.draw()
예제 #28
0
    def __init__(self, gameDisplay):
        self.__gameDisplay = gameDisplay

        self.__completePlaylist = Playlist("")  #Radio Contact
        self.__completePlaylistNoAds = Playlist("", False)
        self.__balkanikFM = Playlist(MusicPlayer.BALKANIK_FM_LOCATION)
        self.__kitschFM = Playlist(MusicPlayer.KITSCH_FM_LOCATION)
        self.__MP3Player = Playlist(MusicPlayer.MP3_PLAYER_LOCATION)
        self.__radioChangingSound = SoundCue(
            MusicPlayer.RADIO_CHANGING_SOUND_LOCATION)

        self.__radioContactImage = self.__loadSpecialImage(
            MusicPlayer.RADIO_CONTACT_IMAGE)
        self.__radioContactNoAdsImage = self.__loadSpecialImage(
            MusicPlayer.RADIO_CONTACT_NO_ADS_IMAGE)
        self.__balkanikFMImage = self.__loadSpecialImage(
            MusicPlayer.BALKANIK_FM_IMAGE)
        self.__kitschFMImage = self.__loadSpecialImage(
            MusicPlayer.KITSCH_FM_IMAGE)
        self.__MP3PlayerImage = self.__loadSpecialImage(
            MusicPlayer.MP3_PLAYER_IMAGE)

        self.__radioStationList = [
            (self.__completePlaylist, self.__radioContactImage),
            (self.__completePlaylistNoAds, self.__radioContactNoAdsImage),
            (self.__balkanikFM, self.__balkanikFMImage),
            (self.__kitschFM, self.__kitschFMImage),
            (self.__MP3Player, self.__MP3PlayerImage)
        ]

        self.__currentPlaylistIndex = 0
        self.__musicVolume = Constants.NORMAL_VOLUME

        previousSongButtonText = Text("<", MusicPlayer.TEXT_FONT,
                                      MusicPlayer.TEXT_FONT_SIZE,
                                      MusicPlayer.TEXT_COLOR)
        self.__previousSongButton = Button(
            MusicPlayer.MUSIC_PLAYER_BUTTON_TOP,
            MusicPlayer.MUSIC_PLAYER_BUTTON_LEFT,
            MusicPlayer.MUSIC_PLAYER_BUTTON_SIZE,
            MusicPlayer.MUSIC_PLAYER_BUTTON_SIZE,
            MusicPlayer.MUSIC_PLAYER_BUTTON_COLOR, previousSongButtonText)
        pauseSongButtonText = Text("||", MusicPlayer.TEXT_FONT,
                                   MusicPlayer.TEXT_FONT_SIZE,
                                   MusicPlayer.TEXT_COLOR)
        self.__pauseSongButton = Button(
            MusicPlayer.MUSIC_PLAYER_BUTTON_TOP,
            MusicPlayer.MUSIC_PLAYER_BUTTON_LEFT +
            MusicPlayer.MUSIC_PLAYER_BUTTON_GAP_SIZE +
            MusicPlayer.MUSIC_PLAYER_BUTTON_SIZE,
            MusicPlayer.MUSIC_PLAYER_BUTTON_SIZE,
            MusicPlayer.MUSIC_PLAYER_BUTTON_SIZE,
            MusicPlayer.MUSIC_PLAYER_BUTTON_COLOR, pauseSongButtonText)
        nextSongButtonText = Text(">", MusicPlayer.TEXT_FONT,
                                  MusicPlayer.TEXT_FONT_SIZE,
                                  MusicPlayer.TEXT_COLOR)
        self.__nextSongButton = Button(
            MusicPlayer.MUSIC_PLAYER_BUTTON_TOP,
            MusicPlayer.MUSIC_PLAYER_BUTTON_LEFT +
            2 * MusicPlayer.MUSIC_PLAYER_BUTTON_GAP_SIZE +
            2 * MusicPlayer.MUSIC_PLAYER_BUTTON_SIZE,
            MusicPlayer.MUSIC_PLAYER_BUTTON_SIZE,
            MusicPlayer.MUSIC_PLAYER_BUTTON_SIZE,
            MusicPlayer.MUSIC_PLAYER_BUTTON_COLOR, nextSongButtonText)
        previousRadioStationText = Text("R-", MusicPlayer.TEXT_FONT,
                                        MusicPlayer.TEXT_FONT_SIZE,
                                        MusicPlayer.TEXT_COLOR)
        self.__previousRadioStationButton = Button(
            MusicPlayer.CHANGE_RADIO_STATION_TOP,
            MusicPlayer.PREV_RADIO_STATION_LEFT,
            MusicPlayer.CHANGE_RADIO_STATION_WIDTH,
            MusicPlayer.CHANGE_RADIO_STATION_HEIGHT,
            MusicPlayer.MUSIC_PLAYER_BUTTON_COLOR, previousRadioStationText)
        nextRadioStationText = Text("R+", MusicPlayer.TEXT_FONT,
                                    MusicPlayer.TEXT_FONT_SIZE,
                                    MusicPlayer.TEXT_COLOR)
        self.__nextRadioStationButton = Button(
            MusicPlayer.CHANGE_RADIO_STATION_TOP,
            MusicPlayer.NEXT_RADIO_STATION_LEFT,
            MusicPlayer.CHANGE_RADIO_STATION_WIDTH,
            MusicPlayer.CHANGE_RADIO_STATION_HEIGHT,
            MusicPlayer.MUSIC_PLAYER_BUTTON_COLOR, nextRadioStationText)
        self.__volumeBarButton = Button(MusicPlayer.VOLUME_BAR_TOP,
                                        MusicPlayer.VOLUME_BAR_LEFT,
                                        MusicPlayer.VOLUME_BAR_WIDTH,
                                        MusicPlayer.VOLUME_BAR_HEIGHT,
                                        MusicPlayer.MUSIC_PLAYER_BUTTON_COLOR,
                                        None)
예제 #29
0
파일: levelscene.py 프로젝트: morganq/4x2d
    def add_ui_elements(self):
        self.meters = {}
        self.upgrade_texts = {}
        for i, r in enumerate(self.player_civ.resources.data.keys()):
            self.meters[r] = Meter(V2(19, 3 + i * 14),
                                   120,
                                   9,
                                   RESOURCE_COLORS[r],
                                   self.player_civ.upgrade_limits.data[r],
                                   tick_x=120)
            self.meters[r].stay = True
            self.ui_group.add(
                simplesprite.SimpleSprite(V2(6, 2 + i * 14),
                                          "assets/i-%s.png" % r))
            self.ui_group.add(self.meters[r])
            self.upgrade_texts[r] = Text("",
                                         "small",
                                         V2(144, 4 + i * 14),
                                         multiline_width=200)
            self.ui_group.add(self.upgrade_texts[r])

        self.player_civ.resources.on_change(self.on_civ_resource_change)

        # Set up blueprint and memory crystal buttons
        self.saved_upgrade_buttons = {}
        upy = 50

        def make_reward_icon(frame, h):
            img = FrameSprite(V2(3, upy), "assets/reward_icons.png", 23)
            img.frame = frame
            self.ui_group.add(img)
            self.ui_group.add(
                Line(V2(2, upy + 12), V2(7, upy + 12), PICO_YELLOW))
            self.ui_group.add(
                Line(V2(2, upy + 11), V2(2, upy + h), PICO_YELLOW))

        if self.game.run_info.saved_technologies:
            make_reward_icon(
                2,
                len(self.game.run_info.saved_technologies) * 27 + 17)
            upy += 17
            for u in self.game.run_info.saved_technologies:
                upicon = UpgradeIcon(V2(3, upy),
                                     u,
                                     self.on_click_saved_upgrade,
                                     tooltip=True)
                self.saved_upgrade_buttons[u] = upicon
                self.ui_group.add(upicon)
                upy += 27

        if self.game.run_info.blueprints:
            upy += 10
            make_reward_icon(3, len(self.game.run_info.blueprints) * 27 + 17)
            upy += 17
            for u in self.game.run_info.blueprints:
                upicon = UpgradeIcon(V2(3, upy),
                                     u,
                                     self.on_click_saved_upgrade,
                                     tooltip=True)
                self.saved_upgrade_buttons[u] = upicon
                self.ui_group.add(upicon)
                upy += 27

        if game.DEV:
            self.ui_group.add(
                Button(
                    V2(self.game.game_resolution.x - 50,
                       self.game.game_resolution.y - 20), 'Win', 'small',
                    self.dev_win))
            self.ui_group.add(
                Button(
                    V2(self.game.game_resolution.x - 110,
                       self.game.game_resolution.y - 20), 'Lose', 'small',
                    self.dev_lose))

        self.player_ship_info = CivShipUI(
            V2(self.game.game_resolution.x - 70, 24), self.player_civ)
        #self.ui_group.add(self.player_ship_info)

        self.player_pop_info = text.Text("Ships: 0/0",
                                         "small",
                                         V2(self.game.game_resolution.x - 6,
                                            24),
                                         PICO_WHITE,
                                         shadow=PICO_BLACK)
        self.player_pop_info.offset = (1, 0)
        self.ui_group.add(self.player_pop_info)

        self.o2_meter = o2meter.O2Meter(V2(self.game.game_resolution.x - 86,
                                           6))

        if self.options == "oxygen":
            self.game.run_info.o2 = 0

        self.o2_meter.o2 = self.game.run_info.o2
        self.o2_meter._generate_image()
        self.ui_group.add(self.o2_meter)

        self.stage_name = stagename.StageName(V2(0, 100), self.stage_num,
                                              self.title, self.description)
        self.ui_group.add(self.stage_name)
        if self.title == "":
            self.stage_name.kill()

        self.upkeep_indicator = upkeepindicator.UpkeepIndicator(self)
        #self.ui_group.add(self.upkeep_indicator)

        self.pause_sprite = pauseoverlay.PauseOverlay()
        self.pause_sprite.layer = 5
        self.ui_group.add(self.pause_sprite)
        self.game.game_speed_input = 0
def run():
    # Initialization
    pygame.init()
    settings = Settings()
    state = Game_State()
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    pygame.display.set_caption("Super Mario Bros")
    bg_color = settings.bg_color
    stats = Game_Stats(screen, settings)

    clock = pygame.time.Clock()

    mario = Mario(screen, settings, stats)

    pygame.mixer.music.load("Sounds/overworld.mp3")
    pygame.mixer.music.play(-1)

    # Groups
    map_group = Group()
    block_group = Group()
    floor_group = Group()
    pipe_group = Group()
    enemy_group = Group()
    powerup_group = Group()
    fireball_group = Group()
    dead_group = Group()

    map.generate_map(screen, settings, map_group, floor_group, pipe_group,
                     block_group, enemy_group)
    f = Flag(screen, settings, 198 * settings.block_width,
             13 * settings.block_height)
    f.add(map_group)

    pipesprites = pipe_group.sprites()

    timer = 0
    death_counter = 0

    # Game Loop
    while state.running:
        settings.reset_holders()
        clock.tick(settings.fps)

        # handle mario death
        if mario.is_dead and death_counter <= 240:
            # draw black screen
            if death_counter == 60:
                screen.fill(settings.bg_color)
                stats.lives -= 1
                if stats.lives < 0:
                    stats.init_base_values()
                    #display game over
                    game_over_label = Text(None, settings.TEXT_SIZE,
                                           "Game Over", settings.WHITE, 0, 0)
                    game_over_label.rect.center = (settings.screen_width / 2,
                                                   settings.screen_height / 2)
                    game_over_label.draw(screen)
                else:
                    # display level
                    lvl_str = "World " + str(stats.world) + "-" + str(
                        stats.level_num)
                    level_label = Text(None, settings.TEXT_SIZE, lvl_str,
                                       settings.WHITE, 0, 0)
                    level_label.rect.center = (settings.screen_width / 2,
                                               settings.screen_height / 2)
                    level_label.draw(screen)
                pygame.display.flip()
            death_counter += 1
            print(death_counter)
        elif mario.is_dead and death_counter > 240:
            # reset
            death_counter = 0
            mario.kill()
            mario = Mario(screen, settings, stats)
            map_group = Group()
            block_group = Group()
            floor_group = Group()
            pipe_group = Group()
            enemy_group = Group()
            powerup_group = Group()
            fireball_group = Group()
            dead_group = Group()
            pygame.mixer.music.play(-1)
            map.generate_map(screen, settings, map_group, floor_group,
                             pipe_group, block_group, enemy_group)
            f = Flag(screen, settings, 198 * settings.block_width,
                     13 * settings.block_height)
            f.add(map_group)
            stats.new_level()

        # victory -> change level -> use death_counter to reset
        if mario.has_won and death_counter <= 300:
            # draw black screen
            if death_counter == 100:
                stats.level_num += 1
                screen.fill(settings.bg_color)
                # display level
                lvl_str = "World " + str(stats.world) + "-" + str(
                    stats.level_num)
                level_label = Text(None, settings.TEXT_SIZE, lvl_str,
                                   settings.WHITE, 0, 0)
                level_label.rect.center = (settings.screen_width / 2,
                                           settings.screen_height / 2)
                level_label.draw(screen)
                coming_soon = Text(None, settings.TEXT_SIZE, "Coming Soon",
                                   settings.WHITE, 0, 0)
                coming_soon.rect.center = (settings.screen_width / 2,
                                           (settings.screen_height / 2) +
                                           settings.SPACER)
                coming_soon.draw(screen)
                pygame.display.flip()
            death_counter += 1
            print(death_counter)
        elif mario.has_won and death_counter > 300:
            # reset game
            death_counter = 0
            mario.kill()
            mario = Mario(screen, settings, stats)
            map_group = Group()
            block_group = Group()
            floor_group = Group()
            pipe_group = Group()
            enemy_group = Group()
            powerup_group = Group()
            fireball_group = Group()
            dead_group = Group()
            pygame.mixer.music.load("Sounds/overworld.mp3")
            pygame.mixer.music.play(-1)
            map.generate_map(screen, settings, map_group, floor_group,
                             pipe_group, block_group, enemy_group)
            f = Flag(screen, settings, 198 * settings.block_width,
                     13 * settings.block_height)
            f.add(map_group)
            stats.new_level()

        # Game Play
        gf.check_events(state, mario, screen, settings, fireball_group,
                        map_group)
        # Update here
        if not mario.is_dead and not mario.has_won:
            if timer < settings.fps:
                timer += 1
            else:
                timer = 0
                stats.decrement_time()

            gf.update(screen, settings, mario, map_group, floor_group,
                      pipe_group, block_group, enemy_group, powerup_group,
                      fireball_group, dead_group, f)

            if stats.did_time_runout():
                mario.dead()
            if stats.time == 100:
                pygame.mixer.Sound('Sounds/time_warning.wav').play()

            # update game values
            stats.add_score(settings.score_holder)
            stats.add_coin(settings.coin_holder)
            if settings.one_up:
                stats.lives += 1
                settings.one_up = False
            # Display here
            stats.update()
            gf.update_screen(screen, settings, stats, mario, map_group,
                             floor_group, pipe_group, block_group, enemy_group,
                             powerup_group, fireball_group, dead_group, f)
        # stats.draw()

    pygame.quit()
    sys.exit()
예제 #31
0
    def __getDifficulty(self):
        easyButtonText = Text("easy", NameScreen.TEXT_FONT,
                              NameScreen.TEXT_FONT_SIZE, NameScreen.TEXT_COLOR)
        easyButton = Button(NameScreen.DIFFICULTY_BUTTON_TOP_COORD,
                            NameScreen.EASY_BUTTON_LEFT_COORD,
                            NameScreen.DIFFICULTY_BUTTON_SIZE,
                            NameScreen.DIFFICULTY_BUTTON_SIZE,
                            NameScreen.EASY_BUTTON_BG_COLOR, easyButtonText)
        mediumButtonText = Text("medium", NameScreen.TEXT_FONT,
                                NameScreen.TEXT_FONT_SIZE,
                                NameScreen.TEXT_COLOR)
        mediumButton = Button(NameScreen.DIFFICULTY_BUTTON_TOP_COORD,
                              NameScreen.MEDIUM_BUTTON_LEFT_COORD,
                              NameScreen.DIFFICULTY_BUTTON_SIZE,
                              NameScreen.DIFFICULTY_BUTTON_SIZE,
                              NameScreen.MEDIUM_BUTTON_BG_COLOR,
                              mediumButtonText)
        hardButtonText = Text("hard", NameScreen.TEXT_FONT,
                              NameScreen.TEXT_FONT_SIZE, NameScreen.TEXT_COLOR)
        hardButton = Button(NameScreen.DIFFICULTY_BUTTON_TOP_COORD,
                            NameScreen.HARD_BUTTON_LEFT_COORD,
                            NameScreen.DIFFICULTY_BUTTON_SIZE,
                            NameScreen.DIFFICULTY_BUTTON_SIZE,
                            NameScreen.HARD_BUTTON_BG_COLOR, hardButtonText)

        mouseX = 0
        mouseY = 0
        mouseClicked = False

        easyButton.display(self.__gameDisplay)
        mediumButton.display(self.__gameDisplay)
        hardButton.display(self.__gameDisplay)
        pygame.display.update()

        while True:
            mouseClicked = False
            pygame.time.wait(1)

            for event in pygame.event.get():
                if event.type == QUIT or (event.type == KEYUP
                                          and event.key == K_ESCAPE):
                    return Screen.QUIT_PROGRAM
                elif event.type == pygame.USEREVENT or (event.type == KEYUP and
                                                        event.key == K_RIGHT):
                    self.__musicPlayer.nextSong()
                elif event.type == MOUSEMOTION:
                    mouseX, mouseY = event.pos
                elif event.type == MOUSEBUTTONUP:
                    mouseX, mouseY = event.pos
                    mouseClicked = True
                elif event.type == SoundCue.SOUND_CUE_END_EVENT:
                    self.__musicPlayer.fadeIn()

            if mouseClicked == True:
                if easyButton.collides(mouseX, mouseY):
                    return Constants.EASY_DIFFICULTY_MULTIPLIER

                if mediumButton.collides(mouseX, mouseY):
                    return Constants.MEDIUM_DIFFICULTY_MULTIPLIER

                if hardButton.collides(mouseX, mouseY):
                    return Constants.HARD_DIFFICULTY_MULTIPLIER
예제 #32
0
 def set_text(self, text):
     """
     """
     self.remove(self.text)
     self.text = Text(config.all_player_overlay_font, text)
     self.add(self.text)
예제 #33
0
 def __init__(self, anc_way, settings={}):
     if anc_way == 'text':
         from text import Text as Record
     self.anchor = Record(settings)
예제 #34
0
 def set_pop(self, pop):
     self.population = pop
     self.num_label = Text(str(self.population), "small", self.pos + V2(7, -7), PICO_WHITE,shadow=PICO_BLACK)
     self.scene.ui_group.add(self.num_label)
예제 #35
0
    def __init__(self,
                 mic,
                 position,
                 bar_size=(20, 40),
                 scale_margin=(10, 5),
                 border=2,
                 tick_length=10,
                 min_db=-70):

        # parent init
        super().__init__()

        # vars
        self.mic = mic
        self.position = position
        self.bar_size = bar_size
        self.scale_margin = scale_margin
        self.border = border
        self.tick_length = tick_length
        self.min_db = min_db

        # image size
        self.image_size = (
            self.bar_size[0] + self.scale_margin[0],
            self.bar_size[1] + self.scale_margin[1] * 2,
        )

        # colors
        self.color_bag = ColorBag()

        # bar init
        self.image = pygame.surface.Surface(self.image_size)
        self.rect = self.image.get_rect()

        # set rectangle position
        self.rect.x, self.rect.y = self.position[0], self.position[1]

        # lengths
        self.act_length = 5
        self.total_length = self.bar_size[1]

        # energy thresh
        self.energy_thresh_position = int(
            10 * np.log10(self.mic.mic_params['energy_thresh']) *
            (bar_size[1] / self.min_db))

        print("e: ", self.energy_thresh_position)

        # fill with background color
        self.image.fill(self.color_bag.mic_bar_background)

        # border
        pygame.draw.rect(
            self.image, self.color_bag.mic_bar_border,
            (0, self.scale_margin[1] - self.border, self.bar_size[0] +
             2 * self.border, self.total_length + 2 * self.border))

        # scale
        scale_ticks = [
            i * self.total_length // (np.abs(self.min_db) // 10)
            for i in range(np.abs(self.min_db) // 10 + 1)
        ]
        scale_tick_names = [i * -10 for i in range(len(scale_ticks))]

        # print("scale ticks: ", scale_ticks)
        # print("total: ", self.total_length)
        # print("space: ", self.total_length // (np.abs(self.min_db) // 10))
        [
            pygame.draw.rect(self.image, self.color_bag.mic_bar_meter_tick,
                             (self.bar_size[0], self.scale_margin[1] + i,
                              self.tick_length, 2)) for i in scale_ticks
        ]

        # draw text
        texts = [
            Text(self.image,
                 message=str(m),
                 position=(self.border + self.bar_size[0] + self.tick_length +
                           2, self.scale_margin[1] - 6 + i),
                 font_size='tiny',
                 color=self.color_bag.mic_bar_meter_tick)
            for i, m in zip(scale_ticks, scale_tick_names)
        ]
        texts.append(
            Text(self.image,
                 message='[db]',
                 position=(self.border + self.bar_size[0] + self.tick_length +
                           2, self.scale_margin[1] // 2 - 6),
                 font_size='tiny',
                 color=self.color_bag.mic_bar_meter_tick))
        [text.draw() for text in texts]
예제 #36
0
    def __init__(self, width, height):
        self.width = width
        self.height = height

        self.options = [
            {
                "text":
                "2 Player",
                "text_index":
                3,
                "x":
                self.width / 2,
                "y":
                self.height / 2 - 32,
                "state":
                Game(self.width, self.height, manual_player_1, manual_player_2)
            },
            {
                "text": "1 Player",
                "text_index": 4,
                "x": self.width / 2,
                "y": self.height / 2,
                "state": Game(self.width, self.height, manual_player_1,
                              AI_player)
            },
            {
                "text": "0 Player",
                "text_index": 5,
                "x": self.width / 2,
                "y": self.height / 2 + 32,
                "state": Game(self.width, self.height, AI_player, AI_player)
            },
            {
                "text": "Instructions",
                "text_index": 6,
                "x": self.width / 2,
                "y": self.height / 4 * 3,
                "state": Instruction(self.width, self.height)
            },
            {
                "text": "Thanks",
                "text_index": 7,
                "x": self.width / 2,
                "y": self.height / 4 * 3 + 34,
                "state": Thanks(self.width, self.height)
            },
        ]

        self.text = [
            Text(self.width / 2, self.height / 5, "Pong", 72),
            Text(self.width / 2, self.height / 5 + 30, "By Luke Brom", 12),
            Text(self.width / 2, self.height - 14,
                 "(Hit escape to exit at any time)", 12)
        ]
        for option in self.options:
            self.text.append(Text(option["x"], option["y"], option["text"],
                                  32))

        self.selected = 0
        self.clock = pygame.time.Clock()
        self.time_since_button_pressed = self.clock.tick()
예제 #37
0
 def prep_score(self):
     """Create a rendered image for score."""
     score = str(self.game_stats.score)
     self.score_image = Text(self.screen, self.settings, score,
                             self.settings.black, 765, 120)
예제 #38
0
파일: cipher.py 프로젝트: zgthompson/sp14
 def __init__(self, text):
     self.text = Text.only_letters(text)
예제 #39
0
    def _text_view(self, screen):
        h, w = screen.getmaxyx()

        text_win = self._init_text_win(h, w)
        input_win = self._init_input_win(h, w)
        status_win = self._init_status_win(h, w)

        words = text_generator.generate(
            self.config_manager.config.get_param('active_dictionary'),
            int(self.config_manager.config.get_param('text_words_count')))
        text = Text(words)
        self._print_text_win(text_win, text)
        self._print_status_win(status_win, text)

        self._refresh_all(screen, text_win, input_win, status_win)

        input_text = ''
        while True:
            key = screen.get_wch()

            # TODO: refactor
            if key == curses.KEY_RESIZE:
                h, w = screen.getmaxyx()
                screen.erase()
                text_win = self._init_text_win(h, w)
                input_win = self._init_input_win(h, w)
                status_win = self._init_status_win(h, w)
                self._print_text_win(text_win, text)
                self._print_input_win(input_win, status_win, text, input_text,
                                      key)
                self._refresh_all(screen, text_win, input_win, status_win)

            if text.current_word_index == 0 and len(input_text) == 0:
                text.start_typing()

            if key == '\n' or key == ' ':
                if text.has_next():
                    text.next(input_text)
                input_text = ''
            elif type(key) == str:
                if text.has_next():
                    current_word = text.words[text.current_word_index].word_str
                    if current_word.startswith(input_text) and \
                            not current_word.startswith(input_text + key):
                        text.mistakes += 1
                input_text += key
            elif int(key) == curses.KEY_BACKSPACE:
                input_text = input_text[:-1]

            self._print_text_win(text_win, text)
            self._print_status_win(status_win, text)

            key = self._print_input_win(input_win, status_win, text,
                                        input_text, key)

            if not key:
                continue

            if key == 'n':
                self._text_view(screen)
                return
            if key == 'w':
                self._welcome_view(screen)
                return
            if key == ':':
                self._command_view(screen)
                self._print_status_win(status_win, text)
                self._print_input_win(input_win, status_win, text, input_text,
                                      key)
            if key == 'q':
                return
# Getting rid of the "#" symbol and making a list from the color string
    project[3] = list(project[3].replace("#", ""))

# Converting the HEX colors to RGB colors to : [r, g, b]
    for i in range(len(project[3])):
        project[3][i] = int(project[3][i], 16)*17

# Creating the text objects(still inside the for cycle :) )
    text = Text(project[0], int((project[1] * 2) / 400), (255, 0, 0), random.choice(fonttype_list), project[1]/100*2.7)
    text.calculate_length(picture)

# Sort the class list based on the object attribute size, which is based on the desired factor(budget)
# Na itt az ordered_list készen, már csak ki kell íratni a randommal. A fonttype_list-re nem
# fog hibát kiírni, az is mehet randommal, meg esetleg a rotate is lehetne random.choice(0, 90, 270)
# sok sikert a demóhoz!

for text in Text.text_object_list:
    text.calculate_length(picture)

Text.checkOccupyRatio()

Text.order_list()
percent = 0
count = 0
for text in Text.ordered_list:
    picture = text.randomPlace(picture)
    count += 1
    percent = int(count/len(first_list)*100)
    print(str(percent) + " % completed\nWorking...")

picture.save("SecondAssignment.png")
예제 #41
0
 def test_byte_array_to_lower(self):
     self.assertEqual(Text.byte_array_to_lower(ByteArray(HELLO_WORLD)), HELLO_WORLD.lower())
예제 #42
0
 def __init__(self, text1, text2):
     self._idf_matches_cache = {}
     self.text1 = Text(text1)
     self.text2 = Text(text2)
     self.calculate_all_features()
예제 #43
0
def enemies_screen():
    
    topleft = (0,0)
    screen.blit(background_image,topleft)
    font_path = os.path.join('assets','atari.ttf')
    title_font_size = 40
    title_text = Text("ENEMIES",WIDTH//2,50,font_path,title_font_size,WHITE,center_coordinate=True)
    menu_button = Button("BACK",WIDTH//2,HEIGHT - 100,WHITE,RED,None,title_font_size)
        
    button_group = pygame.sprite.Group(menu_button)
    text = pygame.sprite.GroupSingle(title_text)
    
    
    class Icon(pygame.sprite.Sprite):


        def __init__(self,x,y,image,size=40):
            super().__init__()

            if type(image) == list:
                self.images = image
                for i,image in enumerate(self.images):
                    self.images[i] = pygame.transform.scale(pygame.image.load(image).convert_alpha(),(size,size))

                self.image = self.images[0]
                self.multiple = True
            else:
                self.image = pygame.transform.scale(image,(size,size))
                self.multiple = False



            self.rect = self.image.get_rect(topleft=(x,y))



    class MultipleIcon(pygame.sprite.Sprite):


        def __init__(self,x,y,images,size=-1,frames=60):
            super().__init__()
            self.images = images

            
            for i,image in enumerate(self.images):
                if size != -1:
                    self.images[i] = pygame.transform.scale(pygame.image.load(image).convert_alpha(),(size,size))
                else:
                    self.images[i] = pygame.image.load(image).convert_alpha()

            self.image = self.images[0]

            self.rect = self.image.get_rect(topleft=(x,y))
            self.image_index = 0
            self.frame_counter = 0
            self.frames = frames


        def update(self):


            self.frame_counter += 1

            if self.frame_counter == self.frames:
                self.frame_counter = 0
                self.image_index = (self.image_index + 1) % len(self.images)

                self.image = self.images[self.image_index]



    image_size = 60
    top_gap = HEIGHT//2 + 50

    icons = pygame.sprite.Group()
    


    cols = 4
    rows = 2

    gap = 40
    left_gap = WIDTH//2  - ((image_size + gap) *cols - gap)//2

    
    directory = os.path.join('assets','aliens')

    file_names = [os.path.join(directory,file_name) for file_name in os.listdir(directory)]
    images = [file_names]
    print(len(file_names))

    directory = os.path.join('assets','enemies')

    images = []
    for file_ in os.listdir(directory):
        path = os.path.join(directory,file_)
        if os.path.isfile(path):
            images.append(path)
        else:
            file_names = [os.path.join(path,file_name) for file_name in os.listdir(path)]
            images.append(file_names)
    
    exit = False
    for row in range(rows):
        for col in range(cols):
            try:
                image = images[row * cols + col]
            except IndexError:
                exit = True
                break

            


            if isinstance(image,list):
                if row * cols + col > 1:
                    fps = 10
                else:
                    fps = 60

                icon = MultipleIcon(left_gap + (col * (image_size + gap)),top_gap +row * image_size,image,image_size,fps)
            else:
                icon = Icon(left_gap + (col * (image_size + gap)),top_gap +row * image_size,image,image_size)
            icons.add(icon)
        if exit:
            break


    while True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                return
            elif event.type == pygame.MOUSEBUTTONDOWN:
                point = pygame.mouse.get_pos()
                for button in button_group:
                    if button.clicked_on(point):
                        if button.callback:
                            button.callback()
                        else:
                            return

        
        screen.blit(background_image,topleft)
         
        point = pygame.mouse.get_pos()
        button_group.update(point)
        icons.update()

        text.draw(screen)
        

        button_group.draw(screen)
        icons.draw(screen)
        pygame.display.update()
        clock.tick(FPS)
예제 #44
0
 def prep_level(self):
     """Create a rendered image for level."""
     level = str(self.game_stats.level)
     self.level_image = Text(self.screen, self.settings, level,
                             self.settings.black, 725, 280)
예제 #45
0
def instructions_screen():
    
    
    text_group = pygame.sprite.Group()
    
    font_path = os.path.join('assets','atari.ttf')
    title_font_size = 40

    title_text = Text("HOW TO PLAY",WIDTH//2,50,font_path,title_font_size,WHITE,center_coordinate=True)
    
    
    instructions = "HIT SPACEBAR TO FIRE MISSILES TOWARDS ENEMIES. USE THE LEFT AND RIGHT ARROW TO MOVE LEFT AND RIGHT. COLLECT POWERUPS FOR BOOSTS AND AVOIDTHE HARMFUL ITEMS. DEFEAT A WAVE TO MOVE ON TO THE NEXT ONE."

    width = 28
    texts = textwrap.wrap(instructions,width)

    gap = 40
    start = 50 + title_text.get_height()//2 +  gap
    instruction_font_size = 20
    gap = 20
    for i,text in enumerate(texts):
        text_sprite = Text(text,WIDTH//2,start + i * (instruction_font_size + 20),font_path,instruction_font_size,WHITE,center_coordinate=True)
        text_group.add(text_sprite)
    




    text_group.add(title_text)
    screen.blit(background_image,(0,0))

    menu_button = Button("MENU",WIDTH//2,HEIGHT - 100,WHITE,RED,None,title_font_size)
    power_ups_button = Button("ITEMS",WIDTH//2,HEIGHT - 220,WHITE,RED,power_up_screen,title_font_size)
    enemies_button = Button("ENEMIES",WIDTH//2,HEIGHT - 340,WHITE,RED,enemies_screen,title_font_size)


    button_group = pygame.sprite.Group(menu_button,power_ups_button,enemies_button)
    


    while True:


        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                return
            elif event.type == pygame.MOUSEBUTTONDOWN:
                point = pygame.mouse.get_pos()
                

                for button in button_group:
                    if button.clicked_on(point):
                        if button.callback:
                            button.callback()
                        else:
                            return



        point = pygame.mouse.get_pos()
        button_group.update(point)
        screen.blit(background_image,(0,0))
        

        text_group.draw(screen)
        button_group.draw(screen)

        pygame.display.update()
예제 #46
0
 def __init__(self, bus, object_path):
     super(EngineBase, self).__init__()
     self.__proxy = EngineProxy (self, bus.get_dbusconn(), object_path)
     self.__surrounding_text = Text()
     self.__surrounding_cursor_pos = 0
     self.__selection_anchor_pos = 0
예제 #47
0
파일: game.py 프로젝트: LordHamu/RunNGun
 def add_title(self, title):
     TextSurf, TextRect = Text.text_objects(title, constants.largeText, constants.WHITE)
     TextRect.center = ((constants.DWIDTH / 2), ((constants.DHEIGHT / 2) - 100))
     self.ui_list.append({'title':title, 'type': 'text','surface':TextSurf,'rectangle':TextRect})
예제 #48
0
파일: vigenere.py 프로젝트: zgthompson/sp14
 def __init__(self, text, key):
     super(Vigenere, self).__init__(text)
     self.key = Text.only_letters(key)
     self.table = { ENGLISH_LETTERS[i]: Affine.create_alphabet( 1, i ) for i in range(26) }
     self.reverse_table = self.create_reverse_table()
예제 #49
0
object_pos = [width // 2, height // 2]
scale = 600
dist = 5
speed = 0.01

cube = np.zeros((8, 3, 1))
cube[0] = [[-1], [-1], [1]]
cube[1] = [[1], [-1], [1]]
cube[2] = [[1], [1], [1]]
cube[3] = [[-1], [1], [1]]
cube[4] = [[-1], [-1], [-1]]
cube[5] = [[1], [-1], [-1]]
cube[6] = [[1], [1], [-1]]
cube[7] = [[-1], [1], [-1]]

scale_txt = Text(10, 10, 100, 30)
scale_down_btn = Button(10, 40, 50, 30, '-')
scale_up_btn = Button(60, 40, 50, 30, '+')

dist_txt = Text(10, 90, 100, 40)
dist_down_btn = Button(10, 120, 50, 30, '-')
dist_up_btn = Button(60, 120, 50, 30, '+')

speed_txt = Text(10, 150, 100, 40)
speed_down_btn = Button(10, 180, 50, 30, '-')
speed_up_btn = Button(60, 180, 50, 30, '+')

while True:
    clock.tick(fps)
    window.fill(black)
예제 #50
0
def power_up_screen():
    
    

    def load_items():

        
        
        item_types = [Heart,InvincibilityPotion,Cross,Star,TorpedoPowerUp,Safety,Skull,BombPowerUp,Snowflake,PoisonMuk,FreeMovement,Strength,RedButton]
        
        item_type_index = 0

        items_group = pygame.sprite.Group() 

    
        top_gap = 450
            
        gap_between_items = 20
        rows = 5
        size = 40
        side_gap = (WIDTH - (size + gap_between_items) * rows)//2
        print(len(item_types)/rows)
        for row in range(math.ceil(len(item_types)/rows)):
            for col in range(rows):
                item = item_types[item_type_index](WIDTH,HEIGHT)

                x= side_gap + (col * (size + gap_between_items))
                y= top_gap + (row * (size + gap_between_items))
                item.change_rects_topleft(x,y)
                item_type_index += 1

                items_group.add(item)
                if item_type_index == len(item_types):
                    break

            else:
                continue

            break

            


        return items_group






    




    items_group = load_items()
        



    

    font_path = os.path.join('assets','atari.ttf')
    title_font_size = 40
    

    text_group = pygame.sprite.Group()
    hover_font_size = 20
    title_text = Text("ITEMS",WIDTH//2,50,font_path,title_font_size,WHITE,center_coordinate=True)
    hover_text = Text("HOVER OVER ITEMS FOR DETAILS",WIDTH//2,100,font_path,hover_font_size,WHITE,center_coordinate=True)

    text_group.add(title_text)
    text_group.add(hover_text)
    menu_button = Button("BACK",WIDTH//2,HEIGHT - 100,WHITE,RED,None,title_font_size)

    
    button_group = pygame.sprite.Group(menu_button)



    

    while True:

        

        text = None
        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            elif event.type == pygame.MOUSEBUTTONDOWN:
                point = pygame.mouse.get_pos()

                for button in button_group:
                    if button.clicked_on(point):
                        if button.callback:
                            button.callback()
                        else:
                            return


        screen.blit(background_image,(0,0))
        

        point = pygame.mouse.get_pos()


        for item in items_group:
            if item.is_hovered_on(point):
                text = item.text


        
        if text:
            if isinstance(text,list):
                start = 150
                for i,t in enumerate(text):
                    screen.blit(t,(WIDTH//2 - t.get_width()//2,150 + (i * (t.get_height() + 20))))
            else:
                screen.blit(text,(WIDTH//2- text.get_width()//2,150))



        button_group.update(point)
        

        items_group.draw(screen)
        text_group.draw(screen)
        button_group.draw(screen)

        pygame.display.update()
예제 #51
0
파일: tags.py 프로젝트: schuyler/nlplib
from graph import TextGraph
from text import Text

import sys, textwrap, urllib2

print >>sys.stderr, ">>> starting..."

if "://" in sys.argv[1]:
    text = Text.from_url(sys.argv[1])
else:
    text = Text.from_file(sys.argv[1])
graph = TextGraph(text)
summary = graph.summary()
print "\n".join(textwrap.wrap(summary))
print
graph = TextGraph(text)
print "Tags:", ", ".join(graph.tags())