SlideShare ist ein Scribd-Unternehmen logo
1 von 6
Downloaden Sie, um offline zu lesen
Convert the DiceDemo program discussed in this chapter to a completed craps game gui
application (crapsgui.py), using the Player data model class you developed in Project 6
(craps.py).
Be sure to use the field names provided in the comments in your starter code.
crapsgui.py
"""
File: crapsgui.py
Project 9.7
Pops up a window that allows the user to play the game of craps.
"""
from breezypythongui import EasyFrame
from tkinter import PhotoImage
from craps import Player
class CrapsGUI(EasyFrame):
def __init__(self):
"""Creates the player, and sets up the Images and labels for the two dice to be displayed, the
text area for the game state, and the two command buttons."""
EasyFrame.__init__(self, title = "Craps Game")
self.setSize(220, 320)
"""Instantiate the model and initial values of the dice"""
# self.player
# self.v1
# self.v2
"""Add labels and buttons to the view"""
# self.dieLabel1
# self.dieLabel2
# self.stateArea
# self.rollButton
# self.addButton
self.refreshImages()
def nextRoll(self):
"""Rolls the dice and updates the view with
the results."""
# Add your code here
def newGame(self):
"""Create a new craps game and updates the view."""
# Add your code here
def refreshImages(self):
"""Updates the images in the window."""
# Add your code here
def main():
CrapsGUI().mainloop()
if __name__ == "__main__":
main()
craps.py
"""
File: craps.py
Project 6
This module studies and plays the game of craps.
Refactors code from case study so that the user
can have the Player object roll the dice and view
the result.
"""
from die import Die
class Player(object):
def __init__(self):
"""Has a pair of dice and an empty rolls list."""
self.die1 = Die()
self.die2 = Die()
self.roll = ""
self.rollsCount = 0
self.atStartup = True
self.winner = self.loser = False
def __str__(self):
"""Returns a string representation of the last roll."""
return self.roll
def getNumberOfRolls(self):
"""Returns the number of the rolls."""
return self.rollsCount
def rollDice(self):
"""Rolls the dice once. Updates the roll, the won and
lost outcomes, and returns a tuple of the values
of the dice."""
self.rollsCount += 1
self.die1.roll()
self.die2.roll()
(v1, v2) = (self.die1.getValue(),
self.die2.getValue())
self.roll = str((v1, v2)) + " total = " + str(v1 + v2)
# Game logic for one roll of the dice.
if self.atStartup:
self.initialSum = v1 + v2
self.atStartup = False
if self.initialSum in (2, 3, 12):
self.loser = True
elif self.initialSum in (7, 11):
self.winner = True
else:
laterSum = v1 + v2
if laterSum == 7:
self.loser = True
elif laterSum == self.initialSum:
self.winner = True
return (v1, v2)
# Note: both isWinner() and isLoser() can be False,
# if the game is not finished.
def isWinner(self):
"""Returns True if player has won."""
return self.winner
def isLoser(self):
"""Returns True if player has lost."""
return self.loser
def play(self):
"""Plays a game, counts the rolls for that game,
and returns True for a win and False for a loss."""
while not self.isWinner() and not self.isLoser():
self.rollDice()
return self.isWinner()
def playOneGame():
"""Plays a single game and prints the results after
each roll."""
player = Player()
while not player.isWinner() and not player.isLoser():
player.rollDice()
print(player)
if player.isWinner():
print("You win!")
else:
print("You lose!")
def playManyGames(number):
"""Plays a number of games and prints statistics."""
wins = 0
losses = 0
winRolls = 0
lossRolls = 0
for count in range(number):
player = Player()
hasWon = player.play()
rolls = player.getNumberOfRolls()
if hasWon:
wins += 1
winRolls += rolls
else:
losses += 1
lossRolls += rolls
print("The total number of wins is", wins)
print("The total number of losses is", losses)
print("The average number of rolls per win is %0.2f" % 
(winRolls / wins))
print("The average number of rolls per loss is %0.2f" % 
(lossRolls / losses))
print("The winning percentage is %0.3f" % (wins / number))
def main():
"""Plays one game and then a number of games and prints statistics."""
playOneGame()
number = int(input("Enter the number of games: "))
playManyGames(number)
if __name__ == "__main__":
main()
die.py
"""
File: die.py
This module defines the Die class.
"""
from random import randint
class Die:
"""This class represents a six-sided die."""
def __init__(self):
"""Creates a new die with a value of 1."""
self.value = 1
def roll(self):
"""Resets the die's value to a random number
between 1 and 6."""
self.value = randint(1, 6)
def getValue(self):
"""Returns the value of the die's top face."""
return self.value
def __str__(self):
"""Returns the string rep of the die."""
return str(self.getValue())
I need help on this but Carefull I want use the same fileld names which provided up there.

