Пример #1
0
	def logout(self):
		print utils.colorize('Logging out of ' + self.current_user.name + '. You can log in to a diferent account now.', "YELLOW")
		self.logged_in = False
		self.current_user = None
		self.display_name = ">"
		self.api = None
		self.auth = tweepy.OAuthHandler(utils.CONSUMER_KEY, utils.CONSUMER_SECRET)
Пример #2
0
	def print_status(self, status):
		print "|" + "_"*78 + "|"
		print utils.add_symbol(utils.colorize(status.author.screen_name, "B_CYAN"), 90)
		lines = utils.split_tweet(status.text)
		for line in lines:
			print line
		timestamp = utils.colorize("at " + status.created_at.strftime("%A, %d/%m/%y, %H:%M:%S") + " from " + status.source, "CYAN")
		print utils.add_symbol(timestamp, 90)
Пример #3
0
	def complete_login(self):
		self.logged_in = True
		self.auth.set_access_token(self.current_user.key, self.current_user.secret)
		self.api = tweepy.API(self.auth)
		self.display_name = self.current_user.name + " "
		self.clear()
		print_text.header_user(self.current_user.name)
		print utils.colorize("You have successfully logged in!", "GREEN")
Пример #4
0
	def get_home_timeline(self):
		print utils.colorize("Fetching latests tweets, please wait.....", "YELLOW")
		statuses = self.api.home_timeline(count=20)
		statuses = reversed(statuses)
		print "Twitter timeline: last updated at " + datetime.now().strftime("%A, %d/%m/%Y %I:%M%p")
		for status in statuses:
			self.print_status(status)
		print "|" + "_"*78 + "|"
Пример #5
0
 def do_intro(self):
     """
     Does any start-of-game actions for the player. Initializing GameState variables
     should be done in the __init__ function
     """
     lines = [
         "Welcome to your text game!",
         "To view the help screen, type `h` or `help`."
     ]
     print colorize('\n'.join(lines), 'yellow')
Пример #6
0
	def on_status(self, status):
		try:
			print "|" + "_"*78 + "|"
			print utils.add_symbol(utils.colorize(status.author.screen_name, "B_CYAN"), 90)
			for line in self.status_wrapper.wrap(status.text):
				print utils.add_symbol_end(line, 80)
			timestamp = utils.colorize("at " + status.created_at.strftime("%A, %d/%m/%y, %H:%M:%S") + " from " + status.source, "CYAN")
			print utils.add_symbol(timestamp, 90)
		except:
			print 'error'
Пример #7
0
	def try_login(self, login_string):
		params = login_string.split(" ")
		if len(params) == 2:
			self.current_user = self.user_auth.login(params[1])
			if self.current_user:
				self.complete_login()
		elif params[0] == 'login':
			print utils.colorize('Command syntax incorrect. Please refer to "help" to see the correct syntax.', "B_RED")
		else:
			print utils.colorize('The command "' + login_string + '" was not recognized.', "B_RED")
Пример #8
0
	def save_user(self, name, password, key, secret):
		if not self.username_exists(name):
			self.config.add_section(name)
			self.config.set(name, "password", self.encrypt_password(password))
			self.config.set(name, "key", key)
			self.config.set(name, "secret", secret)
			with open('config.cfg', 'wb') as configfile:
				self.config.write(configfile)
				print utils.colorize('User saved successfully!', "GREEN")
		else:
			print utils.colorize("User name already exists!", "RED")
Пример #9
0
	def login(self, user_name):
		try:
			user = self.get_user(user_name)
			password = getpass.getpass('Password: ')
			if user and user.password == self.encrypt_password(password):
				return user
			else:
				print utils.colorize('Username or password incorrect. Please try again.', "B_RED")
				return None
		except:
			print utils.colorize('An error ocurred. Please try again.', "RED")
			return None
