Project4 BlackJack

embedded/2024/10/22 14:00:06/

Overview

这是一个简单的Python实现的21点(Blackjack)游戏。以下是代码的主要部分和功能解释:

1. `main()` 函数:主要的游戏逻辑在这里。它包括处理玩家的赌注、发牌、处理玩家和庄家的动作、判断输赢等。

2. `getBet()` 函数:提示玩家下注金额,并验证输入的赌注是否合法。

3. `getDeck()` 函数:生成一副完整的扑克牌(52张)并洗牌。

4. `displayHands()` 函数:显示玩家和庄家的牌面。如果 `showDealerHand` 参数为 `False`,则隐藏庄家的第一张牌。

5. `getHandValue()` 函数:计算一手牌的总点数。将A的值视为1或11,其他牌的值为其点数值,J、Q、K视为10。

6. `displayCards()` 函数:用文本形式打印出玩家和庄家的牌面。

7. `getMove()` 函数:获取玩家的行动选择,可以选择继续要牌(Hit)、停止要牌(Stand)、双倍下注(Double down)。

8. `if __name__ == '__main__':` 部分:如果直接运行代码文件,则执行 `main()` 函数。

这个游戏允许玩家与庄家进行21点游戏,并实现了赌注、牌面显示、动作选择、赢家判定等基本功能。

 

1.The Program in Action:

python">(ll_env) maxwellpan@192 4BlackJack % python3 blackjack.py
Blackjack, by Maxwell PanRules:Try to get as close to 21 without going over.Kings,Queens, and Jacks are worth 10 points.Aces are worth 1 or 11 points.Cards 2 through 10 are worth their face value.(H)it to take another card.(S)tand to stop taking cards.On your first play, you can (D)ouble down to increase your bet but must hit exactly one more time before standing, In case of a tie, the bet is returned to the player.The dealer stops hitting at 17.
Money: 5000
How much do you bet? (1-5000, or QUIT)
> 400
Bet: 400DEALER: ???____   ____
|## | |J   |
|###| | ♦ |
|_##| |__J |PLAYER: 20____   ____
|K   ||Q   |
| ♥ || ♠ |
|__K ||__Q |(H)it, (S)tand, (D)ouble down> h
You drew a 8 of ♠.DEALER: ???____   ____
|## | |J   |
|###| | ♦ |
|_##| |__J |PLAYER: 28____   ____   ____
|K   ||Q   ||8   |
| ♥ || ♠ || ♠ |
|__K ||__Q ||__8 |DEALER: 21____   ____
|A   ||J   |
| ♣ || ♦ |
|__A ||__J |PLAYER: 28____   ____   ____
|K   ||Q   ||8   |
| ♥ || ♠ || ♠ |
|__K ||__Q ||__8 |You lost!
Press Enter to continue...Money: 4600
How much do you bet? (1-4600, or QUIT)
> quit
Thanks for playing!
(ll_env) maxwellpan@192 4BlackJack %

2. How It Works