Weitere ähnliche Inhalte

Ähnlich wie Convert the DiceDemo program discussed in this chapter to a complete.pdf

The Ring programming language version 1.5.3 book - Part 58 of 184
The Ring programming language version 1.5.3 book - Part 58 of 184The Ring programming language version 1.5.3 book - Part 58 of 184
The Ring programming language version 1.5.3 book - Part 58 of 184Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 48 of 184
The Ring programming language version 1.5.3 book - Part 48 of 184The Ring programming language version 1.5.3 book - Part 48 of 184
The Ring programming language version 1.5.3 book - Part 48 of 184Mahmoud Samir Fayed
 
The Ring programming language version 1.4 book - Part 14 of 30
The Ring programming language version 1.4 book - Part 14 of 30The Ring programming language version 1.4 book - Part 14 of 30
The Ring programming language version 1.4 book - Part 14 of 30Mahmoud Samir Fayed
 
The following GUI is displayed once the application startsThe sug.pdf
The following GUI is displayed once the application startsThe sug.pdfThe following GUI is displayed once the application startsThe sug.pdf
The following GUI is displayed once the application startsThe sug.pdfarihantsherwani
 
The Ring programming language version 1.8 book - Part 76 of 202
The Ring programming language version 1.8 book - Part 76 of 202The Ring programming language version 1.8 book - Part 76 of 202
The Ring programming language version 1.8 book - Part 76 of 202Mahmoud Samir Fayed
 
Intro to programming games with clojure
Intro to programming games with clojureIntro to programming games with clojure
Intro to programming games with clojureJuio Barros
 
The Ring programming language version 1.10 book - Part 71 of 212
The Ring programming language version 1.10 book - Part 71 of 212The Ring programming language version 1.10 book - Part 71 of 212
The Ring programming language version 1.10 book - Part 71 of 212Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 74 of 196
The Ring programming language version 1.7 book - Part 74 of 196The Ring programming language version 1.7 book - Part 74 of 196
The Ring programming language version 1.7 book - Part 74 of 196Mahmoud Samir Fayed
 
The Ring programming language version 1.3 book - Part 38 of 88
The Ring programming language version 1.3 book - Part 38 of 88The Ring programming language version 1.3 book - Part 38 of 88
The Ring programming language version 1.3 book - Part 38 of 88Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 80 of 210
The Ring programming language version 1.9 book - Part 80 of 210The Ring programming language version 1.9 book - Part 80 of 210
The Ring programming language version 1.9 book - Part 80 of 210Mahmoud Samir Fayed
 

Ähnlich wie Convert the DiceDemo program discussed in this chapter to a complete.pdf (13)

The Ring programming language version 1.5.3 book - Part 58 of 184
The Ring programming language version 1.5.3 book - Part 58 of 184The Ring programming language version 1.5.3 book - Part 58 of 184
The Ring programming language version 1.5.3 book - Part 58 of 184
 
The Ring programming language version 1.5.3 book - Part 48 of 184
The Ring programming language version 1.5.3 book - Part 48 of 184The Ring programming language version 1.5.3 book - Part 48 of 184
The Ring programming language version 1.5.3 book - Part 48 of 184
 
The Ring programming language version 1.4 book - Part 14 of 30
The Ring programming language version 1.4 book - Part 14 of 30The Ring programming language version 1.4 book - Part 14 of 30
The Ring programming language version 1.4 book - Part 14 of 30
 
The following GUI is displayed once the application startsThe sug.pdf
The following GUI is displayed once the application startsThe sug.pdfThe following GUI is displayed once the application startsThe sug.pdf
The following GUI is displayed once the application startsThe sug.pdf
 
The Ring programming language version 1.8 book - Part 76 of 202
The Ring programming language version 1.8 book - Part 76 of 202The Ring programming language version 1.8 book - Part 76 of 202
The Ring programming language version 1.8 book - Part 76 of 202
 
Intro to programming games with clojure
Intro to programming games with clojureIntro to programming games with clojure
Intro to programming games with clojure
 