Пример #10
0
	def get_user_profile(self, user_input):
		try:
			name = user_input.split(' ')[1]
			print "Loading user....."
			user = self.api.get_user(name)
			print "|" + "_"*78 + "|"
			print utils.add_symbol(utils.colorize(user.name, "B_YELLOW"), 90)
			print "|" + " "*78 + "|"
			print utils.add_symbol(utils.colorize(" Location: " +user.location, "YELLOW"), 90)
			lines = utils.split_user_bio("Bio: " + user.description)
			for line in lines:
				print line
			print "|" + " "*78 + "|"
			print utils.add_symbol(utils.colorize(" " + str(user.statuses_count) + " tweets", "YELLOW"), 90)
			print utils.add_symbol(utils.colorize(" Followers: " + str(user.followers_count), "YELLOW"), 90)
			print utils.add_symbol(utils.colorize(" Following: " + str(user.friends_count), "YELLOW"), 90)
			print utils.add_symbol(utils.colorize(" " + str(user.favourites_count) + " tweets favorited", "YELLOW"), 90)
			print "|" + "_"*78 + "|"
			print utils.add_symbol("Loading tweets.....", 80)
			statuses = self.api.user_timeline(screen_name=name, count=20)
			print utils.add_symbol("User tweets: last updated at " + datetime.now().strftime("%A, %d/%m/%Y %I:%M%p"), 80)
			for status in statuses:
				self.print_status(status)
			print "|" + "_"*78 + "|"
		except:
			print utils.colorize('User not found', "RED")
Пример #11
0
    def run(self):
        """
        Runs a loop that accepts the user's input, executes the appropriate command, and
        exits the game with an exit message when finished.
        """
        while True:
            # print out location information
            print colorize('\n%s:' % self.curr_location.name, 'cyan')
            print colorize(self.curr_location.description, 'yellow')

            try:
                user_input = capture_input()
            except QuitGame:
                break

            # the primary command is the first word in the user input
            command = user_input[0]
            try:
                command_class = ALL_COMMANDS[command]
            except KeyError:
                print colorize("Command '%s' does not exist" % command, 'red')
                continue

            # call the appropriate function
            try:
                command_class.execute(user_input, self)
            except QuitGame:
                break

            if self.finished:
                self.do_finish()
                return

        print colorize('\nExiting the game...', 'red')
Пример #12
0
    def on_status(self, status):
        try:
			print "|" + "_"*78 + "|"
			print utils.add_symbol(utils.colorize(status.author.screen_name, "B_CYAN"), 90)
			for line in self.status_wrapper.wrap(status.text):
				print utils.add_symbol_end(line, 80)
			timestamp = utils.colorize("at " + status.created_at.strftime("%A, %d/%m/%y, %H:%M:%S") + " from " + status.source, "CYAN")
			print utils.add_symbol(timestamp, 90)
            #print self.status_wrapper.fill(status.text)
            #print '\n %s  %s  via %s\n' % (status.author.screen_name, status.created_at, status.source)
        except:
            # Catch any unicode errors while printing to console
            # and just ignore them to avoid breaking application.
            print 'error'
def main(argv):
    pattern = "/scratch/nharness/Library/RAW/*TIF"
    files = glob(pattern)
    assert len(files) > 0
    assert len(files) < 1000000, len(files)
    shuffle(files)

    outfile = '/home/nharness/idcgans/datasets/patents' + str(IMSIZE) + '.tfrecords'
    writer = tf.python_io.TFRecordWriter(outfile)

    for i, f in enumerate(files):
        print i
        image = get_image(f, IMSIZE, is_crop=True, resize_w=IMSIZE)
        image = colorize(image)
        assert image.shape == (IMSIZE, IMSIZE, 3)
        image += 1.
        image *= (255. / 2.)
        image = image.astype('uint8')
        #print image.min(), image.max()
        # from pylearn2.utils.image import save
        # save('foo.png', (image + 1.) / 2.)
        image_raw = image.tostring()
        label = 0
        if i % 1 == 0:
            print i, '\t',label
        example = tf.train.Example(features=tf.train.Features(feature={
            'height': _int64_feature(IMSIZE),
            'width': _int64_feature(IMSIZE),
            'depth': _int64_feature(3),
            'image_raw': _bytes_feature(image_raw),
            'label': _int64_feature(label)
            }))
        writer.write(example.SerializeToString())

    writer.close()
