- 浏览: 489291 次
文章分类
最新评论
-
追求幸福:
这个问题你解决了吗?我也遇到这个问题了,可以交流一下吗
android OpenGL ES实现渲染到透明的纹理 render to transparent texture -
xyxdasnjss:
这个真心不错,支持
App应用之提交到各大市场渠道 -
zh_harry:
楼主是90后吧,下面那句就不说了,太伤自尊
程序员的出路 -
hero_shaoshuai:
你当创业是过家家么
程序员的出路 -
linlfx:
确实很扯,被励志书洗脑严重
程序员的出路
Interactive Python:Mini-project # 6 - Blackjack
An Introduction to Interactive Programming in Python
Mini-project description - Blackjack
Blackjack is a simple, popular card game that is played in many casinos. Cards in Blackjack have the following values: an ace may be valued as either 1 or 11 (player's choice), face cards (kings, queens and jacks) are valued at 10 and the value of the remaining cards corresponds to their number. During a round of Blackjack, the players plays against a dealer with the goal of building a hand (a collection of cards) whose cards have a total value that is higher than the value of the dealer's hand, but not over 21. (A round of Blackjack is also sometimes referred to as a hand.)
The game logic for oursimplifiedversion of Blackjack is as follows. The player and the dealer are each dealt two cards initially with one of the dealer's cards being dealt faced down (hisholecard). The player may then ask for the dealer to repeatedly "hit" his hand by dealing him another card. If, at any point, the value of the player's hand exceeds 21, the player is "busted" and loses immediately. At any point prior to busting, the player may "stand" and the dealer will then hit his hand until the value of his hand is 17 or more. (For the dealer, aces count as 11 unless it causes the dealer's hand to bust). If the dealer busts, the player wins. Otherwise, the player and dealer then compare the values of their hands and the hand with the higher value wins.The dealer wins ties in our version.Mini-project development process
We suggest you develop your Blackjack game in two phases. The first phase will concentrate on implementing the basic logic of Blackjack while the second phase will focus on building a more full-featured version. In phase one, you will use buttons to control the game and print the state of the game to the console using print statements. In the second phase, you will replace the print statements by drawing images and text on the canvas and add some extra game logic.In phase one, we will provide testing templates for four of the steps. The templates are designed to check whether your class implementations work correctly. You should copy your class definition into the testing template and compare the console output generated by running the template with the provided output. If the output matches, it is likely that your implementation of the class is correct.DO NOT PROCEED TO THE NEXT STEP UNTIL YOUR CODE WORKS WITH THE PROVIDED TESTING TEMPLATE.Debugging code that uses incorrectly implemented classes is extremely difficult. Avoid this problem by using our provided testing templates.
Phase one
- Download theprogram templatefor this mini-project
and review the class definition for the
Card
class. This class is already implemented so your task is to familiarize yourself with the code. Start by pasting theCard
class definition into the providedtesting templateand verifying that our implementation works as expected. - Implement the methods
__init__, __str__, add_card
for theHand
class. We suggest modeling a hand as a list of cards. For help in implementing the__str__
method for hands, refer back topractice exercise number fourfrom last week. Remember to use the string method for cards to convert each card object into a string. Once you have implemented theHand
class, test it using the providedtesting template. - Implement the methods for the
Deck
class listed in the mini-project template. We suggest modeling a deck of cards as list of cards. You can generate this list using a pair of nestedfor
loops or a list comprehension. Remember to use theCard
initializer to create your cards. Userandom.shuffle()
to shuffle this deck of cards. Once you have implemented theDeck
class, test your Deck class using the providedtesting template. - Implement the handler for a "Deal" button that shuffles the deck and deals the two cards to both the dealer and the player. The event handler
deal
for this button should shuffle the deck (stored as a global variable), create new player and dealer hands (stored as global variables), and add two cards to each hand. To transfer a card from the deck to a hand, you should use thedeal_card
method of theDeck
class and theadd_card
method ofHand
class in combination. The resulting hands should be printed to the console with an appropriate message indicating which hand is which. - Implement the
get_value
method for theHand
class. You should use the providedVALUE
dictionary to look up the value of a single card in conjunction with the logic explained in the video lecture for this project to compute the value of a hand. Once you have implemented theget_value
method, test it using the providedtesting template. Remember that the deck is randomized after shuffling, so the output of the testing template should match the output in the comments in form but not in exact value. - Implement the handler for a "Hit" button. If the value of the hand is less than or equal to 21, clicking this button adds an extra card to player's hand. If the value exceeds 21 after being hit, print "You have busted".
- Implement the handler for a "Stand" button. If the player has busted, remind the player that they have busted. Otherwise, repeatedly hit the dealer until his hand has value 17 or more (using a while loop). If the dealer busts, let the player know. Otherwise, compare the value of the player's and dealer's hands. If the value of the player's hand is less than or equal to the dealer's hand, the dealer wins. Otherwise the player has won.Remember the dealer wins ties in our version.
With this design, the player needs to explicitly press "Deal" to start a new deal. This choice will make using the canvas to build an image-based version of Blackjack easier. At this point, we would suggest testing your implementation of Blackjack extensively.
Phase twoIn the second phase of your implementation, you will add five features. For those involving drawing with global variables, remember to initialize these variables to appropriate values (like creating empty hands for the player and dealer) just before starting the frame.
- Implement your own
draw
method for theHand
class using thedraw
method of theCard
class. We suggest drawing a hand as a horizontal sequence of cards where the parameterpos
is the position of the upper left corner of the leftmost card. To simplify your code, you may assume that only the first five cards of a player's hand need to be visible on the canvas. - Replace printing in the console by drawing text messages on the canvas. We suggest adding a global
outcome
string that is drawn in the draw handler usingdraw_text
. These messages should prompt the player to take some require action and have a form similar to "Hit or stand?" and "New deal?". Also, draw the title of the game, "Blackjack", somewhere on the canvas. - Add logic using the global variable
in_play
that keeps track of whether the player's hand is still being played. If the round is still in play, you should draw an image of the back of a card (provided in the template) over the dealer's first (hole) card to hide it. Once the round is over, the dealer's hole card should be displayed. - Add a score counter that keeps track of wins and losses for your Blackjack session. In the simplest case (see our demo), the program displays wins minus losses. However, you are welcome to implement a more sophisticated betting/scoring system.
- Modify the logic for the "Deal" button to create and shuffle a new deck (or restock and shuffle an existing deck) each time the "Deal" button is clicked. This change avoids the situation where the deck becomes empty during play.
- Finally, modify the
deal
function such that, if the "Deal" button is clicked during the middle of a round, the program reports that the player lost the round and updates the score appropriately.
经验:list作为collection使用时,for-in调用元素对象的方法前无需确认不为空。函数调用时一定要加括号。
测试代码:
class t: def __init__(self): self.v=0 def d(self): pass def a(b): c=b #c[1]=0 for tmp in c: tmp.d #b=[t(),t()] b=[] a(b) print b
代码如下:
# Mini-project #6 - Blackjack import simplegui import random # load card sprite - 949x392 - source: jfitz.com CARD_SIZE = (73, 98) CARD_CENTER = (36.5, 49) card_images = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/cards.jfitz.png") CARD_BACK_SIZE = (71, 96) CARD_BACK_CENTER = (35.5, 48) card_back = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/card_back.png") # initialize some useful global variables in_play = False outcome = "Hit or stand?" score = 0 # define globals for cards SUITS = ('C', 'S', 'H', 'D') RANKS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K') VALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10} # define card class class Card: def __init__(self, suit, rank): if (suit in SUITS) and (rank in RANKS): self.suit = suit self.rank = rank else: self.suit = None self.rank = None print "Invalid card: ", suit, rank def __str__(self): return self.suit + self.rank def get_suit(self): return self.suit def get_rank(self): return self.rank def draw(self, canvas, pos): card_loc = (CARD_CENTER[0] + CARD_SIZE[0] * RANKS.index(self.rank), CARD_CENTER[1] + CARD_SIZE[1] * SUITS.index(self.suit)) canvas.draw_image(card_images, card_loc, CARD_SIZE, [pos[0] + CARD_CENTER[0], pos[1] + CARD_CENTER[1]], CARD_SIZE) # define hand class class Hand: def __init__(self): self.cards=[] # create Hand object def __str__(self): s='Hand contains: ' for tmp in self.cards: s+=str(tmp)+' ' return s # return a string representation of a hand def add_card(self, card): self.cards.append(card) # add a card object to a hand def get_value(self): # count aces as 1, if the hand has an ace, then add 10 to hand value if it doesn't bust value=0 # compute the value of the hand, see Blackjack video num_ace=0 if len(self.cards)==0: return value for index in range(0,len(self.cards)): tmp=self.cards[index].get_rank() value+=VALUES[tmp] if tmp=='A':num_ace+=1 if (num_ace>0)and(value+10<=21):value+=10 return value def draw(self, canvas, pos): tmppos=pos[:] if len(self.cards)==0: return for index in range(0,len(self.cards)): # draw a hand on the canvas, use the draw method for cards self.cards[index].draw(canvas,tmppos) tmppos[0]+=100 # define deck class class Deck: def __init__(self): self.cards=[] # create a Deck object for tmp1 in SUITS: for tmp2 in RANKS: card=Card(tmp1,tmp2) self.cards.append(card) def shuffle(self): # shuffle the deck random.shuffle(self.cards) # use random.shuffle() def deal_card(self): tmp=self.cards.pop() #print str(tmp) return tmp # deal a card object from the deck def __str__(self): s='Deck contains ' # return a string representing the deck if len(self.cards)==0: return s for tmp in self.cards: s+=tmp+' ' return s #define event handlers for buttons def deal(): global outcome, in_play,player,dealer,deck,score # your code goes here player=Hand() dealer=Hand() deck=Deck() deck.shuffle() tmp=deck.deal_card() player.add_card(tmp) tmp=deck.deal_card() dealer.add_card(tmp) if in_play: outcome='You give up ! New game start' score-=1 else: outcome='New game start' in_play = True #print 'dealer '+str(dealer)+'\nplayer '+str(player) def hit(): # replace with your code below global in_play,score,outcome if in_play: tmp=deck.deal_card() player.add_card(tmp) if player.get_value()>21: outcome = "You have busted! New deal?" in_play=False score-=1 #print 'dealer '+str(dealer)+'\nplayer '+str(player) # if the hand is in play, hit the player # if busted, assign a message to outcome, update in_play and score def stand(): global score,outcome,in_play if not in_play:return if player.get_value()>21: # replace with your code below outcome = "You have busted! New deal?" score-=1 else: while(dealer.get_value()<17): tmp=deck.deal_card() dealer.add_card(tmp) if dealer.get_value()>21: outcome = "dealer have busted! New deal?" score+=1 else: if player.get_value()>dealer.get_value(): outcome = 'You win! New deal?' score+=1 else: score-=1 outcome = 'You loose! New deal?' in_play=False #print 'dealer '+str(dealer)+'\nplayer '+str(player) # if hand is in play, repeatedly hit dealer until his hand has value 17 or more # assign a message to outcome, update in_play and score # draw handler def draw(canvas): canvas.draw_text('Blackjack', (50, 200), 36, "Yellow") canvas.draw_text(outcome, (300, 150), 16, "White") canvas.draw_text('Score = '+str(score), (300, 200), 24, "White") pos=[100,300] dealer.draw(canvas, pos) player.draw(canvas, [pos[0],pos[1]+100]) if in_play: card_loc = (CARD_BACK_CENTER[0] + CARD_BACK_SIZE[0],CARD_BACK_CENTER[1] + CARD_BACK_SIZE[1]) #canvas.draw_image(card_back, card_loc, CARD_SIZE, [pos[0] + CARD_BACK_CENTER[0], pos[1]+100 + CARD_BACK_CENTER[1]], CARD_BACK_SIZE) # test to make sure that card.draw works, replace with your code below deal() # initialization frame frame = simplegui.create_frame("Blackjack", 600, 600) frame.set_canvas_background("Green") #create buttons and canvas callback frame.add_button("Deal", deal, 200) frame.add_button("Hit", hit, 200) frame.add_button("Stand", stand, 200) frame.set_draw_handler(draw) # get things rolling frame.start() # remember to review the gradic rubric
相关推荐
Kivy-Interactive-Applications-and-Games-in-Python-2nd-Edition-Create-responsive-cross-platform-UI-UX-applications-and-games-in-Python-using-the-open-source-Kivy-library.pdf
Chapter 6: Dictionaries Chapter 7: User Input and while Loops Chapter 8: Functions Chapter 9: Classes Chapter 10: Files and Exceptions Chapter 11: Testing Your Code Part II: Projects Project 1: Alien...
Python 交互式编程简介Python-mini 项目中交互式编程简介
In this paper we present the ontology matching system LogMap 2, a much improved version of its predecessor LogMap. LogMap 2 supports user interaction during the matching process, which is essential ...
使用Python + Kivy 开发应用程序。 Kivy 是一个跨平台的GUI 支持Window、Linux、Mac、Android
Learning-Robotics-Using-Python-Design-simulate-program-and-prototype-an-interactive-autonomous-mobile-robot-from-scratch-with-the-help-of-Python-ROS-and-Open-CV-.pdf
Interactive Computer Graphics:A.Top-Down Approach with Shader-Based OpenGL(6th.2011)
交互式计算机图形学——基于WEBGL的自顶向下方法 第7版,Interactive Computer Graphics:A Top-Down Approach with WebGL (7th Edition) 英文版
示例:ArrayIndexOutOfBounds 数组越界错误异常会在索引在数组中不存在时抛出 (e.g: 尝试获得 arr[5],但是 arr 数组最大只能获
人机交互经典书籍,系统阐述人机交互内涵、方法、实践、案例等。.epub书籍,可在ibook中打开。
python库。 资源全名:interactive_kit-0.1.3-py3-none-any.whl
与虚拟环境# creamos el entorno virtual> virtualenv --python=python37 interactive-console# ingresamos al directorio del entorno> cd interactive-console# iniciamos el entorno> source ./bin/activate# ...
Authentication: none, password, public-key, hostbased, keyboard-interactive Channels: shell, exec (incl. SCP wrapper), direct-tcpip, subsystem Global Requests: tcpip-forward Channel ...
实验,解释器实现,演示,数据入口切线和Birdong ID的大量注释 Web口译员设置:节点: cd interpreter# node:npm install# venv:python3 -m venv merlinai_venvsource merlinai_venv/bin/activatepip3 install -r ...
Interactive computer graphics : a top-down approach with WebGL ,7th Edition Edward Angel, University of New Mexico, Dave Shreiner, ARM, Inc.
Kivy – Interactive Applications and Games in Python 2nd Edition, will equip you with all the necessary knowledge to create interactive, responsive, and cross-platform applications and games. ...
英文原版
资源分类:Python库 所属语言:Python 资源全名:ignis-0.0.7-py3-none-any.whl 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
interactive-pricing-component:挑战#6
After covering Python Chapters 1—5 and a few key parts of Chapters 6—7, you’ll be able to handle significant portions of the hands-on introductory AI case studies in Chapters 11—16, which are ...