The Ring programming language version 1.10 book - Part 71 of 212
The Ring programming language version 1.10 book - Part 71 of 212The Ring programming language version 1.10 book - Part 71 of 212
The Ring programming language version 1.10 book - Part 71 of 212
 
Bow&arrow game
Bow&arrow gameBow&arrow game
Bow&arrow game
 
The Ring programming language version 1.7 book - Part 74 of 196
The Ring programming language version 1.7 book - Part 74 of 196The Ring programming language version 1.7 book - Part 74 of 196
The Ring programming language version 1.7 book - Part 74 of 196
 
The Ring programming language version 1.3 book - Part 38 of 88
The Ring programming language version 1.3 book - Part 38 of 88The Ring programming language version 1.3 book - Part 38 of 88
The Ring programming language version 1.3 book - Part 38 of 88
 
The Ring programming language version 1.9 book - Part 80 of 210
The Ring programming language version 1.9 book - Part 80 of 210The Ring programming language version 1.9 book - Part 80 of 210
The Ring programming language version 1.9 book - Part 80 of 210
 
Game dev 101 part 3
Game dev 101 part 3Game dev 101 part 3
Game dev 101 part 3
 
python.pptx
python.pptxpython.pptx
python.pptx
 

Mehr von americanopticalsmdu

convert this python code to java script. Make sure it works on Eclip.pdf
convert this python code to java script. Make sure it works on Eclip.pdfconvert this python code to java script. Make sure it works on Eclip.pdf
convert this python code to java script. Make sure it works on Eclip.pdfamericanopticalsmdu
 
Convert M9 to a regular expression. Consider the following generalis.pdf
Convert M9 to a regular expression. Consider the following generalis.pdfConvert M9 to a regular expression. Consider the following generalis.pdf
Convert M9 to a regular expression. Consider the following generalis.pdfamericanopticalsmdu
 
Contesta las preguntas del siguiente p�rrafo �Deber�a respons.pdf
Contesta las preguntas del siguiente p�rrafo �Deber�a respons.pdfContesta las preguntas del siguiente p�rrafo �Deber�a respons.pdf
Contesta las preguntas del siguiente p�rrafo �Deber�a respons.pdfamericanopticalsmdu
 
CONTRATO DE ARRENDAMIENTO COMERCIAL Este Contrato de Arrendamiento C.pdf
CONTRATO DE ARRENDAMIENTO COMERCIAL Este Contrato de Arrendamiento C.pdfCONTRATO DE ARRENDAMIENTO COMERCIAL Este Contrato de Arrendamiento C.pdf
CONTRATO DE ARRENDAMIENTO COMERCIAL Este Contrato de Arrendamiento C.pdfamericanopticalsmdu
 
Considere una econom�a donde la industria dominante es la producci�n.pdf
Considere una econom�a donde la industria dominante es la producci�n.pdfConsidere una econom�a donde la industria dominante es la producci�n.pdf
Considere una econom�a donde la industria dominante es la producci�n.pdfamericanopticalsmdu
 
Considere una econom�a descrita por las siguientes ecuacionesY .pdf
Considere una econom�a descrita por las siguientes ecuacionesY .pdfConsidere una econom�a descrita por las siguientes ecuacionesY .pdf
Considere una econom�a descrita por las siguientes ecuacionesY .pdfamericanopticalsmdu
 
Considere todo lo que ha aprendido en este curso sobre problemas soc.pdf
Considere todo lo que ha aprendido en este curso sobre problemas soc.pdfConsidere todo lo que ha aprendido en este curso sobre problemas soc.pdf
Considere todo lo que ha aprendido en este curso sobre problemas soc.pdfamericanopticalsmdu
 
Considere los virus en soluci�n como una suspensi�n. �C�mo esperar�a.pdf
Considere los virus en soluci�n como una suspensi�n. �C�mo esperar�a.pdfConsidere los virus en soluci�n como una suspensi�n. �C�mo esperar�a.pdf
Considere los virus en soluci�n como una suspensi�n. �C�mo esperar�a.pdfamericanopticalsmdu
 
Considere los roles de las partes interesadas internas y externas y .pdf
Considere los roles de las partes interesadas internas y externas y .pdfConsidere los roles de las partes interesadas internas y externas y .pdf
Considere los roles de las partes interesadas internas y externas y .pdfamericanopticalsmdu
 
Make in java programming Receive a piece of text and a comparison str.pdf
 Make in java programming Receive a piece of text and a comparison str.pdf Make in java programming Receive a piece of text and a comparison str.pdf
