I was trying to make a basic RNG combat, so people could just copy and paste it and use for their games at our school but I need help on one part.
import random
print("Your Weapon's Stats")
print(" /^\\ ")
print(" | | ")
print(" | | ")
print(" | | ")
print(" | | ")
print(" | | ")
print(" \\\=*=// ")
print(" | ")
print(" (+) ")
print("(+)~~~~~~~~~~~~~~~(+)")
print(" | Damage: | ")
print(" | 1-9 | ")
print(" | Attack Speed: | ")
print(" | 6/10 | ")
print(" | Critical Chance:| ")
print(" | 64% | ")
print("(+)~~~~~~~~~~~~~~~(+)")
your_damage = random.choice("12345789")
enemy_health = 20
enemy_health - your_damage <---it says that not right so what do I do?
print(enemy_health)
You need to use the -= operator to subtract your_damage from enemy_health:
enemy_health -= your_damage
This is equivalent to writing enemy_health = enemy_health - your_damage.
You also want to change random.choice("12345789") to random.randint(1, 9). This selects a random integer between 1 and 9 inclusive, thus ensuring that your_damage is a number instead of a string.
Your code should be:
import random
print("Your Weapon's Stats")
print(" /^\\ ")
print(" | | ")
print(" | | ")
print(" | | ")
print(" | | ")
print(" | | ")
print(" \\\=*=// ")
print(" | ")
print(" (+) ")
print("(+)~~~~~~~~~~~~~~~(+)")
print(" | Damage: | ")
print(" | 1-9 | ")
print(" | Attack Speed: | ")
print(" | 6/10 | ")
print(" | Critical Chance:| ")
print(" | 64% | ")
print("(+)~~~~~~~~~~~~~~~(+)")
your_damage = random.randint(1, 9)
enemy_health = 20
enemy_health -= your_damage
print(enemy_health)
You aren't actually assigning your new value to enemy_health, so you want to do this:
enemy_health = enemy_health - your_damage
Which can be simplified using the -= operator.
So:
enemy_health -= your_damage
To comment about your usage of random.choice. You are almost correct in what you are trying to do, however, you want to use a list of integers instead of a string of numbers. So you can do this instead:
random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Even nicer:
random.choice(range(1, 10))
Related
I am writing a hangman game in python and I have variable called userguess and the user will type in what letter they want to use to guess. However, when the while loop begins it's second repeat, the if statement no longer recognizes the userguess and immediately concludes it to be an incorrect guess. I hope you don't mind the amount of code I am using as an example.
movieletters contains the hiddenword split into letters
defaultletters represents the blanks that have to be filled in by the user
I have tried using exception handlers by creating boolean variables but this hasn't done what I needed it to do.
userguess = input("Guess a letter: ")
while True:
for letter in movieletters:
for defaultletter in defaultletters:
if userguess == letter:
print("You guessed correctly")
score += 1
guessedletters.append(userguess)
print(score, "/", totalletters)
print(guessedletters)
print(movie)
if score == totalletters:
print("\n")
print("*************************************************************************************************")
print(movie)
print("*************************************************************************************************")
print("\n")
print("You guessed all the letters correctly and uncovered the word!")
playagain = input("Would you like to play again? Type y for yes and n for no: ")
if playagain == "y":
main()
else:
quit()
userguess = input("Guess a letter: ")
continue
elif userguess != letter:
incorrectlyguessed += 1
print("INCORRECT!")
print(str(incorrectlyguessed) + "/" + str(tally))
if incorrectlyguessed == 1:
print("""
__________""")
elif incorrectlyguessed == 2:
print("""
|
|
|
|
|__________ """)
elif incorrectlyguessed == 3:
print("""
-----------
|
|
|
|
|__________ """)
elif incorrectlyguessed == 4:
print("""
-----------
| |
|
|
|
|__________ """)
elif incorrectlyguessed == 5:
print("""
-----------
| |
| 0
|
|
|__________ """)
elif incorrectlyguessed == 6:
print("""
-----------
| |
| 0
| |
|
|__________ """)
elif incorrectlyguessed == 7:
print("""
-----------
| |
| 0
| \|/
|
|__________ """)
elif incorrectlyguessed == 8:
print("""
-----------
| |
| 0
| \|/
| |
|__________ """)
elif incorrectlyguessed == 9:
print("""
-----------
| |
| 0
| \|/
| |
|________/_\ """)
if incorrectlyguessed == tally:
print("GAME OVER!")
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
print(movie)
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
playagain = input("Would you like to play again? Type y for yes and n for no: ")
if playagain == "y":
main()
else:
quit()
userguess = input("Guess a letter: ")
continue
I expect the output to show that the character is recognized as one of the letters in the hidden word in the while loop's second phase. This also effects all of the while loop's phases except for the first one.
Here's an example of the current output:
Output
if the movie was cars then movieletters would be ['c', 'a', 'r', 's']
defaultletters would be _ _ _ _
The problem is that it always matches with the first letter in the list of movieletters.
use if userguess in movieletters to check whether it matches or not
userguess = input("Guess a letter: ")
if userguess in movieletters:
print("You guessed correctly")
score += 1
guessedletters.append(userguess)
print(score, "/", totalletters)
print(guessedletters)
print(movie)
if score == totalletters:
print("\n")
print("*************************************************************************************************")
print(movie)
print("*************************************************************************************************")
print("\n")
print("You guessed all the letters correctly and uncovered the word!")
playagain = input("Would you like to play again? Type y for yes and n for no: ")
if playagain == "y":
main()
else:
quit()
userguess = input("Guess a letter: ")
continue
else :
incorrectlyguessed += 1
print("INCORRECT!")
print(str(incorrectlyguessed) + "/" + str(tally))
if incorrectlyguessed == 1:
print("""
__________""")
elif incorrectlyguessed == 2:
print("""
|
|
|
|
|__________ """)
elif incorrectlyguessed == 3:
print("""
-----------
|
|
|
|
|__________ """)
elif incorrectlyguessed == 4:
print("""
-----------
| |
|
|
|
|__________ """)
elif incorrectlyguessed == 5:
print("""
-----------
| |
| 0
|
|
|__________ """)
elif incorrectlyguessed == 6:
print("""
-----------
| |
| 0
| |
|
|__________ """)
elif incorrectlyguessed == 7:
print("""
-----------
| |
| 0
| \|/
|
|__________ """)
elif incorrectlyguessed == 8:
print("""
-----------
| |
| 0
| \|/
| |
|__________ """)
elif incorrectlyguessed == 9:
print("""
-----------
| |
| 0
| \|/
| |
|________/_\ """)
if incorrectlyguessed == tally:
print("GAME OVER!")
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
print(movie)
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
playagain = input("Would you like to play again? Type y for yes and n for no: ")
if playagain == "y":
main()
else:
quit()
userguess = input("Guess a letter: ")
continue
Basically, my assignment is to simulate rolling dice and printing them out side by side depending on what was rolled. The dice have take up 5 lines each so I need a way to print out all 5 lines next to another die result of all 5 lines.
The program that I have been trying attempted to convert the functions into regular strings but it wasn't working and I also tried putting ,end = '' in the functions themselves and simply put them right under each other but I had no luck there either. I only posted in the case of if the first die is a 1.
import random
def roll_dice():
return random.choice(['1','2','3','4','5','6'])
def display_die1():
print("+-------+")
print("| |")
print("| * |")
print("| |")
print("+-------+")
def display_die2():
print("+-------+")
print("| * |")
print("| |")
print("| * |")
print("+-------+")
def display_die3():
print("+-------+")
print("| * |")
print("| * |")
print("| * |")
print("+-------+")
def display_die4():
print("+-------+")
print("| * * |")
print("| |")
print("| * * |")
print("+-------+")
def display_die5():
print("+-------+")
print("| * * |")
print("| * |")
print("| * * |")
print("+-------+")
def display_die6():
print("+-------+")
print("| * * * |")
print("| |")
print("| * * * |")
print("+-------+")
def main():
pic1, pic2, pic3, pic4, pic5, pic6 = display_die1(), display_die2(), display_die3(), display_die4(), display_die5(), display_die6()
print(f"Craps: A Popular Dice Game")
prompt = input(f"Press <Enter> to roll the dice.")
if prompt == (""):
x = roll_dice()
y = roll_dice()
add = int(x) + int(y)
if x == '1':
if y == '1':
print(pic1, end = '')
print(pic1)
if y == '2':
print(pic1, end = '')
print(pic2)
if y == '3':
print(pic1, end = '')
print(pic3)
if y == '4':
print(pic1, end = '')
print(pic4)
if y == '5':
print(pic1, end = '')
print(pic5)
if y == '6':
print(pic1, end = '')
print(pic6)
stopper = int(x) + int(y)
if add == (7 or 11):
print(f"You rolled a {add} on your first roll.")
print(f"You win!")
elif add == (2 or 3 or 12):
print(f"You rolled a {add} on your first roll.")
print(f"You lose!")
else:
print(f"You rolled a {add} on your first roll.")
print(f"\nThat's your point. Roll it again before you roll a 7 and lose!")
while add != (7 or stopper):
proceed = input(f"\nPress <Enter> to roll the dice.")
if proceed == (""):
x = roll_dice()
y = roll_dice()
add = int(x) + int(y)
if (add == 7):
print(f"You rolled a 7.")
print(f"You lose!")
break
elif (add == stopper):
print(f"You rolled a {stopper}.")
print(f"You win!")
break
else:
print(f"You rolled a {add}")
main()
I would expect the output to be two dice displaying next to each other with three spaces in between but the actual output is a very jumbled, twisted version of the two dice on one line.
You have to keep dice as lists of rows
die3 = [
"+-------+",
"| * |",
"| * |",
"| * |",
"+-------+",
]
die4 = [
"+-------+",
"| * * |",
"| |",
"| * * |",
"+-------+",
]
and then you can use zip() to create pairs [first row of die3, first row of die4], [second row of die3, second row of die4], etc. And then you can concatenate pair using "".join() and display it
for rows in zip(die3, die4):
#print(rows)
print(''.join(rows))
+-------++-------+
| * || * * |
| * || |
| * || * * |
+-------++-------+
you can do the same with more dice
for rows in zip(die3, die4, die4, die3):
print(''.join(rows))
+-------++-------++-------++-------+
| * || * * || * * || * |
| * || || || * |
| * || * * || * * || * |
+-------++-------++-------++-------+
If you need space between dice then use space in " ".join(rows)
One big problem is in this line:
pic1, pic2, pic3, pic4, pic5, pic6 = display_die1(), display_die2(), display_die3(), display_die4(), display_die5(), display_die6()
Let's simplify it to a single assignment and find the mistake:
pic1 = display_die()
will result in the following:
In the console:
+-------+
| * * * |
| |
| * * * |
+-------+
And pic1 == None.
Another problem is, that you can only print line by line and not jump back. So you need a mechanism, to print in one line two "lines" for each dice.
A solution would be to store every line of a dice in a list element:
def get_dice_1():
lines = [
"+-------+",
"| * * * |",
"| |",
"| * * * |",
"+-------+"
]
To print two dice:
def print_dices(list_dice_1, list_dice_2):
for i range(len(list_dice_1)):
line = list_dice_1[i] + " " + list_dice_2[i]
print(line)
I think the best solution would be to store the dice in a list and then you can print each row of the dice with string formatting methods. An example of this would be:
import random
dice_list = [
[
"+-------+",
"| |",
"| * |",
"| |",
"+-------+"],
[
"+-------+",
"| * |",
"| |",
"| * |",
"+-------+"],
[
"+-------+",
"| * |",
"| * |",
"| * |",
"+-------+"],
[
"+-------+",
"| * * |",
"| |",
"| * * |",
"+-------+"],
[
"+-------+",
"| * * |",
"| * |",
"| * * |",
"+-------+"],
[
"+-------+",
"| * * * |",
"| |",
"| * * * |",
"+-------+"]
]
roll1 = random.randint(0, 5)
roll2 = random.randint(0, 5)
for i in range(5): # number of rows of strings per dice
print("{} {}".format(dice_list[roll1][i], dice_list[roll2][i]))
Which outputs something like this:
+-------+ +-------+
| * * * | | * * * |
| | | |
| * * * | | * * * |
+-------+ +-------+
Something to note though is the range of dice rolls with this method is 0-5 so if you wanted to say, print('You rolled a 2 and a 5') you would have to add 1 to both roll1 and roll2 so the numbers will match up!
Edit:
I know that there is already an answer selected to this post but here is an alternate solution using the yield keyword which can be used in sequences. I had this thought before but didn't have enough time to make the code for it. If anything, it is nice to see another way to accomplish the same thing. :)
def display_die1():
yield ("+-------+")
yield ("| |")
yield ("| * |")
yield ("| |")
yield ("+-------+")
def display_die2():
yield ("+-------+")
yield ("| * |")
yield ("| |")
yield ("| * |")
yield ("+-------+")
dice1 = display_die1()
dice2 = display_die2()
for line in range(0,5):
print(f"{next(dice1)} {next(dice2)}")
Here is the output:
+-------+ +-------+
| | | * |
| * | | |
| | | * |
+-------+ +-------+
I hope it helps!
################ My Older answer
Using docstrings instead of printing each individual line will give you a more consistent output.
def display_die1():
dice = '''
+-------+
| |
| * |
| |
+-------+
'''
return dice
def display_die2():
dice = '''
+-------+
| * |
| |
| * |
+-------+
'''
return dice
print(f"{str(display_die1())} {str(display_die2())}")
Not side by side but one on top of the other in this case.
Here is the output
python ./testing/dice_test.py
+-------+
| |
| * |
| |
+-------+
+-------+
| * |
| |
| * |
+-------+
I am trying to make a text-based tic tac toe game, made of mostly nested ifs. But my 3rd if statement doesn't execute what its supposed to.
I didnt know what do, i was pretty confused, as i am a complete beginner.
print("Welcome to the text-based Tic Tac Toe!")
print(" 1| 2 |3 ")
print(" ---------")
print(" 4| 5 |6 ")
print(" ---------")
print(" 7| 8 |9 ")`enter code here`
print("You can choose where you want to place your letter")
print("By choosing the number of that spot or place in the grid")
choice=input("What do you want to be(X/O)?: ")
while(choice=="X"):
plychoice=int(input("Where would you like to place your letter? "))
if plychoice==1:*#This is if the player chooses to place their letter in the "1" slot*
print(" X| | ")
print(" ---------")
print(" | O | ")
print(" ---------enter code here")
print(" | | ")
plychoice=int(input("Where would you like to place your letter? "))
if plychoice==9:#This is if the player chooses to place their letter in the "9" slot
print(" X| |O ")
print(" ---------")
print(" | O | ")
print(" ---------")
print(" | |X ")
plychoice==int(input("Where would you like to place your letter? "))
if plychoice==7:#This is if the player chooses to place their letter in the "7" slot
print(" X| |O ")
print(" ---------")
print(" O| O | ")
print(" ---------")
print(" X| |X ")
plychoice==int(input("Where would you like to place your letter? "))
if plychoice==8:#This is if the player chooses to place their letter in the "8" slot
print(" X| |O ")
print(" ---------")
print(" O| O | ")
print(" ---------")
print(" X| X |X ")
print("YOU WON!!!")
i expect the 3rd nested if statement to execute its code.
I'm trying to create a hangman game with python. I know there is still a lot to complete but I'm trying to figure out the main component of the game which is how to compare the user inputted string (one letter) with the letters in one of the three randomly selected words.
import random
print("Welcome to hangman,guess the five letter word")
words =["china", "ducks", "glass"]
correct_word = (random.choice(words))
guess = input(str("Enter your guess:"))
guess_left = 10
guess_subtract = 1
if guess == "":
guess_left = guess_left - guess_subtract
print("you have" + guess_left + "guesses left")
I think you need a skeleton and then spend some time to improve the game.
import random
print "Welcome to hangman, guess the five letter word"
words = ["china", "ducks", "glass"]
correct_word = (random.choice(words))
trials = 10
for trial in range(trials):
guess = str(raw_input("Enter character: "))
if (len(guess) > 1):
print "You are not allowed to enter more than one character at time"
continue
if guess in correct_word:
print "Well done! '" + guess + "' is in the list!"
else:
print "Sorry " + guess + " does not included..."
Your next step could be print out something like c_i__ as well as the number of trials left. Have fun :)
When you finish with the implementation, take some time and re-implement it using functions.
I've completed this project yesterday; (to anyone else reading this question) take inspiration if needed.
import random
stages = ['''
+---+
| |
O |
/|\ |
/ \ |
|
=========
''', '''
+---+
| |
O |
/|\ |
/ |
|
=========
''', '''
+---+
| |
O |
/|\ |
|
|
=========
''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========
''', '''
+---+
| |
O |
|
|
|
=========
''', '''
+---+
| |
|
|
|
|
=========
''']
#used to choose random word
random_lst=['addition','adequate','adjacent','adjusted','advanced','advisory','advocate','affected','aircraft','alliance','although','aluminum','analysis','announce','anything','anywhere','apparent','appendix','approach','approval','argument','artistic','assembly']
chosen_word = random.choice(random_lst)
#used to create display list + guess var
print("Welcome to hangman! ")
print("--------------------")
print("you have 6 lives." )
print(" ")
print (stages[-1])
display = []
for letters in chosen_word:
display += "_"
print(display)
print(" ")
#used to check if guess is equal to letter, and replace pos in display if yes.
lives = 6
game_over = False
#use the var guesses to store guesses and print at every guess to let player know what letters they tried already.
guesses = ""
while not game_over:
guess = input("Guess a letter. ")
print(" ")
guesses += (guess + " , ")
for pos in range(len(chosen_word)):
letter = chosen_word[pos
if letter == guess:]
display[pos] = letter
print("√")
print("- - -")
print(" ")
if display.count("_") == 0:
print("Game over. ")
game_over = True
elif guess not in chosen_word:
lives -= 1
print(f"Wrong letter. {lives} lives left. ")
print("- - - - - - - - - - - - - - - - - - -")
print(" ")
if lives == 0:
print (stages[0])
elif lives == 1:
print (stages[1])
elif lives == 2:
print (stages[2])
elif lives == 3:
print(stages[3])
elif lives == 4:
print(stages[4])
elif lives == 5:
print(stages[5])
elif lives == 6:
print(stages[6])
elif lives == 0:
game_over = True
print("Game over. ")
print(f"letters chosen: {guesses}")
print(" ")
print(display)
print(" ")
if lives == 0 or display.count("_") == 0:
break
if lives == 0:
print("Game over. You lose.")
elif lives > 0:
print("Congrats, you win! ")
What you can do is treat the string like an array/list.
So if you use loops:
x = ""#let's assume this is the users input
for i in range(len(y)): #y is the string your checking against
if x == y[i]:
from here what I'm thinking is that if they are equal it would add that letter to a string
Let's say the string is "Today was fun" then would have an array like this, [""."" and so on but you'd have to find a way to factor in spaces and apostrophes. So if the letter is == to that part of the string
#this is a continuation of the code, so under if
thearray[theposition] == the letter
But looking a your code your game is diffrent from the regular one so, also consider using a while look
gamewon = False
number of trials = 10
while gamewon == False and number of trials > 0:
#the whole checking process
if x == guess:
gamewon == True
print ........# this is if your doing word for word else use
the code above
else:
number of trials = number of trials - 1
I think that's it I know its a bit all over the place but you can always ask for help and I'll explain plus I was referring to your code things i thought you could fix
First you should accept both a and A by using guess = guess.lower(). The you have to search the string for the character guessed and find the positions.
guess = guess.lower()
# Find the position(s) of the character guessed
pos = [idx for idx,ch in enumerate(correct_word) if ch == guess]
if pos:
print('Letter Found')
guess_left -= 1
Another way to understand the for-loop is:
pos = []
for idx,ch in enumerate(correct_word):
if ch == guess:
pos.append(idx)
Imagine the user has input(ed) the letter 'f'. Then the error below pops up.
wrdsplit = list('ferret')
guess = input('> ')
# user inputs `f`
print(wrdsplit.index(guess))
But this results in ValueError: 'f' is not in list.
OMG....... Thank you guys so much for your help. I finally fixed it. Here... have fun playing my Hangman Game:
import random
import time
import collections
def pics():
if count == 0:
print (" _________ ")
print ("| | ")
print ("| 0 ")
print ("| /|\ ")
print ("| / \ ")
print ("| ")
print ("| ")
elif count == 1:
print (" _________ ")
print ("| | ")
print ("| 0 ")
print ("| /|\ ")
print ("| / ")
print ("| ")
print ("| ")
elif count == 2:
print (" _________ ")
print ("| | ")
print ("| 0 ")
print ("| /|\ ")
print ("| ")
print ("| ")
print ("| ")
elif count == 3:
print (" _________ ")
print ("| | ")
print ("| 0 ")
print ("| /| ")
print ("| ")
print ("| ")
print ("| ")
elif count == 4:
print (" _________ ")
print ("| | ")
print ("| 0 ")
print ("| | ")
print ("| ")
print ("| ")
print ("| ")
elif count == 5:
print (" _________ ")
print ("| | ")
print ("| GAME OVER ")
print ("| YOU LOSE ")
print ("| ")
print ("| ")
print ("| (**)--- ")
print("Welcome to HANGMAN \nHave Fun =)")
print("You can only get 5 wrong. You will lose your :\n1. Right Leg\n2.Left Leg\n3.Right Arm\n4.Left Arm\n5.YOUR HEAD... YOUR DEAD")
print("")
time.sleep(2)
words = "ferret".split()
word = random.choice(words)
w = 0
g = 0
count = 0
correct = []
wrong = []
for i in range(len(word)):
correct.append('#')
wrdsplit = [char for char in "ferret"]
while count < 5 :
pics()
print("")
print("CORRECT LETTERS : ",''.join(correct))
print("WRONG LETTERS : ",wrong)
print("")
print("Please input a letter")
guess = input("> ")
loop = wrdsplit.count(guess)
if guess in wrdsplit:
for count in range(loop):
x = wrdsplit.index(guess)
correct[x] = guess
wrdsplit[x] = '&'
g = g + 1
if "".join(correct) == word:
print("Well done... You guessed the word in", g ,"guesses and you got", w , "wrong")
print("YOU LIVED")
break
elif guess not in wrdsplit:
wrong.append(guess)
w = w + 1
g = g + 1
count = count +1
pics()
print("The correct word was : ",word)
Try this code to see if it works and does what you want
# Get this from a real place and not hardcoded
wrdsplit = list("ferret")
correct = ["-"]*len(wrdsplit) # We fill a string with "-" chars
# Ask the user for a letter
guess = input('> ')
if guess in wrdsplit:
for i, char in enumerate(wrdsplit):
if char == guess:
correct[i-1] = guess
# Calculate the number of guesses
if "-" in correct:
g = len(set(correct)) - 1
else:
g = len(set(correct))
# Print the right word
print("".join(correct))
The set generates an array without duplicates to count how many guesses he has done, if a "-" is found, one is substracted as that character is not a guess.
The only error I am seeing in here (based on your earlier code) is:
if guess in wrdsplit:
for count in range(len(wrdsplit)):
x = wrdsplit.index(guess)
wrdsplit[x] = '&'
correct[x] = guess
g = g + 1
wrdsplit[x] = '&' # x is out of scope
if "".join(correct) == word:
print("Well done... You guessed the word in", g ,"guesses and you got", w , "wrong")
print("YOU LIVED")
break
Now if you were to continue to retry things in here looking for f, it won't work because you've changed 'f' to '&' so you will get an error for f not in list. You just got caught in a nasty little bug cycle.
You should consider using dictionaries for this instead.