I compared code to other training example code out there and did a compare and everything matches. Here is my issue: I have a health bar and when I take damage the bar decreases.
The problem is when in my code I use █ the pipe line after the bar never stays put, it always move dynamically. When I use / the pipe bar always stays put and no issue. I'm guessing there is something in my terminal tool (using Pycharm) that it doesn't like ascii code 219. If it matters from reading forums the tool is set to UTF-8. example below so might not format correctly but top part you can see the | being shifted when using █ and the bottom part is fine when using /.
______________________________ __________
CARLOS: 2210/3260 |■■■■■■■■■■■■■■■■■ | 132/132 |//////////|
__________________ __________
CARLOS: 2219/3260 |///////////////// | 132/132 |//////////|
Code:
def get_stats(self):
hp_bar = ""
bar_ticks = (self.hp / self.maxhp) * 100 / 4
mp_bar = ""
mp_ticks = (self.mp / self.maxmp) * 100 / 10
while bar_ticks > 0:
hp_bar += '█'
bar_ticks -= 1
#num_spaces_needed = (100/4) - len(hp_bar)
#str_spaces_needed = ""
#while num_spaces_needed > 0:
#str_spaces_needed += " "
#num_spaces_needed -= 1
while len(hp_bar) < 25:
hp_bar += " "
while mp_ticks > 0:
mp_bar += "/"
mp_ticks -= 1
while len(mp_bar) < 10:
mp_bar += " "
hp_string = str(self.hp) + "/" + str(self.maxhp)
current_hp = ""
if len(hp_string) < 9:
decreased = 9 - len(hp_string)
while decreased > 0:
current_hp += " "
decreased -= 1
current_hp += hp_string
else:
current_hp = hp_string
mp_string = str(self.mp) + "/" + str(self.maxmp)
current_mp = ""
if len(mp_string) < 7:
decreased = 7 - len(mp_string)
while decreased > 0:
current_mp += " "
decreased -= 1
current_mp += mp_string
else:
current_mp = mp_string
print(" _______________________________ __________ ")
print(bcolors.BOLD + self.name + " " +
current_hp + " |" + bcolors.BAR + hp_bar + bcolors.ENDC + "| " +
current_mp + " |" + bcolors.OKBLUE + mp_bar + bcolors.ENDC + "| ")
You have to change your font type
Navigate to File -> Settings -> Editor -> Font
Font: Source Code Pro
Apply -> Ok
Rerun the program
Try the following at the top of your script:
import sys
reload(sys)
sys.setdefaultencoding('utf8')
Related
I have made a python program that recreates an image in excel by filling cells with different shades of red, green and blue. I have made this method to convert a number to a x coordinate in excel:
alph = [i for i in string.ascii_uppercase]
alph.insert(0,'')
def numToExcel(x):
stri = ''
row = x
rdiv26 = row//26
rdiv676 = row//676
stri += alph[(rdiv676)-((rdiv676)//676)*676]
stri += alph[(rdiv26)-((rdiv26)//26)*26]
stri += alph[1+(row%26)]
return stri
I added an empty space at the beginning so the program prints, for example, B3 instead of AAB3. However this means it does not reach for the letter Z. If i do x // 27 the image comes out wavy and it does not fix the issue.
This is my entire program:
import string
import time
import math
import openpyxl
from PIL import Image
from openpyxl import Workbook
from openpyxl.styles import Color, PatternFill, Font, Border
alph = [i for i in string.ascii_uppercase]
alph.insert(0,'')
def rgb_to_hex(r, g, b):
return '%02x%02x%02x' % (r,g,b)
def numToExcel(x):
stri = ''
row = x
rdiv26 = row//26
rdiv676 = row//676
stri += alph[(rdiv676)-((rdiv676)//676)*676]
stri += alph[(rdiv26)-((rdiv26)//26)*26]
stri += alph[1+(row%26)]
return stri
wb = Workbook()
ws = wb.active
im = Image.open('input.jpg')
pix = im.load()
x,y=im.size
start_time = time.time()
ct=0
for j in range(1,y-1):
i = 0
while i < 3*(x-1):
#Debug shi: print("["+"#"*math.floor(20*(ct/(x*3*y)))+"-"*(20-math.floor(20*ct/(x*3*y)))+"] " + str(math.floor(ct/(x*3*y)*100))+"% "+ str(ct) + "/" + str(x*y))
#Debug Shi: print("["+"#"*math.floor(20*(ct/(x*3*y)))+"-"*(20-math.floor(20*ct/(x*3*y)))+"] " + str(math.floor(ct/(x*3*y)*100))+"% "+ str(ct) + "/" + str(x*y*3) + " | (" + numToExcel(i) + "," + str(j) + ") -> (" + numToExcel(i+2) + "," + str(j) +") | " + str(pix[i/3,j][0])+','+str(pix[i/3,j][1])+','+str(pix[i/3,j][2]))
ws[numToExcel(i)+str(j)].fill = PatternFill("solid", fgColor=rgb_to_hex(pix[i/3,j][0],0,0))
ws[numToExcel(i+1)+str(j)].fill = PatternFill("solid", fgColor=rgb_to_hex(0,pix[i/3,j][1],0))
ws[numToExcel(i+2)+str(j)].fill = PatternFill("solid", fgColor=rgb_to_hex(0,0,pix[i/3,j][2]))
i += 3
ct += 3
#Progress Bar and stuff
print("\n"*100)
print("["+"#"*math.floor(20*(ct/(x*3*y)))+"-"*(20-math.floor(20*ct/(x*3*y)))+"] " + str(math.floor(ct/(x*3*y)*100))+"% "+ str(ct) + "/" + str(x*y*3) + " | Row " + str(j))
wb.save("sample2.xlsx")
print("--- Complete! ---\n--- %s seconds ---" % (time.time() - start_time))
And here is the output:
Please ignore any shitty code/math lol. I do not want to use any if statements because I am scared it would slow down the program.
Decided to make a simple mp3 player for terminal. But while I was doing animation I had a problem - it blinks when the frame changes. Heres a video of it: https://youtu.be/in4VLPOfzHw. And the code:
import time, os, glob, eyed3, math, sys
from colorama import init
from mutagen.mp3 import MP3
mpts = glob.glob('*.mp3')
dark_grey = '\033[1;30;40m'
light_grey = '\033[0;37;40m'
white = '\033[1;37;40m'
lime = '\033[1;32;40m'
red = '\033[0;31;40m'
i = 0
song_list = []
for mpt in mpts:
song = MP3(mpt)
duration = math.ceil(song.info.length)
m_duration = duration // 60
s_duration = duration % 60
song = eyed3.load(mpt)
name = song.tag.title
song_list.append([name, [m_duration, s_duration]])
init()
# draw
while True:
# cassette
res = ''
i += 1
res += light_grey + ' ■̅̅̅̅̅̅̅̅̅̅̅̅■ \n'
res += dark_grey + ' |'
res += light_grey + '|############|'
res += dark_grey + '| \n'
res += dark_grey + ' |'
res += light_grey + '|'
if i % 4 == 0:
res += white + ' (/)====(/) '
elif i % 4 == 1:
res += white + ' (-)====(-) '
elif i % 4 == 2:
res += white + ' (\\)====(\\) '
elif i % 4 == 3:
res += white + ' (|)====(|) '
res += light_grey + '|'
res += dark_grey + '| \n'
res += dark_grey + ' |'
res += light_grey + '|############|'
res += dark_grey + '|\n'
res += light_grey + ' ■____________■ \n'
# green line
res += lime + ' ___________________________________\n\n'
# song list
res += red + ' # NAME TIME\n'
for i1 in range(len(song_list)):
res += dark_grey + ' ' + str(i1+1) + '.'
res += white + ' ' + song_list[i1][0] + ' '*(28 - len(song_list[i1][0])) + f'{song_list[i1][1][0]}:{song_list[i1][1][1]}\n'
os.system('cls')
sys.stdout.write(res)
sys.stdout.flush()
time.sleep(0.4)
Can it be fixed or sould I try to make in some other language instead of python?
It's the shelling out to cls that's doing it. Since you're already using ANSI codes for other stuff, try something like:
clear = '\033c'
...
while True:
...
print(clear)
Note that you'll never be able to completely get rid of the screen flicker using the "clear the screen then redraw it" technique, but this will shave several milliseconds from every loop and should decrease the flickering.
The idea is to avoid cleaning the whole screen (os.system('cls')). We could simply move the cursor to top and reprint everything. However moving cursor to top is almost impossible. One workaround I found is to print a lot of special characters that move cursor up one line until all the way to the top.
Reference:
cmd console game; reduction of blinking
The first solution of using \b does not work for me on a windows machine. So I go for the ender_scythe's solution. You have to print an empty line on first run to avoid the issue he/she mentioned. Here is the sample code that does not blink at all:
import time
import os
i = 0
dark_grey = '\033[1;30;40m'
light_grey = '\033[0;37;40m'
white = '\033[1;37;40m'
lime = '\033[1;32;40m'
red = '\033[0;31;40m'
def my_cls(nrow = 0):
if nrow == 0:
os.system('cls')
else:
print('\033[F'*nrow)
def my_display(chars):
print(''.join(chars))
return len(chars)
nrow = 0
while True:
my_cls(nrow)
# cassette
res = []
i+=1
if i == 1:
res.append('\n')
res.append(light_grey + ' ■̅̅̅̅̅̅̅̅̅̅̅̅■ \n')
res.append(dark_grey + ' |')
res.append(light_grey + '|###########|')
res.append(dark_grey + '| \n')
res.append(dark_grey + ' |')
res.append(light_grey + '|')
if i % 4 == 0:
res.append(white + ' (/)====(/) ')
elif i % 4 == 1:
res.append(white + ' (-)====(-) ')
elif i % 4 == 2:
res.append(white + ' (\\)====(\\) ')
elif i % 4 == 3:
res.append(white + ' (|)====(|) ')
res.append(light_grey + '|')
res.append(dark_grey + '| \n')
res.append(dark_grey + ' |')
res.append(light_grey + '|############|')
res.append(dark_grey + '|\n')
res.append(light_grey + ' ■____________■ \n')
# green line
res.append(lime + ' ___________________________________\n\n')
# song list
res.append(red + ' # NAME TIME\n')
nrow = my_display(res)
time.sleep(0.4)
How can I make the program print the CTRL+C to go BACK once down?[Look pictures][Picture][1]
while h < math.inf:
time2 = time.strftime("[%H" + ":%M" + ":%S]")
console = colorama.Fore.WHITE + time2 + '' + defaultname
file = open("Accounts/Failed.txt", "a+")
file2 = open("Accounts/Success.txt", "a+")
x = random.randrange(0, 100)
f = generator()
if x <= 97:
print(console + colorama.Fore.RED + "[FAILED] " + "0x" + f + ' ETH Wallet' + colorama.Fore.WHITE + ' CTRL+C to go BACK')
file.write(str(j) + ":0x" + f + "\n")
time.sleep(0.15)
j += 1
file.close()
elif x >= 97:
print(console + colorama.Fore.GREEN + "[SUCCESS] " + "0x" + f + ' ETH Wallet' + colorama.Fore.WHITE + ' CTRL+C to go BACK')
file2.write(str(h) + ":0x" + f + "\n")
time.sleep(0.15)
h += 1
file2.close()```
[1]: https://i.stack.imgur.com/Qa7Bw.png
So to print CTRL+C to go BACK only on the last loop iteration, you have too check if h + 1 is going to break the loop condition. To do so, you could check the condition h + 1 >= math.inf.
if h + 1 >= math.inf:
print("CTRL+C to go BACK")
This way you'll have to remove the CTRL+C to go BACK in your infos print functions
I am running this code to list the IP addresses on my network along with the mac addresses but i ran into this problem. it says invalid syntax but i can't seem to find what is wrong with it
I've tried removing spaces and replacing them with tabs but it doesn't fix it. i also tried moving them one up or down but still doesn't work. Any help?
The Whole code:
from getmac import get_mac_address
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
minr = int(input("Starting Ip: "))
maxr = int(input("Ending Ip: "))
while True:
for num in range(minr, maxr + 1): #plus one is to include the last digit entered
ip = "192.168.2." + str(num)
from getmac import getmac
exit_code = os.system("ping -n 1 -w 1 " + ip + " > nul") # Windows
#exit_code = os.system("ping -c 1 -W 1 " + ip + " > /dev/null") # Linux
getmac.PORT = 44444 # Default: 55555
if exit_code == 0:
print(ip, bcolors.OKGREEN + "ONLINE" + bcolors.ENDC + get_mac_address(ip=ip, network_request=True)
elif (ip == '192.168.2.' + str(maxr + 1) and exit_code == 0):
print('192.168.2.' + str(maxr), bcolors.OKGREEN + "ONLINE" + bcolors.ENDC + get_mac_address(ip=ip, network_request=True))
print("")
print(bcolors.HEADER + "Beginning" + bcolors.ENDC)
print("")
elif (ip == '192.168.2.' + str(maxr)):
print('192.168.2.' + str(maxr), bcolors.FAIL + "OFFLINE" + bcolors.ENDC)
print("")
print(bcolors.HEADER + "Refreshed" + bcolors.ENDC)
print("")
else:
print(ip, bcolors.FAIL + "OFFLINE" + bcolors.ENDC)
I am supposed to see the IP addressees along with the mac but i get this error code:
$ python test.py
File "test.py", line 34
elif (ip == '192.168.2.' + str(maxr + 1) and exit_code == 0):
^
SyntaxError: invalid syntax
I just forgot to add the ) at the end of the line above. Thanks to #depperm he showed me my mistake. Where it says ''' print(ip, bcolors.OKGREEN + "ONLINE" + bcolors.ENDC + get_mac_address(ip=ip, network_request=True)
at the end of the bracket add one more. '''
i want to run a python file file.py 20 times with 1000 iterations with single run click so that i dont need to click run 20 times manually.
Init()
globalBest=pop[0].chromosome
# Saving Result
fp=open(resultFileName,"w");
fp.write("Iteration,Fitness,Chromosomes\n")
for i in range(0,iterations):
Crossover()
Mutation()
MemoriseGlobalBest()
if funEval >=maxFunEval:
break
if i%20==0:
print "I:",i,"\t Fitness:", bestFitness
fp.write(str(i) + "," + str(bestFitness) + "," + str(bestChromosome) + "\n")
print "I:",i+1,"\t Fitness:", bestFitness
fp.write(str(i+1) + "," + str(bestFitness) + "," + str(bestChromosome))
fp.close()
You can write another script which call your script 20 times. Make a loop and call the file.py 20 times in it.
try:
for iteration in range(20):
Init()
globalBest = pop[0].chromosome
# Saving Result
fp = open(resultFileName, "a")
fp.write("Iteration,Fitness,Chromosomes\n")
for i in range(0, iterations):
Crossover()
Mutation()
MemoriseGlobalBest()
if funEval >= maxFunEval:
break
if i % 20 == 0:
print
"I:", i, "\t Fitness:", bestFitness
fp.write(str(i) + "," + str(bestFitness) + "," + str(bestChromosome) + "\n")
print
"I:", i + 1, "\t Fitness:", bestFitness
fp.write(str(i + 1) + "," + str(bestFitness) + "," + str(bestChromosome))
fp.close()