I'm trying to print the following string in a centralised position in the console, but .center() doesn't seem to work
""" , ,
(.-""-.)
|\ \/ \/ /|
| \ / =. .= \ / |
\( \ o\/o / )/
\_, '-/ \-' ,_/
v \__/ v
\ \__/\__/ /
___\ \|--|/ /___
/` \ / `\
"""
The problem is that in your input string you have spaces before your pixel art.
I used also the answer provided in the comments (link).
import shutil
SIZE = shutil.get_terminal_size()
COLUMNS = SIZE.columns
def tty_center_str(s: str):
print(s.center(COLUMNS))
def tty_center_multiline(s: str):
for line in s.splitlines():
tty_center_str(line.strip())
Output:
>>> tty_center_multiline(s)
, ,
(.-""-.)
|\ \/ \/ /|
| \ / =. .= \ / |
\( \ o\/o / )/
\_, '-/ \-' ,_/
v \__/ v
\ \__/\__/ /
___\ \|--|/ /___
/` \ / `\
Related
This question already has answers here:
How to make win32 console recognize ANSI/VT100 escape sequences?
(14 answers)
How do I print colored text to the terminal?
(64 answers)
Closed 12 months ago.
I took the reference of How to make every character/line print in a random color? and changed the text to ghost ASCII art but the output is not printing the colored art but printing ascii code + the symbols used in the text.
import colorama
import random
text = """
.-----.
.' - - '.
/ .-. .-. \
| | | | | |
\ \o/ \o/ /
_/ ^ \_
| \ '---' / |
/ /`--. .--`\ \
/ /'---` `---'\ \
'.__. .__.'
`| |`
| \
\ '--.
'. `\
`'---. |
) /
\/
"""
colors = list(vars(colorama.Fore).values())
colored_chars = [random.choice(colors) + char for char in text]
print(''.join(colored_chars))
Output :
Try calling os.system('cls') before printing to the console with colors.
Also include r"" before your string to format it correctly (worked for me).
import colorama
import random
import os
text = r"""
.-----.
.' - - '.
/ .-. .-. \
| | | | | |
\ \o/ \o/ /
_/ ^ \_
| \ '---' / |
/ /`--. .--`\ \
/ /'---` `---'\ \
'.__. .__.'
`| |`
| \
\ '--.
'. `\
`'---. |
) /
\/
"""
os.system("cls")
colors = list(vars(colorama.Fore).values())
colored_chars = [random.choice(colors) + char for char in text]
print(''.join(colored_chars))
So, I'm pretty new to python, but I'm currently coding a text-adventure game. I was wondering how I would be able to display the text at the bottom of the screen while an ASCII image is displayed on top, just like SanctuaryRPG.
Alright, so basically, you want to print an ASCII image with text. This shouldn't be too difficult.
Firstly, set the ASCII image to a variable. For example:
img = '''
__,__
.--. .-" "-. .--.
/ .. \/ .-. .-. \/ .. \
| | '| / Y \ |' | |
| \ \ \ 0 | 0 / / / |
\ '- ,\.-"`` ``"-./, -' /
`'-' /_ ^ ^ _\ '-'`
.--'| \._ _./ |'--.
/` \ \ `~` / / `\
/ '._ '---' _.' \
/ '~---~' | \
/ _. \ \
/ .'-./`/ .'~'-.|\ \
/ / `\: / `\'. \
/ | ; | '.`; /
\ \ ; \ \/ /
'. \ ; \ \ ` /
'._'. \ '. | ;/_
/__> '. \_ _ _/ , '--.
.' '. .-~~~~~-. / |--'`~~-. \
// / .---'/ .-~~-._/ / / /---..__.' /
((_(_/ / / (_(_(_(---.__ .'
| | _ `~~`
| | \'.
\ '....' |
'.,___.'
'''
Next, set the text you want to print out to another variable.
text = "Do you want to say hi to the monkey?"
Finally, print the two like this:
print(img)
print(text)
OR:
print(img + "\n\n" + text)
\n Just means a new line.
To do the same as in SanctuaryRPG with Pygame, you need to use a font where each character is the same width (e.g. Courier):
font = pygame.font.SysFont("Courier", text_height)
Split the text into lines with splitlines() (see How to split a python string on new line characters):
img_text = img.splitlines()
Render the text line by line in a loop:
for i, line in enumerate(img_text):
text_surf = font.render(line, True, (255, 255, 0))
window.blit(text_surf, (50, 20 + i * text_height))
Use the following function:
def renderTextImage(surf, font, text, x, y, color):
img_text = text.splitlines()
for i, line in enumerate(img_text):
text_surf = font.render(line, True, color)
surf.blit(text_surf, (x, y + i * text_height))
Minimal example:
repl.it/#Rabbid76/PyGame-AsciiTextImage
import pygame
img_text = r'''
__,__
.--. .-" "-. .--.
/ .. \/ .-. .-. \/ .. \
| | '| / Y \ |' | |
| \ \ \ 0 | 0 / / / |
\ '- ,\.-"`` ``"-./, -' /
`'-' /_ ^ ^ _\ '-'`
.--'| \._ _./ |'--.
/` \ \ `~` / / `\
/ '._ '---' _.' \
/ '~---~' | \
/ _. \ \
/ .'-./`/ .'~'-.|\ \
/ / `\: / `\'. \
/ | ; | '.`; /
\ \ ; \ \/ /
'. \ ; \ \ ` /
'._'. \ '. | ;/_
/__> '. \_ _ _/ , '--.
.' '. .-~~~~~-. / |--'`~~-. \
// / .---'/ .-~~-._/ / / /---..__.' /
((_(_/ / / (_(_(_(---.__ .'
| | _ `~~`
| | \'.
\ '....' |
'.,___.'
'''
def renderTextImage(surf, font, text, x, y, color):
img_text = text.splitlines()
for i, line in enumerate(img_text):
text_surf = font.render(line, True, color)
surf.blit(text_surf, (x, y + i * text_height))
pygame.init()
window = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()
text_height = 16
font = pygame.font.SysFont("Courier", text_height)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill(0)
renderTextImage(window, font, img_text, 50, 20, (255, 255, 0))
pygame.display.flip()
pygame.quit()
exit()
I'm trying to print the following image via python
print("""
____
.\ /
|\\ //\
/ \\// \
/ / \ \
/ / \ \
/ / \ \
/ /______^ \ \
/ ________\ \ \
/ / \ \
/\\ / \ //\
/__\\_\ /_//__\
""")
input()
output
____
.\ /
|\ // / \// / / \ / / \ / / \ \
/ /______^ \ / ________\ \ / / \ /\ / \ ///__\_\ /_//__
hope someone can help me solve this problem
Backslashes escape the newlines, change it to a raw string with r"...":
print(r"""
____
.\ /
|\\ //\
/ \\// \
/ / \ \
/ / \ \
/ / \ \
/ /______^ \ \
/ ________\ \ \
/ / \ \
/\\ / \ //\
/__\\_\ /_//__\
""")
input()
I am having an issue with a Text Based Game I am making for my AP Computer Science principals project. What's supposed to happen is this line of code:
def pI(options):
#PI stands for Player Input
playerInput = (input("==> "))
if playerInput not in options or commands:
print(playerInput + " is not a possible option")
print("Do /options for a list of acceptable options")
playerInput = (input("==> "))
if playerInput == "/commands":
print(commands)
elif playerInput == "/options":
print("Acceptable inouts are" + options)
elif playerInput == "/help":
gHelp()
return(playerInput)
is supposed to check if the player's input is one that can be done. However, with this system, the interpreter does not even check the playerInput. I don't get any errors, but it's not working the way i want it to. The logic makes sense to me, but not the interpreter. Does anyone know why this is? Here is the rest of my code so far for the game if that helps:
#Made by -----------------------------------------------------------#
import sys
import os
import time
import random
os.system("mode con: cols=45 lines=80")
#Commands-----------------------------------------------------------#
commands = ["/options, /Help"]
#Functions----------------------------------------------------------#
def save():
print("This is supposed to save, but it doesn't work yet")
def clear():
os.system('cls')
def back():
pCS
def pI(options):
#PI stands for Player Input
playerInput = (input("==> "))
if playerInput not in options or commands:
print(playerInput + " is not a possible option")
print("Do /options for a list of acceptable options")
playerInput = (input("==> "))
if playerInput == "/commands":
print(commands)
elif playerInput == "/options":
print("Acceptable inouts are" + options)
elif playerInput == "/help":
gHelp()
return(playerInput)
#Graphics-----------------------------------------------------------#
#All Graphic functions start with "g" so that i don't take any
#names I might need later
def gLine():
#Function Draws lines
ps2("******************************************************************************************************************")
def gHeader():
gLine()
ps2("""
___________.__ __ __ __ .__ _____ __________ .__
\__ ___/| |__ ____ / \ / \___________ _/ |_| |__ _____/ ____\ \____ /____ | | ____ ____
| | | | \_/ __ \ \ \/\/ |_ __ \__ \\ __\ | \ / _ \ __\ / /\__ \ | | / ___\ / _ \
| | | Y \ ___/ \ / | | \// __ \| | | Y \ ( <_> ) | / /_ / __ \| |_/ /_/ > <_> )
|____| |___| /\___ > \__/\ / |__| (____ /__| |___| / \____/|__| /_______ (____ /____|___ / \____/
\/ \/ \/ \/ \/ \/ \/ /_____/ """)
gLine()
def gExit():
clear()
save()
gLine()
ps2("""
___________ .__ __ .__
\_ _____/__ __|__|/ |_|__| ____ ____
| __)_\ \/ / \ __\ |/ \ / ___\
| \> <| || | | | | \/ /_/ >
/_______ /__/\_ \__||__| |__|___| /\___ / /\ /\ /\ /\ /\ /\ /\
\/ \/ \//_____/ \/ \/ \/ \/ \/ \/ \/""")
gLine()
sys.exit
def gHelp():
clear()
gLine()
p2("""
___ ___ .__ _____
/ | \ ____ | | ______ / \ ____ ____ __ __
/ ~ \/ __ \| | \____ \ / \ / \_/ __ \ / \| | \
\ Y | ___/| |_| |_> > / Y \ ___/| | \ | /
\___|_ / \___ >____/ __/ \____|__ /\___ >___| /____/
\/ \/ |__| \/ \/ \/ """)
gLine()
print("Welcome to the help menu!")
print("1. Go Back")
options = ["1"]
PI()
if PI == 1:
(back())
def gNorthernLights():
gLine()
ps2(""" ` : | | | |: || : ` : | |+|: | : : :| . `
` : | :| || |: : ` | | :| : | : |: | . :
.' ': || |: | ' ` || | : | |: : | . ` . :.
`' || | ' | * ` : | | :| |*| : : :|
* * ` | : : | . ` ' :| | :| . : : * :.||
.` | | | : .:| ` | || | : |: | | ||
' . + ` | : .: . '| | : :| : . |:| ||
. . ` *| || : ` | | :| | : |:| |
. . . || |.: * | || : : :|||
. . . * . . ` |||. + + '| ||| . ||`
. * . +:`|! . |||| :.||`
+ . ..!|* . | :`||+ |||`
. + : |||` .| :| | | |.| ||` .
* + ' + :|| |` :.+. || || | |:`|| `
. .||` . ..|| | |: '` `| | |` +
. +++ || !|!: ` :| |
+ . . | . `|||.: .|| . . `
' `|. . `:||| + ||' `
__ + * `' `'|. `:
"' `---''''----....____,..^---`^``----.,.___ `. `. . ____,.,-
___,--''''`---'' ^ ^ ^ ^ """'---,..___ __,..---'''
"' ^ ``--..,__ """)
gLine()
#Text Functions-----------------------------------------------------#
def ps(string):
#This function allows the game to type like a real person
#PS is short for "Print Slow"
typing_speed = 70
count = 0
space = False
#This aspect of the function works with the autotext wrap
#To make sure that it only wraps after full words, not
#midway through
for letter in string:
if letter == " " or letter == "":
space = True
else:
space = False
if count >= 50 and space == True:
print('\n')
count = 0
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(random.random()*10.0/typing_speed)
print('')
def ps2(str):
#This function is the same as PS1 but without the Text Wrapping
typing_speed = 600
#Ask Mr. Ortiz how to make previous function based of line len.
for letter in str:
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(random.random()*10.0/typing_speed)
print('')
#Mechanics----------------------------------------------------------#
#Game Loop----------------------------------------------------------#
def titleScreen():
gHeader()
ps("1. Start")
ps("2. Load")
ps("3. Exit")
ps("4. Help")
options = ["1","2","3","4"]
pI(options)
if pI == 1:
dream0()
pCS = dream0()
if pI == 2:
load
if PI == 3:
gExit()
if PI == 4:
gHelp()
def dream0():
clear()
gNorthernLights()
ps("[???] Your name my son..what do the mortals use to summon you?")
pName = str(input("==> "))
ps(pName + "? I'm just as amused by the lower realm's creativity, as their ability to destroy themselves.")
ps("The void..she calls to you" + pName + "She favors you, just as her divinity does to me. You..shall be my avatar. It is time. Her prophecy shall be fullfilled. Awaken, my child!")
time.sleep(3)
clear()
#dream0()
titleScreen()
#Player Data--------------------------------------------------------#
pName = "Yorick"
pTrueName = "kliros"
pCS = titleScreen()
#pCS stands for Player Current Scene
There are several issues here:
if playerInput not in options or commands:
This will activate if playerInput is not in options, or if commands is defined. You meant to say that it should activate if playerInput is not in options AND playerInput is not in commands.
pI(options)
if pI == 1:
dream0()
pCS = dream0()
if pI == 2:
load
if PI == 3:
gExit()
if PI == 4:
gHelp()
Here, you expect pI(options) to return some value, but you never save it. When you check pI == 1, you are checking if the function is equal to 1, which is nonsense. Additionally, pI returns a string, not a number. Instead, you should have the following:
playerInput = pI(options)
if playerInput == "1":
dream0()
pCS = dream0()
if playerInput == "2":
load
if playerInput == "3":
gExit()
if playerInput == "4":
gHelp()
My wish is to make every character or line or whatever you think might look best for an ASCII to look. Basically I have tried colorama and it was only based on one color. What is the best method?
What I have is
print("""
_____ _ _ __ _
/ ____| | | | / _| |
| (___ | |_ __ _ ___| | _______ _____ _ __| |_| | _____ __
\___ \| __/ _` |/ __| |/ / _ \ \ / / _ \ '__| _| |/ _ \ \ /\ / /
____) | || (_| | (__| < (_) \ V / __/ | | | | | (_) \ V V /
|_____/ \__\__,_|\___|_|\_\___/ \_/ \___|_| |_| |_|\___/ \_/\_/
""")
and that is pretty much it. Let me know your thoughts through this!
The valid foreground colors provided by colorama are variables on colorama.Fore. We can retrieve them using vars(colorama.Fore).values(). We can random select a foreground color by using random.choice, feeding it the foreground colors as obtained by vars.
Then we simply apply a randomly-chosen color to each character:
text = """
_____ _ _ __ _
/ ____| | | | / _| |
| (___ | |_ __ _ ___| | _______ _____ _ __| |_| | _____ __
\___ \| __/ _` |/ __| |/ / _ \ \ / / _ \ '__| _| |/ _ \ \ /\ / /
____) | || (_| | (__| < (_) \ V / __/ | | | | | (_) \ V V /
|_____/ \__\__,_|\___|_|\_\___/ \_/ \___|_| |_| |_|\___/ \_/\_/
"""
import colorama
import random
colors = list(vars(colorama.Fore).values())
colored_chars = [random.choice(colors) + char for char in text]
print(''.join(colored_chars))
This will print every character in a different color:
If you want colored lines instead, it's a simple change:
colored_lines = [random.choice(colors) + line for line in text.split('\n')]
print('\n'.join(colored_lines))
You can tailor the list of colors to your needs. For instance, if you want to remove colors which may be similar to your terminal background (black, white, etc.) you can write:
bad_colors = ['BLACK', 'WHITE', 'LIGHTBLACK_EX', 'RESET']
codes = vars(colorama.Fore)
colors = [codes[color] for color in codes if color not in bad_colors]
colored_chars = [random.choice(colors) + char for char in text]
print(''.join(colored_chars))
Which gives: