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')
Related
I am making a rock paper scissors game and for that I want the computer to choose a random choice excluding the player's choice so if a player chooses rock then it should choose randomly between paper and scissors. Can anyone help me out?
This is my code:
symbols = [rock,paper,scissors]
player_input = input("Please type 1 for rock, 2 for paper, and 3 for scissors. ")
player_choice = int(player_input) - 1
You could try this code. The first choice will be removed from the list of choices.
c = [1,2,3] # 3 choices
a = random.choice(c) # pick the first (e.g. by input player)
print (a)
c.remove(a) # remove it from the list of choices
b = random.choice(c) # pick the second (e.g. by computer)
print (b)
You can try something along this line (assuming I am continuing from your code above):
import random
remaining_symbol = symbols
remaining_symbol.pop(player_choice)
result = remaining_symbol[random.randint(0, len(remaining_symbol))]
print(result) #this should give you the answer
I have not tested this code but it should be along this idea.
You could do something like that:
from random import choice
symbols = ["rock","paper","scissors"]
try:
player_input = int(input("Please type 1 for rock, 2 for paper, and 3 for scissors. ")) - 1
except (ValueError, TypeError):
print("Not a valid input")
else:
symbols_two = [thing for thing in symbols if thing != symbols[player_input]]
print('random answer: {}'.format(choice(symbols_two)))
this code is not tested for errors
Hello fellow programmers! I am a beginner to python and a couple months ago, I decided to start my own little project to help my understanding of the whole development process in Python. I briefly know all the basic syntax but I was wondering how I could make something inside a function call the end of the while loop.
I am creating a simple terminal number guessing game, and it works by the player having several tries of guessing a number between 1 and 10 (I currently made it to be just 1 to test some things in the code).
If a player gets the number correct, the level should end and the player will then progress to the next level of the game. I tried to make a variable and make a true false statement but I can't manipulate variables in function inside of a while loop.
I am wondering how I can make it so that the game just ends when the player gets the correct number, I will include my code down here so you guys will have more context:
import random
import numpy
import time
def get_name(time):
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
# The Variable 'tries' is the indication of how many tries you have left
tries = 1
while tries < 6:
def try_again(get_number, random, time):
# This is to ask the player to try again
answer = (input(" Do you want to try again?"))
time.sleep(2)
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
else:
print("Thank you for playing the game, I hope you have better luck next time")
def find_rand_num(get_number, random, time):
num_list = [1,1]
number = random.choice(num_list)
# Asks the player for the number
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(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
try_again(get_number, random, time)
def get_number(random, try_again, find_rand_num, time):
# This chooses the number that the player will have to guess
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
find_rand_num(get_number, random, time)
if tries < 2:
get_name(time)
tries += 1
get_number(random, try_again, find_rand_num, time)
else:
tries += 1
get_number(random, try_again, find_rand_num, time)
if tries > 5:
break
I apologize for some of the formatting in the code, I tried my best to look as accurate as it is in my IDE. My dad would usually help me with those types of questions but it appears I know more python than my dad at this point since he works with front end web development. So, back to my original question, how do I make so that if this statement:
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
is true, the while loop ends? Also, how does my code look? I put some time into making it look neat and I am interested from an expert's point of view. I once read that in programming, less is more, so I am trying to accomplish more with less with my code.
Thank you for taking the time to read this, and I would be very grateful if some of you have any solutions to my problem. Have a great day!
There were too many bugs in your code. First of all, you never used the parameters you passed in your functions, so I don't see a reason for them to stay there. Then you need to return something out of your functions to use them for breaking conditions (for example True/False). Lastly, I guess calling functions separately is much more convenient in your case since you need to do some checking before proceeding (Not inside each other). So, this is the code I ended up with:
import random
import time
def get_name():
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
def try_again():
answer = (input("Do you want to try again? "))
time.sleep(2)
# Added return True/False to check whether user wants to play again or not
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
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 True
else:
print("Thank you for playing the game, I hope you have better luck next time")
return False
# Joined get_number and find_random_number since get_number was doing nothing than calling find_rand_num
def find_rand_num():
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
num_list = [1,1]
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(2)
print("Congratulations! You got the number correct!")
# Added return to check if correct answer is found or not
return "Found"
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
tries = 1
while tries < 6:
if tries < 2:
get_name()
res = find_rand_num()
if res == "Found":
break
checker = try_again()
if checker is False:
break
# Removed redundant if/break since while will do it itself
tries += 1
In this game I've been tasked to do, one part of it is where all players in the game start off with 0 points, and must work their way to achieve 100 points, which is earned through dice rolls. After player decides to stop rolling, each player's score is displayed. My problem is that I don't know how to individually assign each player a "Score" variable, in relation to how many players are playing initially, so for e.g.
Player 1: Rolls a 2 and a 5
Player 1 score = +25
and etc. for every other player
Essentially, I need help on how to check if for example user at the start inputs that 3 players are playing, 3 different variables will be assigned to each player that contains their scores, which will change as the game progresses.
I have no idea what the proper code should actually contain, hence why I'm looking for help
import random
playerList = []
count = 0
def rollTurn():
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
print("Your first dice rolled a: {}".format(dice1))
print("Your second dice rolled a: {}".format(dice2))
print("-------------------------MAIN MENU-------------------------")
print("1. Play a game \n2. See the Rules \n3. Exit")
print("-------------------------MAIN MENU-------------------------")
userAsk = int(input("Enter number of choice"))
if userAsk == 1:
userNun=int(input("Number of players?\n> "))
while len(playerList) != userNun:
userNames=input("Please input name of player number {}/{}\n> ".format(len(playerList)+1, userNun))
playerList.append(userNames)
random.shuffle(playerList)
print("Randomizing list..:",playerList)
print("It's your turn:" , random.choice(playerList))
rollTurn()
while count < 900000:
rollAgain=input("Would you like to roll again?")
if rollAgain == "Yes":
count = count + 1
rollTurn()
elif rollAgain == "No":
print("You decided to skip")
break
I would like that during a player's turn, after rolling their dices, the value of those two rolled dices are added to that individual's score, and from there, a scoreboard will display showcasing all the players' in the lobby current scores, and will continue on to the next player, where the same thing happens.
instead of using a list for playerList, you should use a dict:
playerList = {}
playerList['my_name'] = {
"score": 0
}
You can iterate on the keys in the dict if you need to get data. For example in Python3:
for player, obj in playerList.items():
print(player, obj['score'])
And for adding data its a similar process:
playerList['my_name']['score'] = playerList['my_name']['score'] + 10
I am starting to code a game just to practice. However, the user needs to enter an odd number to play. If they don't then I want the program to ask them for an odd number they loop and play again. I put this code in the else statement but if I enter an odd number it will not loop again.
Question 2:
how can I get the program to display Game 1, Game 2, etc as the loop runs however many times the input in 'Games' is?
Can someone help?
games = input("How many games would you like to play?")
for i in range(games):
if games % 2 == 1:
print('Game 1')
# code here
else:
input('Enter an odd number')
Try this:
games = int(input("How many games would you like to play?"))
while True:
if games % 2 == 1:
for i in range(games):
print('Game', i+1 )
break
else:
games = int(input('Enter an odd number: '))
It appears to me that you your confusion lies in a couple casting errors. Please note that input returns a type string, which you attempt to use as an integer. Try the following code instead:
games = input("How many games would you like to play? ")
numberOfGames = int(games)
for i in range(numberOfGames):
print('Processing Game ' + str(i))
testVal = input('Enter an odd number ')
if int(testVal) % 2 == 1:
print("Congratts! " + testVal + " is odd!\n\n")
else:
print("You Loose. " + testVal + " is even.\n\n")
I have updated my code with the changes made. I am still getting incorrect results...
# Import statements
import random
# Define main function that will ask for input, generate computer choice,
# determine winner and show output when finished.
def main():
# Initialize Accumulators
tie = 0
win = 0
lose = 0
score = 0
# initialize variables
user = 0
computer = 0
# Initialize loop control variable
again = 'y'
while again == 'y':
userInput()
computerInput()
if score == win:
print('You won this round, good job!')
win += 1
elif score == tie:
print('You tied this round, please try again!')
tie += 1
else:
print('You lost this round, please try again!')
lose += 1
again = input('Would you like to play another round (y/n)? ')
#determine winning average
average = (win / (win + lose + tie))
print('You won ', win, 'games against the computer!')
print('You lost ', lose, 'games against the computer.')
print('You tied with the computer for', tie)
print('Your winning average is', average)
print('Thanks for playing!!')
# get user input for calculation
def userInput():
print('Welcome to Rock, Paper, Scissor!')
print('Please make your selection and and Good Luck!')
print('1) Rock')
print('2) Paper')
print('3) Scissor')
user = int(input('Please enter your selection here: '))
print('You selected', user)
# get compter input for calculation
def computerInput():
computer = random.randint(1, 3)
print('The computer chose', computer)
def getScore():
if user == 1 and computer == 3:
score = win
return score
elif user == 2 and computer == 1:
score = win
return score
elif user == 3 and computer == 2:
score = win
return score
elif user == computer:
score = tie
return score
else:
score = lose
return score
# Call Main
main()
In Python:
>>> print("3" == 3)
False
Strings and integers are values of different data types, and will not compare equal. Try changing your input to:
userInput = int(input('Please enter your selection here: '))
This will convert the string typed by the user to a number for later comparison. (Note that I have assumed you are using Python 3.x, because input() behaves slightly differently in Python 2.x.)
Note that this will throw an error if you type anything other than a number.
Update: As pointed out by #FelipeFG in the comments below, you are also overwriting the function userInput with the value typed by the user. You'll need to change the name of one or the other, for example:
def getUserInput():
...
Also don't forget to change the place where you call the function. Do the same for computerInput (change to getComputerInput).
Later on, you can change those to actual functions that return values.
userInput() calls the function "userInput", but you discard the result. The same remark applies to computerInput().
userInput == 1 asks whether the function userInput itself is equal to 1. It isn't. The same remark applies to computerInput == 3 and the others.
In the function "userInput", userInput = ... binds the name "userInput" to the result of the expression. This makes "userInput" a local variable of the function. The function doesn't explcitly return anything, therefore it returns None.
If you're using Python 3, input returns a string, and you should convert its result to an int. If you're using Python 2, input evaluates whatever is entered, which isn't safe; you should use raw_input instead and convert its result to an int.
You need to compare against the return value of your function, not the function itself.
Also:
again = input('Would you like to play another round (y/n)? ')
This will throw an exception if you enter y or n, because there is no defined identifier of that name! What you want to use instead is raw_input()
Edit: As pointed out by Greg, this only applies to Python 2.x. You seem to be using Python3 though.