Make in java programming Receive a piece of text and a comparison str.pdfamericanopticalsmdu
 
Make sure you enter the proper units for all physical quantities in t.pdf
 Make sure you enter the proper units for all physical quantities in t.pdf Make sure you enter the proper units for all physical quantities in t.pdf
Make sure you enter the proper units for all physical quantities in t.pdfamericanopticalsmdu
 
Macromolecules which may be structural parts of the cell, may act as .pdf
 Macromolecules which may be structural parts of the cell, may act as .pdf Macromolecules which may be structural parts of the cell, may act as .pdf
Macromolecules which may be structural parts of the cell, may act as .pdfamericanopticalsmdu
 
Macys, Incorporated, operates the two best-known high-end department.pdf
 Macys, Incorporated, operates the two best-known high-end department.pdf Macys, Incorporated, operates the two best-known high-end department.pdf
Macys, Incorporated, operates the two best-known high-end department.pdfamericanopticalsmdu
 
MACRS RATE Under MACRS, an asset which originally cost $100,000 is be.pdf
 MACRS RATE Under MACRS, an asset which originally cost $100,000 is be.pdf MACRS RATE Under MACRS, an asset which originally cost $100,000 is be.pdf
MACRS RATE Under MACRS, an asset which originally cost $100,000 is be.pdfamericanopticalsmdu
 
Match the following terms to the correct description Anchor residues .pdf
 Match the following terms to the correct description Anchor residues .pdf Match the following terms to the correct description Anchor residues .pdf
Match the following terms to the correct description Anchor residues .pdfamericanopticalsmdu
 
Match the following to the descriptions provided. Drag and .pdf
 Match the following to the descriptions provided. Drag and .pdf Match the following to the descriptions provided. Drag and .pdf
Match the following to the descriptions provided. Drag and .pdfamericanopticalsmdu
 
Match the event with the most appropriate term. Different species of .pdf
 Match the event with the most appropriate term. Different species of .pdf Match the event with the most appropriate term. Different species of .pdf
Match the event with the most appropriate term. Different species of .pdfamericanopticalsmdu
 
Match the correct answer Gel A. negatively charged Ethidium bromide B.pdf
 Match the correct answer Gel A. negatively charged Ethidium bromide B.pdf Match the correct answer Gel A. negatively charged Ethidium bromide B.pdf
Match the correct answer Gel A. negatively charged Ethidium bromide B.pdfamericanopticalsmdu
 
Match the following lettersnumbers with what they represent.The F.pdf
 Match the following lettersnumbers with what they represent.The F.pdf Match the following lettersnumbers with what they represent.The F.pdf
Match the following lettersnumbers with what they represent.The F.pdfamericanopticalsmdu
 
Match the following rock names with their corresponding description R.pdf
 Match the following rock names with their corresponding description R.pdf Match the following rock names with their corresponding description R.pdf
Match the following rock names with their corresponding description R.pdfamericanopticalsmdu
 

Mehr von americanopticalsmdu (20)

convert this python code to java script. Make sure it works on Eclip.pdf
convert this python code to java script. Make sure it works on Eclip.pdfconvert this python code to java script. Make sure it works on Eclip.pdf
convert this python code to java script. Make sure it works on Eclip.pdf
 
Convert M9 to a regular expression. Consider the following generalis.pdf
Convert M9 to a regular expression. Consider the following generalis.pdfConvert M9 to a regular expression. Consider the following generalis.pdf
Convert M9 to a regular expression. Consider the following generalis.pdf
 
Contesta las preguntas del siguiente p�rrafo �Deber�a respons.pdf
Contesta las preguntas del siguiente p�rrafo �Deber�a respons.pdfContesta las preguntas del siguiente p�rrafo �Deber�a respons.pdf
Contesta las preguntas del siguiente p�rrafo �Deber�a respons.pdf
 
CONTRATO DE ARRENDAMIENTO COMERCIAL Este Contrato de Arrendamiento C.pdf
CONTRATO DE ARRENDAMIENTO COMERCIAL Este Contrato de Arrendamiento C.pdfCONTRATO DE ARRENDAMIENTO COMERCIAL Este Contrato de Arrendamiento C.pdf
CONTRATO DE ARRENDAMIENTO COMERCIAL Este Contrato de Arrendamiento C.pdf
 
Considere una econom�a donde la industria dominante es la producci�n.pdf
Considere una econom�a donde la industria dominante es la producci�n.pdfConsidere una econom�a donde la industria dominante es la producci�n.pdf
Considere una econom�a donde la industria dominante es la producci�n.pdf
 