Пример #14
0
    def compose_line(self, color=True, exclusions=None, reorder=None):
        """convert task object into a string for display or writing"""

        if exclusions is None:
            exclusions = []
        self.num = reorder or self.num

        parts = [
            ('n', 'gray', self.num_string),
            ('x', 'gray', self.x),
            ('pr', 'red', self.priority),
            ('dn', 'gray', self.done_string),
            ('d', 'orange', self.due_string),
            ('t', 'white', self.text),
            ('p', 'blue', self.projects_string),
            ('c', 'yellow', self.contexts_string),
            ('r', 'magenta', self.repeat_string),
            ('a', 'green', self.added_string),
            ('o', 'gray', self.order_string),
            ('p_id', 'gray', self.parent_id_string),
            ('c_id', 'gray', self.child_id_string),
            ]

        if color:
            parts = [utils.colorize(s, c) for l, c, s in parts
                     if l not in exclusions and s]
        else:
            parts = [s for l, c, s in parts if l not in exclusions and s]
        return ' '.join(parts)
Пример #15
0
 def execute(user_input, game_state):
     user_input = capture_input(
         colorize('Are you sure you would like to overwrite any saved games? (y/n) ', 'red')
     )
     if user_input[0] == 'y':
         game_state.save()
     else:
         print 'Aborting save'
Пример #16
0
 def execute(user_input, game_state):
     user_input = capture_input(
         colorize('Are you sure you would like to quit? (y/n) ', 'red')
     )
     if user_input[0] == 'y':
         raise QuitGame
     else:
         print 'Aborting quit'
Пример #17
0
def getStaticEnvironment():
    environment = Environment(ENV = os.environ)
    peg_color = 'light-cyan'
    environment['PAINTOWN_PLATFORM'] = ['osx']
    environment['PAINTOWN_USE_PRX'] = False
    environment['PAINTOWN_TESTS'] = {'CheckPython': checkPython}
    environment['PAINTOWN_COLORIZE'] = utils.colorize
    environment['PAINTOWN_NETWORKING'] = True
    environment['PAINTOWN_NETWORKING'] = True
    environment.Append(CPPDEFINES = ['HAVE_NETWORKING'])
    environment.Append(CPPDEFINES = ['MACOSX'])
    environment['LIBS'] = []
    environment['PEG_MAKE'] = "%s %s" % (utils.colorize('Creating peg parser', peg_color), utils.colorize('$TARGET', 'light-blue'))
    environment.Append(BUILDERS = {'Peg' : utils.pegBuilder(environment)})
    environment.Append(CPPPATH = ['#src', '#src/util/network/hawknl'])
    # environment.Append(CCFLAGS = Split("-arch i386 -arch x86_64"))
    # print environment['CCCOM']
    # I don't know why appending -arch to ccflags doesn't work, but whatever
    environment['CCCOM'] = '$CC -arch i386 -arch x86_64 $CFLAGS $CCFLAGS $_CCCOMCOM $SOURCES -c -o $TARGET'
    environment['CXXCOM'] = '$CXX -arch i386 -arch x86_64 -o $TARGET -c $CXXFLAGS $CCFLAGS $_CCCOMCOM $SOURCES'
    environment['LINKCOM'] = '$CXX $LINKFLAGS -arch i386 -arch x86_64 $SOURCES $_FRAMEWORKS -Wl,-all_load $ARCHIVES $_LIBDIRFLAGS $_LIBFLAGS -o $TARGET'

    # Default preference for a graphics renderer / input system
    backends = ['SDL', 'Allegro4', 'Allegro5']

    if utils.useAllegro4():
        backends = ['Allegro4', 'SDL', 'Allegro5']

    if utils.useAllegro5():
        backends = ['Allegro5', 'SDL', 'Allegro4']

    #environment.ParseConfig('freetype-config --libs --cflags')
    #environment.ParseConfig('libpng-config --libs --cflags')

    if utils.useLLVM():
        llvm(environment)

    custom_tests = {"CheckCompiler": utils.checkCompiler,
                    "CheckSDL" : checkStaticSDL,
                    "CheckOgg" : checkStaticOgg,
                    "CheckFreetype" : checkStaticFreetype,
                    "CheckMalloc" : checkMallocH,
                    "CheckZ" : checkStaticZ,
                    "CheckPng" : checkStaticPng,
                    "CheckMpg123" : checkStaticMpg123,
                    "CheckAllegro4" : checkStaticAllegro4,
                    "CheckAllegro5" : checkStaticAllegro5}

    config = environment.Configure(custom_tests = custom_tests)
    config.CheckZ()
    config.CheckOgg()
    config.CheckMpg123()
    config.CheckFreetype()
    config.CheckPng()
    # config.CheckMalloc()
    environment = config.Finish()

    return utils.configure_backend(environment, backends, custom_tests)