python">"""Blackjack, by Maxwell Pan 
The classic card game also known as 21.(This version doesn't have splitting or insurance.)
More info at https://en.wikipedia.org/wiki/Blackjack
View this code at https://nostarch.com/big-book-small-python-projects
Tags: large, game, card game"""import random, sys# Set up the constants:
HEARTS = chr(9829) 
DIAMONDS = chr(9830)
SPADES = chr(9824)
CLUBS = chr(9827)# (A list of chr codes is at https://inventwithpython.com/charactermap)
BACKSIDE = 'backside'def main():print('''Blackjack, by Maxwell PanRules:Try to get as close to 21 without going over.Kings,Queens, and Jacks are worth 10 points.Aces are worth 1 or 11 points.Cards 2 through 10 are worth their face value.(H)it to take another card.(S)tand to stop taking cards.On your first play, you can (D)ouble down to increase your bet but must hit exactly one more time before standing, In case of a tie, the bet is returned to the player.The dealer stops hitting at 17.''')money = 5000while True: # Main game loop.# Check if the player has run out of money.if money < 0:print("You're broke!")print("Good thing you weren't playing with real money.")print("Thanks for playing!")sys.exit()# Let the player enter their bet for this round:print('Money:', money)bet = getBet(money)# Give the dealer and player two cards from the deck each:deck = getDeck()dealerHand = [deck.pop(), deck.pop()]playerHand = [deck.pop(), deck.pop()]# Handle player actions:print('Bet:', bet)while True: #Keep looping until player stands or busts.displayHands(playerHand, dealerHand, False)print()# Check if the player has bust:if getHandValue(playerHand) > 21:break# Get the player's move, either H, S, or D:move = getMove(playerHand, money - bet)# Handle the player actions:if move == 'D':# Player is doubling down, they can increase their bet:additionalBet = getBet(min(bet, (money - bet)))bet += additionalBetprint('Bet increased to {}.'.format(bet))bet += additionalBetprint('Bet increased to {}.'.format(bet))print('Bet:', bet)if move in ('H','D'):# Hit/doubling down tasks another card.newCard = deck.pop()rank, suit = newCardprint('You drew a {} of {}.'.format(rank, suit))playerHand.append(newCard)if getHandValue(playerHand) > 21:# The player has busted:continueif move in ('S', 'D'):# Stand/doubling down stops the player's turn.break# Handle the dealer's actions:if getHandValue(playerHand) <= 21:while getHandValue(dealerHand) < 17:# The dealer hits:print('Dealer hits...')dealerHand.append(deck.pop())displayHands(playerHand, dealerHand, False)if getHandValue(dealerHand) > 21:break # The dealer has busted.input('Press Enter to continue...')print('\n\n')# Show the final hands:displayHands(playerHand, dealerHand, True)playerValue = getHandValue(playerHand)dealerValue = getHandValue(dealerHand)# Handle whether the player won, lost, or tied:if dealerValue > 21:print('Dealer busts! You win ${}!'.format(bet))money += betelif (playerValue > 21) or (playerValue < dealerValue):print('You lost!')money -= betelif playerValue > dealerValue:print('You won ${}!'.format(bet))money += betelif playerValue == dealerValue:print('It\'s a tie, the best is returned to you.')input('Press Enter to continue...')print('\n\n')def getBet(maxBet):"""Ask the player how much they want to bet for this round."""while True: #Keep asking until they enter a valid amount.print('How much do you bet? (1-{}, or QUIT)'.format(maxBet))bet = input('> ').upper().strip()if bet == 'QUIT':print('Thanks for playing!')sys.exit()if not bet.isdecimal():continue   # If the player didn't enter a number , ask again.bet = int(bet)if 1 <= bet <= maxBet:return bet # Player entered a valid bet.def getDeck():"""Return a list of (rank, suit) tuples for all 52 cards."""deck = []for suit in (HEARTS, DIAMONDS, SPADES, CLUBS):for rank in range(2, 11):deck.append((str(rank), suit)) # Add the numbered cards.for rank in ('J','Q','K','A'):deck.append((rank, suit))   # Add the face and race cardsrandom.shuffle(deck)return deckdef displayHands(playerHand, dealerHand, showDealerHand):"""Show the player's and dealer's card. Hide the dealer's first card if showDealerHand is False."""print()if showDealerHand:print('DEALER:', getHandValue(dealerHand))displayCards(dealerHand)else:print('DEALER: ???')# Hide the dealer's first card:displayCards([BACKSIDE] + dealerHand[1:])# Show the player's cards:print('PLAYER:', getHandValue(playerHand))displayCards(playerHand)def getHandValue(cards):"""Returns the value of the cards. Face cards are worth 10, aces are worth 11 or 1 (this function picks the most suitable ace value)."""value = 0numberOfAces = 0# Add the value for the non-ace cardsfor card in cards:rank = card[0] # card is a tuple like(rank, suit)if rank == 'A':numberOfAces += 1elif rank in ('K','Q','J'): # Face cards are worth 10 pointsvalue += 10else:value += int(rank) # Numbered cards are worth their number.# Add the value for the aces:value += numberOfAces   # Add 1 per ace.for i in range(numberOfAces):# If another 10 can be added with busting, do so:if value + 10 <= 21:value += 10return valuedef displayCards(cards):"""Display all the cards in the cards list."""rows = ['', '', '', '', ''] # The text to display on each row.for i, card in enumerate(cards):rows[0] += ' ____  ' # Print the top line of the card.if card == BACKSIDE:# Print a card's back:rows[1] += '|## | 'rows[2] += '|###| 'rows[3] += '|_##| 'else:# Print the card's front:rank, suit = card    #The card is a tuple data structure.rows[1] += '|{}  |'.format(rank.ljust(2))rows[2] += '| {} |'.format(suit)rows[3] += '|_{} |'.format(rank.rjust(2, '_'))# Print each row on the screen:for row in rows:print(row)def getMove(playerHand, money):"""Asks the player for their move, and returns 'H' for hit, 'S' for stand , 'D' for double down."""while True:# Determine what moves the player can make:moves = ['(H)it', '(S)tand']# The player can double down on their first move, which we can # tell because they'll have exactly two cards:if len(playerHand) == 2 and money > 0:moves.append('(D)ouble down')# Get the player's move:movePrompt = ', '.join(moves) + '> 'move = input(movePrompt).upper()if move in ('H', 'S'):return move # Player has entered a valid move.if move == 'D' and '(D)ouble down' in moves:return move # Player has entered a valid move.# If the program is run (instead of imported), run the game:
if __name__ == '__main__':main()

 


http://www.ppmy.cn/embedded/10672.html

相关文章

OpenHarmony网络协议通信c-ares [交叉编译]异步解析器库

简介 c-ares是异步解析器库&#xff0c;适用于需要无阻塞地执行 DNS 查询或需要并行执行多个 DNS 查询的应用程序。 下载安装 直接在OpenHarmony-SIG仓中搜索c-ares并下载。 使用说明 以OpenHarmony 3.1 Beta的rk3568版本为例 将下载的c-ares库代码存在以下路径&#xff1a;…

Java、Spring、Dubbo三者SPI机制原理与区别

Java、Spring、Dubbo三者SPI机制原理与区别 什么是SPI SPI全称为Service Provider Interface&#xff0c;是一种动态替换发现的机制&#xff0c;一种解耦非常优秀的思想&#xff0c;SPI可以很灵活的让接口和实现分离&#xff0c;让api提供者只提供接口&#xff0c;第三方来实…

LED灯降压恒流驱动芯片5~60v输出1.5A大电流AP51656

产品描述 AP51656是一款连续电感电流导通模式的降压恒流源&#xff0c;用于驱动一颗或多颗串联LED输入电压范围从 5 V 到 60V&#xff0c;输出电流 最大可达 1.5A 。根据不同的输入电压和外部器件&#xff0c; 可以驱动高达数十瓦的 LED。 内置功率开关&#xff0c;采用高端电…

《史铁生》-随记

史铁生的文案进一段总是刷到&#xff0c;文字在某些时候真的是一种无形的动力。小时候学过的书&#xff0c;长大了才会更加理解其中的蕴意。如看到的文字所说&#xff0c;教育具有长期性和滞后性&#xff0c;就像一个闭环&#xff0c;多年后你有一个瞬间突然意识到什么&#xf…

logback添加日志行号

logback打印行号 全量配置如下 在包名后面添加\(%F:%L\\)这样打印的日志是带类名加行号&#xff0c;支持 ide 点击跳转(xxx.main.java:18)精简配置如下 打印全量类占用显示位置去掉主类名直接打印行号%clr(%4.4L{4})这样打印的日志只是加行号解释&#xff1a;%4&#xff1a;这…

力扣经典150题第三十六题:旋转图像

目录 力扣经典150题第三十六题&#xff1a;旋转图像引言题目详解解题思路代码实现示例演示复杂度分析总结扩展阅读 力扣经典150题第三十六题&#xff1a;旋转图像 引言 本篇博客介绍了力扣经典150题中的第三十六题&#xff1a;旋转图像。题目要求将给定的 n n 二维矩阵顺时针…

新的全息技术突破计算障碍

一种突破性的方法利用基于Lohmann透镜的衍射模型实时创建计算机生成全息图&#xff08;CGH&#xff09;&#xff0c;在保持3D可视化质量的同时&#xff0c;大大降低了计算负荷要求。 全息显示为制作逼真的三维图像提供了一条令人兴奋的途径&#xff0c;这种图像给人以连续深度…

4.0-Python列表(list)、元组(tuple)、字典(dict)和集合(set)详解

Python 序列&#xff08;Sequence&#xff09;是指按特定顺序依次排列的一组数据&#xff0c;它们可以占用一块连续的内存&#xff0c;也可以分散到多块内存中。Python 中的序列类型包括列表&#xff08;list&#xff09;、元组&#xff08;tuple&#xff09;、字典&#xff08…