Considere una econom�a descrita por las siguientes ecuacionesY .pdf
Considere una econom�a descrita por las siguientes ecuacionesY .pdfConsidere una econom�a descrita por las siguientes ecuacionesY .pdf
Considere una econom�a descrita por las siguientes ecuacionesY .pdf
 
Considere todo lo que ha aprendido en este curso sobre problemas soc.pdf
Considere todo lo que ha aprendido en este curso sobre problemas soc.pdfConsidere todo lo que ha aprendido en este curso sobre problemas soc.pdf
Considere todo lo que ha aprendido en este curso sobre problemas soc.pdf
 
Considere los virus en soluci�n como una suspensi�n. �C�mo esperar�a.pdf
Considere los virus en soluci�n como una suspensi�n. �C�mo esperar�a.pdfConsidere los virus en soluci�n como una suspensi�n. �C�mo esperar�a.pdf
Considere los virus en soluci�n como una suspensi�n. �C�mo esperar�a.pdf
 
Considere los roles de las partes interesadas internas y externas y .pdf
Considere los roles de las partes interesadas internas y externas y .pdfConsidere los roles de las partes interesadas internas y externas y .pdf
Considere los roles de las partes interesadas internas y externas y .pdf
 
Make in java programming Receive a piece of text and a comparison str.pdf
 Make in java programming Receive a piece of text and a comparison str.pdf Make in java programming Receive a piece of text and a comparison str.pdf
Make in java programming Receive a piece of text and a comparison str.pdf
 
Make sure you enter the proper units for all physical quantities in t.pdf
 Make sure you enter the proper units for all physical quantities in t.pdf Make sure you enter the proper units for all physical quantities in t.pdf
Make sure you enter the proper units for all physical quantities in t.pdf
 
Macromolecules which may be structural parts of the cell, may act as .pdf
 Macromolecules which may be structural parts of the cell, may act as .pdf Macromolecules which may be structural parts of the cell, may act as .pdf
Macromolecules which may be structural parts of the cell, may act as .pdf
 
Macys, Incorporated, operates the two best-known high-end department.pdf
 Macys, Incorporated, operates the two best-known high-end department.pdf Macys, Incorporated, operates the two best-known high-end department.pdf
Macys, Incorporated, operates the two best-known high-end department.pdf
 
MACRS RATE Under MACRS, an asset which originally cost $100,000 is be.pdf
 MACRS RATE Under MACRS, an asset which originally cost $100,000 is be.pdf MACRS RATE Under MACRS, an asset which originally cost $100,000 is be.pdf
MACRS RATE Under MACRS, an asset which originally cost $100,000 is be.pdf
 
Match the following terms to the correct description Anchor residues .pdf
 Match the following terms to the correct description Anchor residues .pdf Match the following terms to the correct description Anchor residues .pdf
Match the following terms to the correct description Anchor residues .pdf
 
Match the following to the descriptions provided. Drag and .pdf
 Match the following to the descriptions provided. Drag and .pdf Match the following to the descriptions provided. Drag and .pdf
Match the following to the descriptions provided. Drag and .pdf
 
Match the event with the most appropriate term. Different species of .pdf
 Match the event with the most appropriate term. Different species of .pdf Match the event with the most appropriate term. Different species of .pdf
Match the event with the most appropriate term. Different species of .pdf
 
Match the correct answer Gel A. negatively charged Ethidium bromide B.pdf
 Match the correct answer Gel A. negatively charged Ethidium bromide B.pdf Match the correct answer Gel A. negatively charged Ethidium bromide B.pdf
Match the correct answer Gel A. negatively charged Ethidium bromide B.pdf
 
Match the following lettersnumbers with what they represent.The F.pdf
 Match the following lettersnumbers with what they represent.The F.pdf Match the following lettersnumbers with what they represent.The F.pdf
Match the following lettersnumbers with what they represent.The F.pdf
 
Match the following rock names with their corresponding description R.pdf
 Match the following rock names with their corresponding description R.pdf Match the following rock names with their corresponding description R.pdf
Match the following rock names with their corresponding description R.pdf
 

Kürzlich hochgeladen

Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactisticshameyhk98
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptxJoelynRubio1
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationNeilDeclaro1
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 

Kürzlich hochgeladen (20)

Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactistics
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health Education
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 