Пример #18
0
	def update_status(self):
		success = False
		print utils.colorize( 'What\'s happening?\n (type "\cancel" to cancel)' + ' '*(99) + '140char limit -->|', "YELLOW")
		while not success:
			message = raw_input('  > ')
			if message == '\cancel':
				return success
			elif len(message) <= 140 and len(message) > 0:
				self.api.update_status(message)
				print utils.colorize('Tweet sent succefully!', "GREEN")
				success = True
			elif len(message) > 140:
				print utils.colorize('Your message had ' + str(len(message)) + ' characteres, please reduce it to a maximum of 140 and try again.', "RED")
			elif len(message) == 0:
				print utils.colorize('You must say something!', "RED")
Пример #19
0
def getEnvironment():
    import utils
    environment = Environment(ENV = os.environ)
    environment['PAINTOWN_PLATFORM'] = ['wii', 'sdl']
    peg_color = 'light-cyan'
    environment['PAINTOWN_BACKEND'] = 'sdl'
    environment['PAINTOWN_USE_PRX'] = False
    environment['PAINTOWN_TESTS'] = {'CheckPython': checkPython}
    environment['PAINTOWN_COLORIZE'] = utils.colorize
    environment['PAINTOWN_NETWORKING'] = False
    environment['LIBS'] = []
    environment['PEG_MAKE'] = "%s %s" % (utils.colorize('Creating peg parser', peg_color), utils.colorize('$TARGET', 'light-blue'))
    environment.Append(BUILDERS = {'Peg' : utils.pegBuilder(environment)})
    environment.Append(CPPPATH = ['#src', '#src/util/network/hawknl'])
    environment.Append(CPPDEFINES = ['USE_SDL'])

    return utils.lessVerbose(wii(environment))
def main(argv):
    pattern = "/home/ian/imagenet/ILSVRC2012_img_train_t1_t2/n*/*JPEG"
    files = glob(pattern)
    assert len(files) > 0
    assert len(files) > 1000000, len(files)
    shuffle(files)

    dirs = glob("/home/ian/imagenet/ILSVRC2012_img_train_t1_t2/n*")
    assert len(dirs) == 1000, len(dirs)
    dirs = [d.split('/')[-1] for d in dirs]
    dirs = sorted(dirs)
    str_to_int = dict(zip(dirs, range(len(dirs))))


    outfile = '/media/NAS_SHARED/imagenet/imagenet_train_labeled_' + str(IMSIZE) + '.tfrecords'
    writer = tf.python_io.TFRecordWriter(outfile)

    for i, f in enumerate(files):
        print i
        image = get_image(f, IMSIZE, is_crop=True, resize_w=IMSIZE)
        image = colorize(image)
        assert image.shape == (IMSIZE, IMSIZE, 3)
        image += 1.
        image *= (255. / 2.)
        image = image.astype('uint8')
        #print image.min(), image.max()
        # from pylearn2.utils.image import save
        # save('foo.png', (image + 1.) / 2.)
        image_raw = image.tostring()
        class_str = f.split('/')[-2]
        label = str_to_int[class_str]
        if i % 1 == 0:
            print i, '\t',label
        example = tf.train.Example(features=tf.train.Features(feature={
            'height': _int64_feature(IMSIZE),
            'width': _int64_feature(IMSIZE),
            'depth': _int64_feature(3),
            'image_raw': _bytes_feature(image_raw),
            'label': _int64_feature(label)
            }))
        writer.write(example.SerializeToString())

    writer.close()
