Creating a RPG game chest - python

So i' trying to create a chest for a rpg game i'm working on and i'm having a really difficult time implementing probability along with making sure one item always drops on open. I was able to get the probability down but whenever i get it to work i'm unable to make the potion drop along with the weapon. Any help would be greatly appreciated! And yes my items are named from fairy tail.
I've already tried giving the items weight but even so i'm unable to make sure the potion drops
import random
-------------------------------------------------------------------------
Chestitems = [
"constant: Potion",
"common: Bow",
"common: Sword",
"common: Spear",
"uncommon: irondragon_Bow",
"uncommon: irondragon_Sword",
"uncommon: irondragon_Spear",
"rare: skydragon_Bow",
"rare: skydragon_Sword",
"rare: skydragon_Spear",
"legendary: firedragon_bow",
"legendary: firedragon_Sword",
"legendary: firedragon_Spear"
]
while(True):
OpenChest = input("Type 'open' to open the Chest!")
if OpenChest == "open":
print(random.choice(Chestitems))
else:
break
The code i have above is what i have working. Consider i'm self taught with no schooling it's really hard to find anything that helped me completely.

If you always want a potion plus some other item, you can do this:
print("You found a potion plus a " + random.choice(Chestitems))
Also, it might be better to arrange your common/rare/etc. items into separate lists:
common_items = ["Bow", "Sword", "Spear"]
uncommon_items = ["Irondragon Bow", "Irondragon Sword", "Irondragon Spear"]
# etc. for rare_items and legendary_items
Then, you can roll a random number from 1 to 100 to pick which list to choose from:
die_roll = random.randint(1, 100)
if die_roll < 75:
items = common_items
elif die_roll < 90:
items = uncommon_items
elif die_roll < 98:
items = rare_items
else:
items = legendary_items
print("You found a potion plus a " + random.choice(items))

Related

Generating a random number (1-2) as a variable then getting python to do one of two things based on the variable generated

I am making a card game and with 2 players. I want to make a system where it randomly selects one of the players then that player will go first. Here is my code. I am programming in python.
A random number between one and two is determined to decide which player will pick the first card.
print("Determining which player will go first...")
first = print(random.randint(1,2))
if first == int(1) :
print(player1 + " will go first.")
if first == int(2):
print(player2 + " will go first.")
code (image)
Any help is appreciated
Your problem is with first = print(random.randint(1,2)). print doesn't return anything. This should be
first = random.randint(1,2).
Also, int(1) is not needed, as 1 is already an integer. So first == 1 will work.
from random import randint
current_player = randint(1, 2)
print("player{} will go first.".format(current_player))
I would do like this
first = random.randint(1,2)
print(str(first)) #if you want to print the number generated.
if first == 1:
print("player1 will go first.")
elif first == 2:
print("player2 will go first.")

Comparing exact values in two arrays

