Blackjack game not updating hands each time everyone draws - python

I'm trying to make a simple text-based Python game around blackjack. The game knows the variable 'hand' and 'd_hand' which are your hand and the dealer's hand, but won't update it after each new card is drawn. hand and d_hand are assigned to a random integer between 1 and 11 plus your current hand before it added the random number, which in theory should mean that your hand updates itself every time a new card is drawn.
Here's the code:
def draw(hand, d_hand):
x = randint(1, 11)
card = x
hand = x + hand
print("You drew...")
print(card)
y = randint(1, 11)
d_card = y
d_hand = y + d_hand
print("Dealer drew...")
print(d_card)
print("Your hand: ")
print(hand)
print("Dealer's hand: ")
print(d_hand)
ask()
And here's the output of everything:
(Note: I only am showing one function here, the game is obviously more than just this one function I'm showing.)
Press enter to begin:
You drew...
1
Dealer drew...
5
Your hand:
1
Dealer's hand:
5
Hit or stay? (h/s): h
You drew...
10
Dealer drew...
8
Your hand:
10
Dealer's hand:
8
Hit or stay? (h/s): '''
I'm not really sure what the issue is here...
By the way, I'm new to this site so I can't like any comments, so thank you to everyone who answered!

If hand and d_hand are lists (or mutable objets),
you may want to update the object itself by replacing hand = x + hand with hand.append(x).
Otherwise, your code will just create a new local list hand that will be lost when the function ends.

From the code you posted it looks like you aren't returning the new hands. So when the function returns the hands will revert to whatever value they were before the call. You can return tulples in python like return (hand,d_hand) and then do something like hand,d_hand = draw(hand,d_hand)

Related

Creating Memory game (flipping tiles game)

I am having trouble with coordinates and flipping the cards separately. This is my first time handling with coordinates in python.
When trying to flip the cards separately, the code registers the rows of cards as lists. I did use a list of lists to display the cards.
The code is shown below.
import random
wrong = 0
used = []
cards = deck()
def mmain():
random.shuffle(cards)
selected_cards = cards[:int(result / 2)]
selected_cards = selected_cards * 2
random.shuffle(selected_cards)
i = 0
while i < len(selected_cards):
row = selected_cards[i: i + columns]
i = i + columns
grid1.append(row1)
squares = ["🎴"]
grid = []
row = []
for i in range(rows):
row.append(squares)
for e in range(columns):
grid.append(row)
while True:
for i in range(len(grid)):
print(*grid[i])
squares = str(squares)
coordinate1 = int(input("Enter the first coordinate: "))
coordinate2 = int(input("Enter the second coordinate: "))
used.append(coordinate1)
used.append(coordinate2)
if coordinate1 in range(len(grid[i])):
for k in grid[i]:
k[coordinate1] = str(selected_cards[coordinate1])
elif coordinate2 in range(len(grid[i])):
for k in grid[i]:
k[coordinate2] = str(selected_cards[coordinate2])
elif selected_cards[coordinate1] == selected_cards[coordinate1]:
grid9 = "⬛"
grid10 = "⬛"
else:
wrong = wrong + 1
if grid[i] == "⬛":
print("You win! 🥳🥳🥳🎉🎉🎉")
print("Your score is: ")
break
mmain()
I would like help on this since I am struggling with it for weeks. I appreciate the answers to solve the problem. Thank you.
Note: I already have a program that helps displays the cards.
Edit: I am sure if someone helps me with this, the question I asked could help others.
Edit2: I use Google Colab for coding in python.
Your code needs to be rewritten for clarity
Here's a template you can use, then you just need to implement each function
Test each function with test cases to ensure it works properly, then move to the next one
def main():
# create your deck
cards = initialize_cards()
# iterates until the winning condition is satisfied.
# could be a simple check that the deck is empty.
while not check_winning_condition(cards):
# ask the user for coordinates, do all the checks to ensure they are valid coordinates.
coord1, coord2 = ask_user_coordinates()
# reveals the cards to the user. Either a simple console o a sophisticated GUI
card1, card2 = reveal_cards(cards, coord1, coord2)
# checks if the cards match and removes them from the deck if needed
cards = check_cards(cards, card1, card2)
Ideally you should use classes, but for now try organizing like this.
You might need additional parameters, feel free to add the ones you need and avoid global variables.
Each function does one thing, if it does two things make two functions.
You see how simple the main function is?
Just make now each function do what is designed to do and test test test.

How to alternate between players?

I have to make a card game in which the starting player changes after each round or mini round (up to me to decide) but I have no clue how to alternate between the 2 players. After reading online, I tried using the cycle function from itertools but that creates further problems...
The problem is that I do not know how to alternate between the 2 players without messing up the rest of the program (displaying the player's hand and the scoring system)
To clarify in advance, the code snippets I am about to provide work perfectly as long as I do not alternate between the starting players.
Code:
print("Player 1, your cards are: ", hands[0])
print("Player 2, your cards are: ", hands[1])
In this case I want the hands index to change accordingly to the Player if i use the cycle function.
if cards.bigger_card(hands[0][play_1 - 1], hands[1][play_2 - 1], trump[0][1]) == 0:
print("Congrats Player 2! You won this mini round.")
score["score_2"] += 1
else:
print("Congrats Player 1! You won this mini round.")
score["score_1"] += 1
Here the score should update according to the Player that won the round.
I'm not sure if I've understood your question well enough. But I'll try.
To simply alternate between two index i.e. 0, 1, you can add a variable to store current turn and alternating it like this:
currentTurn = 0
def switchTurn():
return (currentTurn + 1) % 2
Usage:
print(currentTurn)
# output: 0
switchTurn()
print(currentTurn)
# output: 1
print(hands[currentTurn])
# output player 2nd's hands (or cards)

Python Black Jack game variant

My Black Jack code is very basic but is running quite smoothly, however I have run into a speed bump. Thus im here. When I call "Hit" to send me another card in my While loop, for every loop the DECK instantiates the same card. The first 2 drawn and the Hit card are always different but within the While loop (which is set to end when the player says "stay" and doesnt want another card.) the Hit cards remain the same.
import random
import itertools
SUITS = 'cdhs'
RANKS = '23456789TJQKA'
DECK = tuple(''.join(card) for card in itertools.product(RANKS, SUITS))
hand = random.sample(DECK, 2)
hit = random.sample(DECK, 1)
print("Welcome to Jackpot Guesser! ")
c = input("Would you like to play Black Jack or play Slots? ")
if c == 'Black Jack':
print()
print("Welcome to Black Jack! Here are the rules: ")
print("Black Jack is a game of whit, skill with a bit of Luck. You will start with 2 card and try to achieve a total of 21 points. \n Each cards worth is equal to its number, face cards are worth 10 and the Ace can be 1 or 11 points. You decide. \n You can decide to -Stay- and take the points you have or -Hit- to get another card. If you get 21 its Black Jack and you win. \n If no one gets 21, the highest points win, but if you go over 21 you -Bomb- and lose everything. \n Becarful not to Bomb and goodluck out there! Remember, you got to know when to Hit, when to Stay and when to walk away! \n")
print(hand)
print()
g = 'swag'
while g != 'Stay':
g = input(("What would you like to do, Stay or Hit: "))
if g == 'Hit':
print(hit)
elif g == 'Stay':
print("Lets see how you did!")
else:
print("test3")
elif c == 'Slots':
print("test")
else:
print("test2")
EX: Hand: Td(two diamonds), 3c(3 club)
Hit: 7s(7 spades)
hit 7s
hit 7s
hit 7s
...
stay: lets see how you did. I need the continued While loop Hits to differ, any ideas.
The problem is that you are generating the hit card only once, during the start of the program. Changing your code from
if g == 'Hit':
print(hit)
to something like
if g == 'Hit':
hit = random.sample(DECK, 1)
print(hit)
will make it outputs different cards on each hit.

Program not terminating when score limit is reached?

I'm working on a simple text-based trivia game as my first python project, and my program won't terminate once the score limit is reached.
def game(quest_list):
points = 0
score_limit = 20
x, y = info()
time.sleep(2)
if y >= 18 and y < 100:
time.sleep(1)
while points < score_limit:
random.choice(quest_list)(points)
time.sleep(2)
print("Current score:", points, "points")
print("You beat the game!")
quit()
...
It looks like the points variable is not increased. Something like this might work in your inner loop:
while points < score_limit:
points = random.choice(quest_list)(points)
time.sleep(2)
print("Current score:", points, "points")
I'm assuming that quest_list is a list of functions, and you're passing the points value as an argument? To make this example work, you'll also want to return the points from the function returned by the quest_list that's called. A perhaps cleaner way to build this would be to return only the points generated by the quest. Then you could do something like:
quest = random.choice(quest_list)
points += quest()
Unless points is a mutable data structure, it won't change the value. You can read more about that in this StackOverflow question.

Python2.7/Confused with variables

initial_p = input("Enter the initial point")
def game():
x = 1
guess = input("Guess value")
if guess == 1:
initial_p += 2
else:
initial_p -= 2
game()
replay = raw_input("Do you want to try it again? Y/N")
if replay == 'Y':
game()
each game needs 2 points
I made it really simple just to explain this stuff easily
So to play each game, it requires you to have at least 2 points otherwise it becomes game over
if you guess right, you earn 2 points
if not, you lose 2 points.
with the outcome(points), you can either play again or quit
if you play again, you pay two points
HOWEVER, when you play for the second time or more, that line
initial_p += 2 and initial_p -= 2 still have points that you typed in the very beginning
The quick and dirty response is to change to the following.
def game(initial_p):
#Your Code
return initial_p
initial_p = game(initial_p)
Basically, you're placing the global variable as a local variable and reassigning the global.
This should also happen at the very bottom as well.
Also, you can just ask for the input inside of the function, and have a default argument of initial_p.
For example,
def game(first_time=True)
#Ask for input with if first_time:
return initial_p
And modify some global point value or something from the return.
Sorry if this is sloppy, was written on my mobile.

Categories

Resources