I'm making a fighting game with HP bars etc. I did almost everything except HP bars. I simply can't stop it slides when the first HP bar's value changes. How can I fix it?
def get_hpbar(hpoints, hpoints2, name1, name2):
bar1 = hpoints2 / 2
bar2 = hpoints / 2
print(name1, " " * 64, name2)
print("HP[{}]:".format(hpoints2), int(bar1) * "|", " ", end="")
print("HP[{}]:".format(hpoints), int(bar2) * "|")
Example of unwanted situation
Example of wanted display
Thanks in advance!
One easy way to solve the problem without worrying about formatting is just add spaces to make the gap constant.
def get_hpbar(hpoints, hpoints2, name1, name2):
bar1 = hpoints2 / 2
bar2 = hpoints / 2
print(name1, " " * 64, name2)
print("HP[{}]:".format(hpoints2), int(bar1) * "|", int(50-bar1) * " " ," ", end="")
print("HP[{}]:".format(hpoints), int(bar2) * "|")
Since you're relying on character count for alignment, you likely want to "pad" the hp bar with empty slots (spaces) to keep them at 100 size, while reducing the printed characters at will.
e.g.
|||||||||| < before hit
|||||| < after hit (fill with spaces)
You can use the string method ljust to help you with that. e.g.
hp_bar = ('|' * hp).ljust(100, ' ')
print(hp_bar)
The ljust method justifies content to the left (ljust = left justify) by padding the right with character until the string reaches the specified size.
Related
This program will output a right triangle based on user specified height triangle_height and symbol triangle_char.
(1) The given program outputs a fixed-height triangle using a * character. Modify the given program to output a right triangle that instead uses the user-specified triangle_char character.
(2) Modify the program to use a loop to output a right triangle of height triangle_height. The first line will have one user-specified character, such as % or *. Each subsequent line will have one additional user-specified character until the number in the triangle's base reaches triangle_height. Output a space after each user-specified character, including a line's last user-specified character.
I'm having trouble figuring out how to create a space between my characters. Example input is % and 5. My code is:
triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')
for i in range (triangle_height):
print((triangle_char) * (i + 1))
my output is:
%
%%
%%%
%%%%
%%%%%
while expected output is:
%
% %
% % %
% % % %
% % % % %
You need to use join(). This would work:
for i in range(triangle_height):
print(' '.join(triangle_char * (i + 1)))
It is adding spaces between every character because strings are iterable.
This may be optimized a bit by having a list of the characters and appending 1 character in each iteration, rather than constructing triangle_char * (i+1) every time.
This should fix the white space errors:
for i in range(triangle_height):
print(' '.join(triangle_char * (i + 1)) + ' ')
for i in range(triangle_height+1):
print(f'{triangle_char} '*i)
I see the popular way so far is using join, but another way while trying to stay true to the original idea is you simply can add a white space after each character. See below:
triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')
for i in range(triangle_height):
print((triangle_char + ' ') * (i + 1))
There are some really good suggestions on here. Another approach is to use an incremented variable in a while loop as shown below:
triangle_char = input("Enter a character:\n")[0]
triangle_height = int(input("Enter triangle height:\n"))
i = 0
while (i <= triangle_height):
print((triangle_char + ' ') * i)
i += 1
With the example above, i iterates until it is equal to triangle_height and uses polymorphism to generate a quantity of (triangle_height + ' ') based on the value of i. This will generate the right triangle this lab requires. The space is used to format the triangle per lab requirements.
Another method is using the .join() feature, and it certainly would work well here, but is not taught until CH7 of this book where you learn about input and CSV files. I am unsure if your professor would approve of using this, and I am only saying this because my professor was strict about using material not covered.
An additional method mentioned already is to use a for loop with the use of the range() feature containing an expression:
triangle_char = input("Enter a character:\n")[0]
triangle_height = int(input("Enter triangle height:\n"))
for i in range((triangle_height + 1)):
print((triangle_char + ' ') * i)
The end point of range() being just triangle_height would not suffice because the value specified as the end point is not included in the sequence. This would make a right triangle with a height of 4 even if triangle_height was 5 Therefore, you must use the expression (triangle_height + 1). From there, the output is set up similarly to my first solution.
Try adding a whitespace in the print statement.
height = int(input())
symbol = (input())
print()
for i in range(height): #Loop for every index in the range 0-height
print((symbol + ' ') * (i + 1)) #Add whitespace to symbol
Let's say we have a text "Welcome to India". And I want to multiply this string with 3, but to appear with comma delimitation, like "Welcome to India, Welcome to India, Welcome to India". The thing is I know this piece of code could work:
a = 'Welcome to India'
required = a * 3 # but this code is not comma-delimited.
Also, this piece of code doesn't work as well
required = (a + ", ") * 3 # because it puts comma even at the end of the string
How to solve this problem?
", ".join(["Welcome to India"]*3)
Based on the part of your code that you say doesn't work well because it adds a comma to the end, you can modify it like this:
required = (a + ", ") * 2 + a
Or if you don't like it, you can use sum instead of multiply, it's not the optimal way, for sure, but it will work:
a = 'Welcome to India'
required = a + ", " + a + ", " + a
Define Function and you can use it.
def commaFunc(value, count):
buffer = []
for x in range(count):
buffer[x] = value
return ",".join(buffer)
I have a 2d list [1,2,3,4],[4,3,3,1],[3,2,1,1],[2,2,2,1] and I want to print it out to match the following format.
0123
XXXXXXXX
0*1234*0
1*4331*1
2*3211*2
3*2221*3
XXXXXXXX
0123
It should not be hard coded and the length of the list = n so this list n=4 but if list n=5 there would be 5 digits per row and the number on the sides would go 0,1,2,3,4.
So far all I have is:
for row in board:
for column in row:
print(column, end="")
print("")
Which only outputs the list as:
1234
4331
3211
2221
please help me add all the special stuff.
so I find a solution for what you want to do however I think it can be improved a lot (not program quite a lot in python), but I'll leave it here anyways :)
print(" ", end="")
for x in range(len(board)):
print(x, end="")
print()
for x in range(len(board)+4):
print("X", end="")
print()
for num,row in enumerate(board):
print(f"{num}*", end="")
for column in row:
print(column, end="")
print(f"*{num}", end="")
print("")
for x in range(len(board)+4):
print("X", end="")
print()
print(" ", end="")
for x in range(len(board)):
print(x, end="")
print()
Well for the first line you pretty much print 2 spaces, followed by all the digits between 0 and the number of columns in your board. You can use the "range" function for this. Then you must print the correct amount of 'X'. The correct amount is number of columns + 4, I think you can see why.
You should keep a counter starting from 0. For each row you print, you must print the string value of the counter, followed by an asterisk(*), followed by your row, followed by an asterisk(*) and finally followed by the same counter value. You must increment the counter by one for each row.
The last 2 rows are the same as top 2.
I do not want to share my code because this is such a simple problem, I think solving it on your own will help you in the long run.
Probably an unpopular opinion, but I think these kinds of problems are really fun.
This solution formats the contents correctly, even if you change the number of rows, and even the number of items in each row.
def draw_board(board):
# determining the number of elements in a row,
# this is used for printing the X's
# and printing the spaced ranges (i.e. " 0123 ")
n = len(board[0])
# calculating the total width of the board,
# + 4 is because of the "0*...*0" situation
width = n + 4
# calculating margin of the spaced ranges
# (i.e. calculating how much space on each side)
margin = int(n / 2)
# printing the spaced ranges using the margin
print(" " * margin + "".join(str(num) for num in list(range(n))) + " " * margin)
# printing the XXXX
print("X" * width)
# printing the row index number,
# with the *,
# along with the numbers in the row,
# followed by the * and the row number
for row in range(len(board)):
print(str(row) + "*" + "".join(str(elem) for elem in board[row]) + "*" + str(row))
# printing the XXXX
print("X" * width)
# printing the spaced ranges using the margin
print(" " * margin + "".join(str(num) for num in list(range(n))) + " " * margin)
b = [
[1,2,3,4],
[4,3,3,1],
[3,2,1,1],
[2,2,2,1]
]
draw_board(b)
# OUTPUT:
# 0123
# XXXXXXXX
# 0*1234*0
# 1*4331*1
# 2*3211*2
# 3*2221*3
# XXXXXXXX
# 0123
Edited to remove my own tests and to reflect given problem.
Below is a code I made in Python for our lab activity which makes a triangle.
side = input("Input side: ")
def triangle(x):
print ((x - 1)*" "),"*"
asterisk = "*"
space = side
for i in range(x):
asterisk = "**" + asterisk
space = (space-1) * " "
print space,asterisk
triangle(side)
The output should be this:
*
***
*****
I got the number of asterisks on each row correctly, but I cannot figure out how to make the necessary amount of spaces to make it look like a triangle. Using the above code, which I think might be the solution, always produces an error at line 9. Any help I appreciated. (I'm new here so if I violated some rules please let me know.) Thanks and good day!
You are getting the error(TypeError) because you are assigning the space variable with a string type, and then you are subtracting it in the next loop. Edited code would look like this (In python 2.7) and Never mix 4 spaces and 8 spaces indentation.
side = input("Input side: ")
def triangle(x):
print ((x)*" "),"*"
asterisk = "*"
spaces = side
for i in range(x):
asterisk = "**" + asterisk
spaces -= 1
print ' ' * spaces,
print asterisk
triangle(side)
I write a new one in python3.5,And it may be suit for you.But it is not prefect
side = 4
def triangle(x):
for y in range(1,x):
s = 2*y - 1
b = x - y
print(" "*b+"*"*s)
triangle(side)
Output:
*
***
*****
Here is the code to have an isosceles triangle:
def print_triangle(n):
for i in range(1, n+1):
print (" "*(n-i), end=" ")
print (("*"*i)+(i*"*"))
print(print_triangle(6))
Output:
**
****
******
********
**********
************
None
I am trying to clean up my code for an assignment by running pylint over it with the google python style rc file. I just want to confirm that this is the correct style for the the first print line, as it look pretty weird, but the google style rcfile is showing that it is the correct style. I know that the length of each line mustn't exceed 80 characters
for position, length in STEPS:
guess = prompt_guess(position, length)
score = compute_score(guess, position, word)
total = + total + score
print("Your guess and score were: " + ('_' * position + str(guess) +
('_' * (len(word) - length -
position))) + " : " +
str(score))
print("")
I would've formatted it like this:
for position, length in STEPS:
guess = prompt_guess(position, length)
score = compute_score(guess, position, word)
total = + total + score
print("Your guess and score were: " + ('_' * position + str(guess) +
('_' * (len(word) - length -position))) + " : " + str(score))
print("")
Any clarification would be appreciated, thanks
You shouldn't build your string inside print.
When it comes to a very long message, take several steps to build it.
s = "Your guess and score were: "
s += '_' * position
s += str(guess)
s += '_' * (len(word) - length - position)
s += " : "
s += str(score))
You can make it a bit cleaner by using the str.format method.
The parameters will replace the curly braces, according to the names given:
pad1 = '_' * position
pad2 = '_' * (len(word) - length - position)
s = "Your guess and score were: {pad1}{guess}{pad2} : {score}"
s = s.format(pad1=pad1, pad2=pad2, guess=guess, score=score)
This allows you to indent the parameters as a listing, in case their names are long:
s = s.format(pad1=pad1,
pad2=pad2,
guess=guess,
score=score)
If the definition of each parameter is short enough, you can send it to the format method:
s = "Your guess and score were: {pad1}{guess}{pad2} : {score}"
s = s.format(pad1='_' * position,
pad2='_' * (len(word) - length - position),
guess=guess,
score=score)
If your string has a lot of values to be interpolated, you can get rid of the variable names, but then, the curly braces will be replaced by the parameters in the same order:
s = "Your guess and score were: {}{}{} : {}"
s = s.format(pad1, guess, pad2, score)
See PEP-8 on indentation:
# YES: Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
var_three, var_four)
# NO: Arguments on first line forbidden when not using vertical alignment.
foo = long_function_name(var_one, var_two,
var_three, var_four)
(Consistent with Google Python Style Guide on indentation.)
Also, should a line break before or after a binary operator?:
# NO: operators sit far away from their operands
income = (gross_wages +
taxable_interest +
(dividends - qualified_dividends) -
ira_deduction -
student_loan_interest)
# YES: easy to match operators with operands
income = (gross_wages
+ taxable_interest
+ (dividends - qualified_dividends)
- ira_deduction
- student_loan_interest)
Correct, indentation depends on previous line's parentheses. But readability is more than just passing pylint, consider:
print("Your guess and score were: {PAD1}{GUESS}{PAD2} : {SCORE}"
"".format(PAD1='_' * position,
GUESS=guess,
PAD2='_' * (len(word) - length - position),
SCORE=score))
(Use of string concatenation makes for easier formatting of longer strings.)