I was wondering if someone can point me in the right direction of a basic script.
This is for a game I created and wanted to create a countdown script to go along with it.
I want be able to have 4 users in which the program will first will ask for their name. After that each user will take turns entering their score starting at 100 and decreasing based on their input. Once they hit zero they win. Once the first person hits 0 the others will have a chance to as well until the end of the round. Each 4 inputs will be considered 1 round.
There will be a lot more to the game but I just need the start. I am new to Python but the easiest way for me to learn is to start off on a working script
Thanks!
Are you looking for something like this?
import cmd
number_users = 4
number_rounds = 10 # or whatever
user_names = [None]*number_users
user_scores = [None]*number_users
for i in range(number_users):
print("Enter name for user #{}: ".format(i+1))
user_names[i] = input()
user_scores[i] = 100
for round_number in range(number_rounds):
print(" --- ROUND {} ---".format(round_number+1))
for i in range(number_users):
print("{}, Enter your score: ".format(user_names[i]))
user_scores[i] = input()
print("--- Scores for Round {} ---".format(round_number+1))
for i in range(number_users):
print("{} : {}".format(user_names[i], user_scores[i]))
print("Done")
Related
I am a beginner to python and coding in general and I was wondering how I can make a print statement run before a module I imported. I am making a number guessing game and in my main file where I combine all the modules, I have a general function for running all the code together. It would be best if I show my code so you guys will have a better understanding of what I am dealing with:
import random
import lvl1
import time
level1 = lvl1.Level_1_activated()
# This is the main file combining everything together to make this game playable
introduction = """
Hello and welcome to NumGuess by Sava. Here is a little bit about the game:
The game works by having 3 levels, each where you must pick a number between a range of
1-10 (level 1), 1-20 (level 2), and 1-50 (level 3).
You are given 5 attempts in the first level, 10 in the second level, and 20 in the final one.
You can also access a hint by typing ‘hint’. You win the game by picking the right number in each level.
You lose the game when you run out of tries. You can get a free bonus with 5 extra tries if you type ‘hlp’.
"""
def start_game(time, lvl1):
print(introduction)
level1
start_game(time, lvl1)
This is just the code for the main module, I have the code for lvl1 (which is the first level of my 'game'), and I have a class which has all the functions which then take part in the while loop. I will also show that file:
import random
import time
# I will fist make variables for the time breaks. S is for short, M is for medium and L is for long
S = 0.2
M = 0.7
L = 1.1
class Level_1_activated():
def get_name(self):
# This function simply asks the name of the player
name = input("Before we start, what is your name? ")
time.sleep(S)
print("You said your name was: " + name)
def try_again(self):
# This asks the player if they want to try again, and shows the progress of the level
answer = (input("Do you want to try again? "))
time.sleep(M)
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(M)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
# Return statement for if the player wants to play again
return True
else:
print("Thank you for playing the game, I hope you have better luck next time")
# This is the return statement that stops the while loop
return False
def find_rand_num(self, random):
# This is the core of the level, where the player just chooses numbers between 1 and 10
time.sleep(S)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(L)
# The list of numbers for the level that the player is on at the moment
num_list = [1,10]
number = random.choice(num_list)
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(S)
print("Congratulations! You got the number correct!")
# Yet another return statement for the while loop
return "Found"
elif input != number:
time.sleep(M)
print("Oops, you got the number wrong")
# This variable is fairly self-explanatory; it is what controls how many itterations there are in the while loop
tries = 1
while tries < 6:
if tries < 2:
Level_1_activated().get_name()
res = Level_1_activated().find_rand_num(random)
if res == "Found":
break
checker = Level_1_activated().try_again()
if checker is False:
break
tries += 1
If you go back to this function in the main file:
def start_game(time, lvl1):
print(introduction)
level1
I intentionally put the print statement before the module to make it run first, and I have tried different approaches to this and still can't seem to get a grasp on what I'm doing wrong here. Thank you for taking the time to read the code and I would be very grateful if any of you have a possible solution to this.
there are number of thing you can do, one is encapsulate your code into functions that only run when you ask for it
lvl1
... #all the previous code
def run_game():
tries = 1
while tries < 6:
...
tries += 1
you can also make a distinction between being executed directly vs being imported, to do that is simple, you include the following check (usually at the end of the file)
if __name__ == "__main__":
#if true it mean that you're executing this module directly, otherwise it was imported
#and you include here whatever you want that happens when you execute the module directly but not when is imported, like for example running a game
run_game()
__name__ is a special variable and python will assigned the value "__main__" if executed directly, otherwise it will be the name of the file, like "lvl1" for example
And in your main you can import it and do stuff like
import lvl1
...
def start_game():
print(introduction)
lvl1.run_game()
I am creating a text based RPG where the player starts with 600 skill points to allocate between 6 skills.
So I start by assigning the value 600 to the skill_points variable.
skill_points = 600
then I assign a default value for each skills variable.
skill_1 = 0
skill_2 = 0
skill_3 = 0
Now I ask the player for input for the first skill.
skill1_input = int(input("Skill 1:"))
And I update the value of the variables.
skill_1 = skill_1 + skill1_input
skill_points = skill_points - skill1_input
Then I use a if statement to check if the number submitted is above the leftover skill points available, If not It prompts you to input the next skill.
if skill1_input > skill_points:
print("Not Valid")
else:
skill_2input = int(input("Skill 2:"))
Nested IF/ELSE statements repeat throughout all 6 skills until you allocate all your points. It is in a while loop so that if you don't use all of your skill points, it starts over at the first skill.
However, it is very finicky. At first I put 100 points into each skill and it worked fine. When I put 100 points into the first skill then 200 into the next skill, it prints not valid, even though there 500 points left and 200 is not is not more then 500.
There are multiple similar scenarios where the math should work properly yet the program still prints not valid
What is the current way to do this? Should I have not designed it using if statements?
This can be better done with a for loop instead of nested if statements, and I would use an array for the skills.
skill_points = 600
skills = []
skill_inputs = 0
for i in range(6):
skill_input = int(input("Skill %i: "%(i+1)))
if skill_inputs + skill_input > skill_points:
print("Not Valid")
break
else:
skills.append(skill_input)
skill_inputs += skill_input
I rewrote your code and its functional to what you asked, but as an advice, before writing code, make sure your program makes fully sense to what you want to build(even if you don't know the tools to build it yet. That is what makes you learn more!)
If your code repeats itself, theres probably a better way to write it. As you can see, that code basically repeats itself 6 times.
You could replace it with:
skill_points = 600
skill_base = []
skill = 0
for i in range(6):
if sum(skill_base) == skill_points:
print("Values stored successfully!")
break
if sum(skill_base) > skill_points:
print("Not valid")
break
skill = int(input(f'skill_ {str(i+1)}: '))
skill_base.append(skill)
if sum(skill_base) == skill_points:
print("Values stored successfully!")
I am doing a project in school which is asking me to make a music quiz in python that reads a file, displays the first letters of each word of the song and the artist (e.g Dave F F). In my file I have a list of 10 song names where python fetches a random line and does the displaying. It must be from a file (mine is notepad) The user must have 2 chances to guess the name of the song, and if they don't then the game ends. The problem that I have is I cannot get my code to ask another question, and store the last one asked so that it doesn't ask it again (e.g if the first question is Dave and F F, I want it to not come again). I would also appreciate it if I was shown how to get python to display a leaderboard. Could answers please be the full code with improvements as i'm not good with indents and putting code In the right place.
I have already gave the user 2 chances to get the song right, and If they dont then the program ends, but doesn't loop to the start.
import random
with open("songlist.txt", "r") as songs_file:
with open("artistlist.txt", "r") as artists_file:
songs_and_artists = [(song.rstrip('\n'), artist.rstrip('\n'))
for (song, artist) in zip(songs_file, artists_file)]
random_song, random_artist = random.choice(songs_and_artists)
songs_intials = "".join(item[0].upper() for item in random_song.split())
print("The songs' initials are", songs_intials, "and the name of the artist is", random_artist)
nb_tries_left = 3
guess = input("Guess the name of the song! ")
nb_tries_left -= 1
finished = False
while not finished:
answer_found = (guess == random_song)
if not answer_found:
guess = input("Nope! Try again! ")
nb_tries_left -= 1
elif answer_found:
print("The songs' initials are", songs_intials, "and the name of the artist is", random_artist)
finished = (answer_found or nb_tries_left <= 0)
if answer_found:
The songs' initials are LT and the name of the artist is Fredo
Guess the name of the song! Like That
The songs' initials are LT and the name of the artist is Fredo
Well done!
Python then doesn't ask another question, and I don't know If it will be that one again.
getting it wrong on purpose outputs this:
The songs' initials are CS and the name of the artist is 50 Cent
Guess the name of the song! candysong
Nope! Try again! carpetshop
Nope! Try again! coolsong
Sorry, you've had two chances. Come back soon!
>>>
First You want to get 2 unique songs. To do that you could use random.sample. For your use case, It is
indexes = random.sample(range(len(songs_and_artists)), 2) # 2 random songs (sampling without replacement)
# song 1
random_song, random_artist = songs_and_artists[indexes[0]]
# song 2
random_song, random_artist = songs_and_artists[indexes[1]]
Additionally, I recommend you to put your code to the function and use it with each selected song.
In order to ask more than one question every game you have to do something like this:
with open("songlist.txt", "r") as songs_file:
with open("artistlist.txt", "r") as artists_file:
songs_and_artists = [(song.rstrip('\n'), artist.rstrip('\n'))
for (song, artist) in zip(songs_file, artists_file)]
def getSongAndArtist():
randomIndex = random.randrange(0, len(songs_and_artists))
return songs_and_artists.pop(randomIndex)
while(len(songs_and_artists) > 0):
random_song, random_artist = getSongAndArtist()
#play game with the song
You save the list of songs in a python list and pop a random one out each round as long as you have more songs to play with.
For the leaderboard you have to ask for a user name before you start the game and save a list of usernames and their score and then pick the top ones. you should also figure out how to score the users
I've been trying to make a basic text game in Python, and I'm using dictionaries to contain the player's information. I want to make it so that when a player's health reaches 0, the code will stop running. I've had trouble making that happen. My dictionary, which is at the beginning of my code, looks like this:
playerAtt = {}
playerAtt["Weapon"] = "Baseball bat"
playerAtt["Party"] = "Empty"
playerAtt["Health"] = 15
playerAtt["Cash"] = "$100"
print(playerAtt)
if playerAtt['Health'] <= 0:
exit()
The bottom section is what I wrote to try and make the code stop running when the player's health reached zero, but it doesn't seem to work. In one path of my game, your health gets set to zero and the game is supposed to end, but the program continues to run:
townChoice = raw_input("You met a traveler in the town. 'Yo. I'm Bob. Let's be friends.' Will you invite him to your party? Y/N\n")
if townChoice == 'y' or townChoice == 'Y':
print("That kind traveler was not such a kind traveler. He stabbed you with a machete. RIP " + Name + '.')
playerAtt['Health'] == 0
When you reach this part of the game, all it does is print the message, and moves on to the next decision. In this situation, I could just manually end the program by doing exit() under the print command, but there are circumstances where the player only loses a fraction of their health, and they would eventually reach zero. Sorry if this is a stupid question, I've only been working on Python for a few days.
You have two "=" when you set the player's health to 0
I had put 2 == instead of 1 = when defining
playerAtt["Health"].
Also, I needed to make sure it was constantly checking if the player's health was zero, so I used a while loop. I used
while playerAtt["Health"] = 0:
deathmsg()
exit()
to fix it. deathMsg was a function I made to display a random death message, for more information.
I have written a small coin flipping program for Home work Python, it will choose one of two values; Heads or Tails at random and print them, the loop iterates 10 times then stops. As I understand it the only way to count the number of repetitions of some words is to place the words in an array or a split variable string and then run a pre-written cnt. Click Here to see that discussion.
I need to know how you get Python to take the random value it produced and then save it into an array according to the number of iterations of the for loop(in this case x number of iterations).
Here is the variable name and the two options:
coin = ["Heads", "Tails"]
Here is the code for the coin flipper core:
#Flipping core :)
def flipit(random, flip, time, comment, repeat):
time.sleep(1)
print("It begins...")
print("\n")
for x in range(0, 10):
print("Flip number", x + 1)
print(random.choice(comment))
time.sleep(1)
print(random.choice(coin),"\n")
time.sleep(2)
print("\n")
from collections import Counter
counting = []
cnt = Counter(counting)
cnt
print("Type startup(time) to begin flipping coins again")
If you do feel like refining the code please do if you have the time, but all I need is a method that I can put into the overall program that will make it run properly.
Please don't worry about the random comment, that was for a bit of fun.
I have pasted the whole program on PasteBin, Click Here for that.
Thank you for reading this and my gratitude to those who respond or even fix it.
Edit:
Just for reference I am a bit of a newbie to Python, I know some things but not even half of what the people who answer this will know.
Solution:
I have managed to make Python "read" the random value using a per-iteration if statement in my for loop, using if statements I have added 1 to the respective variable according to the random.choice.
Here is the flip core code:
def flipit(random, time, comment, headcount, tailcount, side):
time.sleep(1)
print("It begins...")
print("\n")
for x in range(0, 10):
print("Flip number", x + 1)
side = random.choice(coin) # get the random choice
print(random.choice(comment))
time.sleep(1)
print(side) # print it
if side == "Heads":
headcount += 1
else:
tailcount += 1
time.sleep(2)
print("\n")
print("You got", headcount, "heads and", tailcount, "tails!")
print("Type start() to begin flipping coins again")
resetheadtail()
resetheadtail() is the new function I have added to reset the variables at the end of the program running.
For the full code click Here!
Thanks all who helped, and those who persevered with my newbieness :)
#comment necessary for edit, please ignore
I think what you want to do is:
flip = random.choice(coin) # get the random choice
print(flip) # print it
counting.append(flip) # add it to the list to keep track
Note that you will need to move counting = [] to before your for loop.