Creating a multiplayer blackjack game - python

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.

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.")

How to assign a score to a player and accordingly add/remove points from their score during a player's turn

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

Creating a RPG game chest

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))

"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")

How to create a loop for multiple players turn?

Im trying to get this loop to work, but it just refuses to work. Any help would be very much appreciated.
while player1_score < 100 and player2_score < 100 and player3_score < 100 and player4_score < 100:
while player_turn != playerholder:
dice_rolling()
scoring()
score_awarding()
player_turn = player_turn + 1
if player_turn == playerholder:
player_turn == 1
What im trying to do is get the number of players present (playerholder) and then keep player turn within the bounds of it i.e repeating till someone gains a score of 100 or more.
Just ask if you need any more code :)
Thanks in advance.
EDIT: Everyone seems to be confused as to what I'm asking so I'm going to try explain it more elaborately.
So the game has from 2 to 4 players, and what they are trying to do is get a score of 100 or more. Since there are multiple players, I want to try and have a repeating structure to efficiently use the functions I have created over and over. With the current code, it will score Players like it should up until the last player, where the code stops completely and nothing is presented. What I would like to do is get the code to repeat infinitely until the required score is gained, as in it will keep cycling through the players with no errors. I have tried multiple times with different loops but I cannot get it to work. Hopefully this is a little bit clearer to everyone. Sorry about the unorganized/unclear question, relatively new to StackOverflow.
EDIT: Problem has been solved
As an aside, you should be keeping your players in some sort of list and iterating through them, allowing them each to take a turn in their iteration. Something like:
players = [player1,player2,player3,player4]
for player in players:
if player.score >= 100: win(player)
dice_rolling()
player.score += scoring()
But of course this only works if you have some sort of class Player in your code (which you should).
class Player(object):
def __init__(self,name):
self.name = name
self.score = 0
# what else does a Player do?
In fact you can probably make a Game class as well!
class Game(object):
def __init__(self,players):
self.players = players # a list of players
self.running = False
def dice_rolling(self):
diceroll = sum(random.randint(1,6) for _ in range(2))
def scoring(self):
return score # I don't know how you're doing this so...
def win(self,player):
print("{} wins!".format(player.name))
def run(self):
self.running = True
while self.running:
for player in self.players:
roll = dice_rolling()
player.score += scoring()
if player.score >= 100:
self.running = False
win(player)
Game().run()
Your code probably doesn't work as intended because instead
of assigning 1 to the player_turn you do this:
player_turn == 1
when it should be this:
player_turn = 1
You could try something using a list structure.
It would look like this if there were 4 players:
turns = [0,1,2,3,4,0,1,2,3,4]
#this would add another turn for player 0, to remove you just use del
turns.append(0)
#This would remove a winner from your turn stack while preserving the order
for i in turns:
if i ==4:
del i
#You could also use a dictionary if you don't like list indicies or numbers:
Players = {"blue":3, red":4, "green":2, "orange":1}
turn = [4,2,1,3,4,2,1,3]
#If there is also a maximum number of turns, you can have that hard coded also:
for i in range(max):
turn.append(1)
turn.append(2)
turn.append(3)
turn.append(4)
Truthfully, I don't really understand what your question but hopefully this may have answered it wholly or in part.

Categories