Пример #21
0
	def edit_user_name(self, current_user):
		try:
			print 'Type in your new user name:'
			print '(type "\cancel" to cancel)'
			sucess = False
			while not sucess:
				new_name = raw_input('Username: ')
				if new_name == '\cancel':
					return ''
				elif ' ' in new_name:
					print utils.colorize("User name cannot contain any spaces.", "RED")
				elif len(new_name) == 0:
					print utils.colorize("User name cannot be empty!", "RED")
				elif self.username_exists(new_name):
					print utils.colorize("User name already exists.", "RED")
				else:
					sucess = True
			self.remove_user(current_user.name)
			self.save_user(new_name, current_user.password, current_user.key, current_user.secret)
			return new_name
		except:
			print utils.colorize('An error occurred while saving your new username, sorry.', "B_RED")
			return ''
Пример #22
0
def getEnvironment():
    import utils
    environment = Environment(ENV = os.environ)
    peg_color = 'light-cyan'
    environment['PAINTOWN_PLATFORM'] = ['unix']
    environment['PAINTOWN_USE_PRX'] = False
    environment['PAINTOWN_TESTS'] = {'CheckPython': checkPython}
    environment['PAINTOWN_COLORIZE'] = utils.colorize
    environment['PAINTOWN_NETWORKING'] = True
    environment['LIBS'] = []
    environment['PEG_MAKE'] = "%s %s" % (utils.colorize('Creating peg parser', peg_color), utils.colorize('$TARGET', 'light-blue'))
    environment.Append(BUILDERS = {'Peg' : utils.pegBuilder(environment)})
    environment.Append(CPPPATH = ['#src', '#src/util/network/hawknl'])
    environment['LINKCOM'] = '$CXX $LINKFLAGS $SOURCES -Wl,--start-group $ARCHIVES $_LIBDIRFLAGS $_LIBFLAGS -Wl,--end-group -o $TARGET'

    # Default preference for a graphics renderer / input system
    backends = ['SDL', 'Allegro4', 'Allegro5']

    if utils.useAllegro4():
        backends = ['Allegro4', 'SDL', 'Allegro5']

    if utils.useAllegro5():
        backends = ['Allegro5', 'SDL', 'Allegro4']

    environment.ParseConfig('freetype-config --libs --cflags')
    environment.ParseConfig('libpng-config --libs --cflags')

    if utils.useLLVM():
        llvm(environment)

    custom_tests = {"CheckCompiler": utils.checkCompiler,
                    "CheckSDL" : checkSDL,
                    "CheckAllegro4" : checkAllegro4,
                    "CheckAllegro5" : checkAllegro5}

    return utils.configure_backend(environment, backends, custom_tests)