So this is a bit confusing. I am currently making a Top-Trumps game. Right now I have two arrays, a player deck and a computer deck. The way it works is that it creates an array from a text file of dog names, then assigns 4 values to it (Exercise, Intelligence, Friendliness and Drool). This all works. Then it splits up the deck and gives half to each array (player and computer). The user gets the first pick and I have managed to get it to allow the user to pick a category. What I don't know how to do is compare exact values in the two arrays. The arrays are listed as follows (example):
[['Fern-the-Fox-Terrier'], 'Exercise: ', 3, 'Intelligence: ', 67, 'Friendliness: ', 10, 'Drool: ', 4]
Here is the code if you need it: (I'm not sure how to attach a text file)
import random
import shutil
import os #here I have imported all necessary functions for the following code to work
import array
import time
allowedresponses = ["Exercise","Intelligence","Friendliness","Drool"] #this allows me to make sure both the user and the computer select only the values available
cardcount = 0
usercards = 0 #the following variables are used for later
computercards = 0
x = 1
y = 0
play = input("Welcome to Celebrity Dogs Top Trumps! Press S to start, or Q to quit: ")
play = play.upper()
while x==1:
if play == "S" or play == "s":
print("Great! Lets play!")
x+=1 #here the user is given the option to play the game or quit. Pressing Q will immediatley end the the program, whilst pressing S will start it.
elif play == "Q" or play == "q": #x = 1 variable is used to end the while loop, permitted the user enters an appropriate answer
print("OK, bye")
quit
x+=1
else:
print("That's not a valid answer. Please try again")
play = input("Welcome to Celebrity Dogs Top Trumps! Press S to start, or Q to quit: ")
cardcount = int(input("How many cards in this game? Please pick an even number between 4 and 30: ")) #the following section of code asks the to select the number of cards they want played
while x==2:
if cardcount < 4:
print("Thats too small! Please try again!") #the programs tells the user to select again if they have picked a number smaller than 4
cardcount = int(input("How many cards in this game? Please pick an even number between 4 and 30: "))
elif cardcount > 30:
print("Thats too big! Please try again!") #the programs tells the user to select again if they have picked a number larger than 30
cardcount = int(input("How many cards in this game? Please pick an even number between 4 and 30: "))
if cardcount % 2 != 0:
print("Thats an odd number! Please try again!")#the programs tells the user to select again if they have picked a number that can't be divided by 2 with no remainders, essentially forcing only even numbers
cardcount = int(input("How many cards in this game? Please pick an even number between 4 and 30: "))
else:
print("Perfect! Onwards!")
x+=1 #once again I have used the x variable to allow the user to continue if they have selected a number that fits the requirements
time.sleep(1)
print("----------------------------------------------------------------------")
print("Rules: 1) For exercise, intelligence and friendliness, the highest value wins. For drool, lowest wins")
print(" 2) If there is a draw, the player that picked the value wins and gets the cards")
shutil.copyfile('dogs.txt','celebdogs.txt') #this creates a copy of the dogs text file. It is mainly for if I ever need to edit a file with the dogs in,, the origin file is never changed.
topdogs = [] #here I have created an array for the dogs
inp = open('celebdogs.txt','r') #I have used python's text file edits to import everything in the newly made celebdogs text file into an array, in order to import it later
for line in inp.readlines():
topdogs.append([])
for i in line.split():
topdogs[-1].append(i)
inp.close()
deck = [] #here I have created an array for the deck of cards that will be used in the game
print("----------------------------------------------------------------------")
for index in range(0,cardcount): #this part of the code tells the program to repeat the following until the number of cards selected by the user is in the deck
deck.insert([index][0], [(random.choice(topdogs))])#h
deck[index].append("Exercise: ")
deck[index].append(random.randint(0,5))
deck[index].append("Intelligence: ")
deck[index].append(random.randint(0,100))
deck[index].append("Friendliness: ")
deck[index].append(random.randint(0,10))
deck[index].append("Drool: ")
deck[index].append(random.randint(0,10))
time.sleep(1)
playerDeck=[]
computerDeck=[]
while len(deck)>0:
playerDeck.append(deck.pop(0))
computerDeck.append(deck.pop(0))
time.sleep(1)
print("This is your deck: ")
print(playerDeck)
playerTurn = True
print("----------------------------------------------------------------------")
time.sleep(1)
print("This is your first card: ")
print(playerDeck[0])
if playerTurn == True:
answer = input("Please select an attack (Exercise, Intelligence, Friendliness and Drool): ")
while allowedresponses.count(answer) == 0:
answer = input("That isn't a valid choice, please try again: ")
else:
answer = random.choice(allowedresponses)
print("Computer chooses", answer)
print("Computer Card: ")
print(computerDeck[0])
if playerDeck == cardcount:
print("You win!!!!")
if computerDeck == cardcount:
print("Computer wins!!!!")
os.remove('celebdogs.txt')
Just in case I haven't explained this well, I need help knowing how to compare precise values in two arrays, so if I want to compare the values of Exercise in both decks for the single cards. Both arrays have the exact same format (name, exercise, value, intelligence, value, friendliness, value, drool, value) so I need to be able to compare specific values.
Thanks!
Try use python's zip function:
computerDeck = [1, 2, 3]
playerDeck = [1, 3, 3]
for computer_card, player_card in zip(computerDeck, playerDeck):
if computer_card == player_card:
print('valid')
else:
print('invalid')

Trying to add my first score counter (Python) (Beginner)

This is my first post here. I'm a total beginner in coding and I've created a little game to get some sort of practice. I'm having trouble adding a score counter to it. I've seen some similar posts but I didn't manage to figure it out.
Also can you guys/girls give me some tips on my code, any feedback is welcome (tell me what I can improve etc.)
Here is the code:
import random
import time
def game():
user_wins = 0
user_loses = 0
while True:
try:
number = int(input('Choose a number between 1 and 10: '))
if 0 <= number <= 10:
print('Rolling the dices {} time(s)!'.format(number))
break
else:
print("That's not quite what we were looking for.")
continue
except ValueError:
print("That's not quite what we were looking for.")
user_number = random.randint(1, 50)
computer_number = random.randint(1, 50)
time.sleep(1)
print("You've rolled {}".format(user_number))
time.sleep(1)
print('Bob rolled {}'.format(computer_number))
if computer_number > user_number:
time.sleep(0.5)
print('Bob Won')
user_loses += 1
elif computer_number < user_number:
time.sleep(0.5)
print("You've Won!")
user_wins += 1
elif computer_number == user_number:
time.sleep(0.5)
print('Seems like we have a little situation')
print("\nWins: {} \nLosses: {}".format(user_wins, user_loses))
time.sleep(0.5)
play_again = input(str("Would you like to play again (y/n)? "))
if play_again == 'y':
print("Ready?\n")
game()
else:
print("\nThank you for playing.")
game()
I want to add something like Your score: 1-0 or something similar. I've made some progress on that but when looping the values reset..
Welcome to programming! So I'm going to tell you how to implement it, so you can do it yourself as well :D. So here is what we will do:
We will have a variable outside the scope(click here) of the while loop to keep track of the score, say score = 0.
And each time someone succeeds, gets the right answer, we will increase that, by saying, score = score + 1. But that takes too much time to type that right D: So python has a shortcut! You say score += 1 somewhere in your code where you want to increase the score (in the while True loop, in this case). And then we will later print out the score (or anything) by referencing it:
print( "Your final score was %s" % str(score) ) - I know, what is that stupid str() for!? It is because our score is an integer. Since we can add and do operations on it(yeah I know soo cool).
Aaaand thats it :). If you need any further help, don't hesitate to ask it. Good luck :D.
Move this line before the while loop starts.
number = int(input('Choose a number between 1 and 10: '))
Also, it prompts to input between 1-10 but the if statement allows 0-10.
To add a counter start by assigning an initial to score to both players to 0.
user_number_score = 0
inside the If statements that determine who won the round for example if the user won add...
user_number_score = user_number_score + 1
I've found a way to do it. I had to start over, re-done the code from scratch and it's better looking too. Thank you all for the feedback.
Added it as image.