Convert the DiceDemo program discussed in this chapter to a complete.pdf

  • 1. Convert the DiceDemo program discussed in this chapter to a completed craps game gui application (crapsgui.py), using the Player data model class you developed in Project 6 (craps.py). Be sure to use the field names provided in the comments in your starter code. crapsgui.py """ File: crapsgui.py Project 9.7 Pops up a window that allows the user to play the game of craps. """ from breezypythongui import EasyFrame from tkinter import PhotoImage from craps import Player class CrapsGUI(EasyFrame): def __init__(self): """Creates the player, and sets up the Images and labels for the two dice to be displayed, the text area for the game state, and the two command buttons.""" EasyFrame.__init__(self, title = "Craps Game") self.setSize(220, 320) """Instantiate the model and initial values of the dice""" # self.player # self.v1 # self.v2 """Add labels and buttons to the view""" # self.dieLabel1 # self.dieLabel2 # self.stateArea # self.rollButton # self.addButton self.refreshImages() def nextRoll(self):
  • 2. """Rolls the dice and updates the view with the results.""" # Add your code here def newGame(self): """Create a new craps game and updates the view.""" # Add your code here def refreshImages(self): """Updates the images in the window.""" # Add your code here def main(): CrapsGUI().mainloop() if __name__ == "__main__": main() craps.py """ File: craps.py Project 6 This module studies and plays the game of craps. Refactors code from case study so that the user can have the Player object roll the dice and view the result. """ from die import Die class Player(object): def __init__(self): """Has a pair of dice and an empty rolls list.""" self.die1 = Die() self.die2 = Die() self.roll = ""
  • 3. self.rollsCount = 0 self.atStartup = True self.winner = self.loser = False def __str__(self): """Returns a string representation of the last roll.""" return self.roll def getNumberOfRolls(self): """Returns the number of the rolls.""" return self.rollsCount def rollDice(self): """Rolls the dice once. Updates the roll, the won and lost outcomes, and returns a tuple of the values of the dice.""" self.rollsCount += 1 self.die1.roll() self.die2.roll() (v1, v2) = (self.die1.getValue(), self.die2.getValue()) self.roll = str((v1, v2)) + " total = " + str(v1 + v2) # Game logic for one roll of the dice. if self.atStartup: self.initialSum = v1 + v2 self.atStartup = False if self.initialSum in (2, 3, 12): self.loser = True elif self.initialSum in (7, 11): self.winner = True else: laterSum = v1 + v2 if laterSum == 7: self.loser = True elif laterSum == self.initialSum: self.winner = True
  • 4. return (v1, v2) # Note: both isWinner() and isLoser() can be False, # if the game is not finished. def isWinner(self): """Returns True if player has won.""" return self.winner def isLoser(self): """Returns True if player has lost.""" return self.loser def play(self): """Plays a game, counts the rolls for that game, and returns True for a win and False for a loss.""" while not self.isWinner() and not self.isLoser(): self.rollDice() return self.isWinner() def playOneGame(): """Plays a single game and prints the results after each roll.""" player = Player() while not player.isWinner() and not player.isLoser(): player.rollDice() print(player) if player.isWinner(): print("You win!") else: print("You lose!") def playManyGames(number): """Plays a number of games and prints statistics.""" wins = 0 losses = 0
  • 5. winRolls = 0 lossRolls = 0 for count in range(number): player = Player() hasWon = player.play() rolls = player.getNumberOfRolls() if hasWon: wins += 1 winRolls += rolls else: losses += 1 lossRolls += rolls print("The total number of wins is", wins) print("The total number of losses is", losses) print("The average number of rolls per win is %0.2f" % (winRolls / wins)) print("The average number of rolls per loss is %0.2f" % (lossRolls / losses)) print("The winning percentage is %0.3f" % (wins / number)) def main(): """Plays one game and then a number of games and prints statistics.""" playOneGame() number = int(input("Enter the number of games: ")) playManyGames(number) if __name__ == "__main__": main() die.py """ File: die.py This module defines the Die class. """ from random import randint
  • 6. class Die: """This class represents a six-sided die.""" def __init__(self): """Creates a new die with a value of 1.""" self.value = 1 def roll(self): """Resets the die's value to a random number between 1 and 6.""" self.value = randint(1, 6) def getValue(self): """Returns the value of the die's top face.""" return self.value def __str__(self): """Returns the string rep of the die.""" return str(self.getValue()) I need help on this but Carefull I want use the same fileld names which provided up there.