Пример #23
0
	def parse_commands(self):
		try:
			while True:
				user_input = raw_input(self.display_name + '> ')
				if len(user_input.strip()) == 0:
					print utils.colorize("Type in a command!", "RED")
				elif user_input == 'exit':
					print_text.exit()
					return
				elif self.logged_in:
					if user_input == 'help':
						print_text.help_user()
					elif user_input == 'update':
						self.update_status()
					elif user_input == 'timeline':
						self.get_home_timeline()
					elif user_input == 'logout':
						self.logout()
					elif user_input == 'edit name':
						new_name = self.user_auth.edit_user_name(self.current_user)
						if len(new_name) > 0:
							self.current_user.name = new_name
							self.display_name = new_name + " "
					elif user_input == 'edit password':
						self.user_auth.edit_password(self.current_user)
					elif 'user' in user_input:
						self.get_user_profile(user_input)
					elif user_input == 'stream':
						self.start_streaming()
					else:
						print utils.colorize('The command "' + user_input + '" was not recognized.', "B_RED")
				else:
					if user_input == 'help':
						print_text.help_guest()
					elif 'login' in user_input:
						self.try_login(user_input)
					elif user_input == 'create':
						self.user_auth.create_user(self.auth)
					else:
						print utils.colorize('The command "' + user_input + '" was not recognized.', "B_RED")
		except KeyboardInterrupt:
			print ''
			print_text.exit()
Пример #24
0
	def edit_password(self, current_user):
		try:
			sucess = False
			while not sucess:		
				print 'Type in your new password:'
				print '(type "\cancel" to cancel)'
				password = getpass.getpass('Password: ')
				if password == '\cancel':
					return ''
				elif len(password) == 0:
					print utils.colorize("Password cannot be empty!", "RED")
				double_check = ''
				print 'Say your new password again:'
				double_check = getpass.getpass('Password: ')
				if not password == double_check:
					print utils.colorize("Passwords didn't match, please try again.", "RED")
				else:
					sucess = True
			self.remove_user(current_user.name)
			self.save_user(current_user.name, password, current_user.key, current_user.secret)
		except:
			print utils.colorize('An error occurred while saving your new password, sorry.', "B_RED")
			return ''
Пример #25
0
        return (err, None, None) if err \
            else (None, mouvements, cube_lu)

if __name__=="__main__":
    """
    :Example:
        python poqb.py
        python poqb.py -cYYYYYYYYYOOOBBBRRRGGGOOOBBBRRRGGGOOOBBBRRRGGGWWWWWWWWW
        python poqb.py --cube=YYYYYYYYYOOOBBBRRRGGGOOOBBBRRRGGGOOOBBBRRRGGGWWWWWWWWW
    """

    #On récupère le cube en paramètre ou on utilise celui par défaut
    params = readArgs()
    cube = str(params['cube']) if 'cube' in params else DEFAULT_CUBE

    err, resolution, cube_lu = solve_full(cube)
    if err:
        print("Erreur dans la lecture du cube : " + err)
    else:
        #L'utilisateur a demandé la résolution pas à pas
        if 'tuto' in params:
            print('Résolution de :', "".join([colorize(x) for x in cube]))
            tuto(cube_lu, resolution)

        print('Résolution de :', "".join([colorize(x) for x in cube]) +'\n')
        resolution = " ".join([translate_mvt(x) for x in resolution])
        print('Positionnez la face bleue face à vous et la face blanche face au sol\n')
        print("Puis exécutez la manoeuvre : {}".format(resolution) +'\n')


Пример #26
0
	def on_timeout(self):
		print utils.colorize('Connection lost due to timeout.', "RED")
Пример #27
0
	def on_error(self, status_code):
		print utils.colorize('An error has occurred! Status code = %s' % status_code, "B_RED")
Пример #28
0
#!/usr/bin/env python
#from distutils.core import setup
from setuptools import setup, find_packages
import os
import utils

print utils.colorize("Starting installation of Tweet Bash...", "CYAN")

setup(name="tweet-bash",
      version=utils.app_version,
      description="Twitter app for Ubuntu's bash terminal",
      license="MIT",
      install_requires="tweepy >=1.7.1",
      author="Rodrigo Castro",
      author_email="[email protected]",
      url="http://github.com/roooodcastro/tweet-bash",
      packages = find_packages(),
      keywords= "twitter terminal",
      zip_safe = True)