"Horse" Math game

For my computer science class final, we have been instructed to make our own game in Python.
Requirements:
1. Needs to use both a “while loop” and a “for x in y loop.”
2. Needs to use list to either keep track of information or score
3. Needs to use a function for gameplay, tracking score, both.
4. Display some art either at the beginning, after, or in between turns.
5. Can be multi player or single player.
6. Must carry a complexity commensurate with a final project.
Anyways, I decided to make a game similar to horse in basketball. The object of the game is to find the answer of the math problem before time runs out. If you don't, you get a letter in horse. Once you get all the letters of horse, your game is over.
Here is what I have so far:
import random
import time
from timeit import default_timer
print("welcome to Jared's Math Horse game!")
time.sleep(1)
print("You will have to do some basic geometry and algebra problem,and some brain teasers...")
time.sleep(1)
print("For each you get wrong, you get a letter, and it will spell 'HORSE'. Once you get all letters, you lose. ROUND TO THE NEAREST INTEGER!!!!!!!!")
time.sleep(1)
###BEgin actual stuff
how_long = int(input("How many times(problems) do you want to play? (above or equal 5)"))
score = 0
##Problems
problems = ["A cylinder has a radius of 5. It's height is 6. What is the volume?471","A boy buys two shirts. One costs $15 and he pays $27 for both shirts. How much was the 2nd shirt?12","dat boi costs $12 after a 15% discount. What was the original price?14.12","A square pyramid with a height 12 and a side length 5. What is the volume?20","What is the square root of 36?", "What is the roman numeral for 500? QUICK USE GOOGLE!!!D","On a scale of 100-100 how cool is jared?100" ]
#######End of variables
####Func time
def horse(score,problem,speed):
b = input("You have {} seconds. Press enter to begin. Round answers to nearest integer.".format(speed))
begin = default_timer()
howfast = default_timer() - begin
print(random.problem[0,7])
##Check answer
answer = input("What is your answer?:")
## Give score
##loops
for x in how_long:
while True:
if score !=5:
a = random.randint(0,7)
problem = problems[a]
##Speed
speed = int(input("How fast do you want to play?? 1=slow 2=medium 3=FAST"))
if speed == (1):
speed = random.randint(30,60)
if speed == 2:
speed = random.randint(20,40)
if speed == 3:
print("spicy!")
speed = random.randint(10,30)
score = horse(score,problem,speed)
if score == 0:
print("You have a perfect score. Good work.")
if score == 1:
print("You have an H")
if score == 2:
print("You have Ho")
if score == 3:
print("You have Hor")
if score == 4:
print("You have Hors")
if score == 5:
print("You have Horse. Game over, loser.")
break
horse()
So. I'm not sure how to make it if you type in the correct answer, you won't get a letter, and move on. I tried used a 'if and' statement and that is it. BTW, the answers to the problems are at the end. Help is VERY appreciated. Sorry if I didn't explain this well, I am a noob at this. Haha
That data structure is a disaster. You would be better off doing something like this. Keep a dict of problem : correctAnswer then get a random key, ask for some user input and time it. You still need to implement the horse logic though.
score = 0
maxTime = 3 #how many milliseconds a user has to answer the question to get it right
problems = {
"A cylinder has a radius of 5. It's height is 6. What is the volume?" : "471",
"A boy buys two shirts. One costs $15 and he pays $27 for both shirts. How much was the 2nd shirt?" : "12",
"dat boi costs $12 after a 15% discount. What was the original price?" : "14.12",
"A square pyramid with a height 12 and a side length 5. What is the volume?" : "20",
"What is the square root of 36?" : "6",
"What is the roman numeral for 500? QUICK USE GOOGLE!!!" : "D",
"On a scale of 100-100 how cool is jared?" : "100"
}
for i in range(how_long):
startTime = time.time()
thisProblem = random.choice(list(problems.keys()))
answer = input(thisProblem + ": ")
endTime = time.time()
totalTime = round(endTime - startTime, 2)
correctAnswer = problems[thisProblem]
if answer == correctAnswer and totalTime < maxTime:
print("Correct!, you took", totalTime, "ms to answer")
score += 1
elif answer != correctAnswer:
print("Incorrect!, the correct answer was", correctAnswer)
elif totalTime > maxTime:
print("Correct, but you took", totalTime, "ms to answer but are only allowed", maxTime, "ms")