Пример #29
0
def build_faces(cube, colors=False, space=False):
    """
    build_faces

    Constructions de la représentation des faces du rubik's cube

    :Args:
        cube    {Cube}      Un rubik's cube
        colors  {Boolean}   Utilisation de couleurs pour les terminal ?
                            Defaut False. (mettre à True pour Cube.__str__())
        space   {Boolean}   Espaces entre les facettes ?
                            Defaut False. (mettre à True pour Cube.__str__())

    :Returns:
        {List,List,List,List,List,List,List,List}
                            up, left, front, right, back, down
    """

    up = [
        [cube.cubes['BLU'][2], cube.cubes['BU'][1], cube.cubes['RBU'][2]],
        [cube.cubes['LU'][1],  5,                   cube.cubes['RU'][1]],
        [cube.cubes['LFU'][2], cube.cubes['FU'][1], cube.cubes['FRU'][2]],
    ]

    left = [
        [cube.cubes['BLU'][1], cube.cubes['LU'][0], cube.cubes['LFU'][0]],
        [cube.cubes['BL'][1],  4,                   cube.cubes['FL'][1]],
        [cube.cubes['BLD'][1], cube.cubes['LD'][0], cube.cubes['LFD'][0]],
    ]

    front = [
        [cube.cubes['LFU'][1], cube.cubes['FU'][0], cube.cubes['FRU'][0]],
        [cube.cubes['FL'][0],  1,                   cube.cubes['FR'][0]],
        [cube.cubes['LFD'][1], cube.cubes['FD'][0], cube.cubes['FRD'][0]],
    ]

    right = [
        [cube.cubes['FRU'][1], cube.cubes['RU'][0], cube.cubes['RBU'][0]],
        [cube.cubes['FR'][1],  2,                   cube.cubes['BR'][1]],
        [cube.cubes['FRD'][1], cube.cubes['RD'][0], cube.cubes['RBD'][0]],
    ]

    back = [
        [cube.cubes['RBU'][1], cube.cubes['BU'][0], cube.cubes['BLU'][0]],
        [cube.cubes['BR'][0],  3,                   cube.cubes['BL'][0]],
        [cube.cubes['RBD'][1], cube.cubes['BD'][0], cube.cubes['BLD'][0]],
    ]

    down = [
        [cube.cubes['LFD'][2], cube.cubes['FD'][1], cube.cubes['FRD'][2]],
        [cube.cubes['LD'][1],  0,                   cube.cubes['RD'][1]],
        [cube.cubes['BLD'][2], cube.cubes['BD'][1], cube.cubes['RBD'][2]],
    ]

    #On convertit tous les entiers en la couleur qui leur correspond
    for face in (up, left, front, right, back, down):
        for ligne in range(3):
            for c in range(3):
                #pour chaque case de chaque ligne de chaque face
                if colors:
                    face[ligne][c] = colorize(
                            codeToColor(face[ligne][c]),
                            COULEURS_SPACE if space else None
                        )
                else:
                    face[ligne][c] = codeToColor(face[ligne][c])

    return (up, left, front, right, back, down)
Пример #30
0
        c.rot_UF() #on descend la face blanche sur D

        #on place la face bleue
        #si elle était sur U, elle est à la bonne place maintenant
        if v[1] == 5: #si elle était sur D, elle est sur B maintenant
            c.rot_FR()
            c.rot_FR()
        #on s'intéresse aux cas pù la face bleue est sur L ou R
        #cas où on est sur R maintenant
        elif v[1] == v[0] + 1 or (v[0], v[1]) == (4, 1):
            for x in range(3):
                c.rot_FR()
        #cas où on est sur L maintenant
        elif v[1] == v[0] - 1 or (v[0], v[1]) == (1, 4):
            c.rot_FR()

    return (False, c)

if __name__ == "__main__":

    print('\nExemple lecture_cube()')
    print('====================')

    exemple = 'OGRBWYBGBGYYOYOWOWGRYOOOBGBRRYRBWWWRBWYGROWGRYBRGYWBOG'
    print('input :', ''.join([colorize(c) for c in exemple]))
    error, cube = lecture_cube(exemple)
    if not error:
        print('output:', cube.to_line())
        print(cube)
    print('Erreur :', error)