Creating a multiplayer blackjack game

I'm very new to python and have been trying to make a multiplayer blackjack game on python for a while now. I've been running into lots and lots of problems and was wondering if you guys could help me with them.
import random
def total(hand):
aces = hand.count(11)
t = sum(hand)
if t > 21 and aces > 0:
while aces > 0 and t > 21:
t -= 10
aces -= 1
return t
Cards = ["2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "10C", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "10S", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "10D", "AH", "JH", "QH", "KH", "AC", "JC", "QC", "KC", "AS", "JS", "QS", "KS", "AD", "JD", "QD", "KD"]
Cards[35] = 11
Cards[36] = 10
Cards[37] = 10
Cards[38] = 10
Cards[39] = 11
Cards[40] = 10
Cards[41] = 10
Cards[42] = 10
Cards[43] = 11
Cards[44] = 10
Cards[45] = 10
Cards[46] = 10
Cards[47] = 11
Cards[48] = 10
Cards[49] = 10
Cards[50] = 10
Players = raw_input("How many players are there?")
for i in range Players:
Player i = []
Player i.append(choice(Cards))
Player i.append(choice(Cards))
tp = total(player)
print "Player" + i + "Cards: " + Player i + "," + "total: " + tp
hitorstand = raw_input("hit (h) or stand (s)?")
if hitorstand == "h":
Player i.append(choice(cards))
print ("hit (h) or stand (s)?")
elif hitorstand == "s":
break
else print "Please enter h or s"
dealer = []
While True:
dealer.append(choice(cards))
dealer.append(choice(cards))
td = total(dealer)
while td > 17:
dealer.append(choice(cards))
else:
break
if td < tp < 21:
"Player i wins"
else print "dealer wins"
This is what I have so far. I understand there are lots of gibberish and code that won't work. I was wondering if you guys can let me know what is wrong with the code and maybe suggest some options on how to fix it.
My main concerns right now:
I am making a "multiplayer" blackjack game.
I have no idea how I'm supposed to make a loop for a multiplayer blackjack game.
In my code, I asked how many people are playing. How do I make a loop for the game without knowing
what the number will be?
Also, how do I create a function to find out the winner without knowing how many players are playing?
After I type in
Players = raw_input("How many players are there?")
for i in range Players:
The Players in the for loop gives me a syntax error. What is wrong?
As an update, I've thought about what you said about making a list
and I still do not really understand how I should go about
making a code to find out the winner.
for example
even if I make a list, if i do not know how many players are actually playing, I wouldn't be able to compare the elements in the list. If I knew how many people were playing,
playerlist = [1,2,3]
I can say
if playerlist[0] > playerlist[1], playerlist[2] and playerlist[0] < 21:
then print "player 1 wins!"
But since I won't know how many people are playing until the user actually types in the input, I am lost as to how I am supposed to write the code for the winner.
I do not know if there is a way of saying "if this is bigger than the rest". I only know how to say "if this is bigger than that".
Is there a way of saying "if this is bigger than the rest" in python?
If not, can you give me some suggestions to making the code to find out the winner?
You're on the right track with your "Players" variable. If you store an int representing the number of players there, then any time you want to do something that should require knowing the number of players, just use the Players variable instead. For instance, you can write a for loop that iterates that number of times (like you've already almost got). In order to iterate over the players, you'll need to place them in some sort of data structure (probably a list).
Once you know the number of players, you can set up the list like this:
playerList = []
for i in range(Players):
playerList[i] = [whateverDataYouWantToStoreAboutEachPlayer]
After that, you can access each player in a for loop by referring to playerList[i]. That way, you can do things for each player without knowing the number of players ahead of time.
When you use raw_input, the input is stored as a string. To use it as an int (which is the way you want to use it), you need to convert it first. You can do this with
Players = int(Players)
although it would be safer to first make sure that the number the user entered is actually a number, as in
while not Players.isdigit():
Players = raw_input("Please enter an integer: ")
Players = int(Players)
Also, as minitech said (and as shown above), you need to iterate over range(Players), rather than just Players, as that will create a list of numbers from 0 to Players-1, and you can only iterate over data that is in some sort of a sequence format.
EDIT (to answer follow-up question): You can find the largest value in the list by iterating over the whole thing and keeping track of the largest value you see:
highestIndex = 0
for i in range(Players):
if PlayerList[i] > playerList[highestIndex]:
highestIndex = i
At the end, highestIndex will hold the index in the list of the player with the highest score.
Python also has a built-in function, max(), which will give you the maximum value in a list. It won't give you the location of that value, though, so it would be more cumbersome to use in this case.

Categories