Sei sulla pagina 1di 4

Lab4

Released:Tuesday,January19@5:00PM
Due:endofyourlabsection

Warning:Thecodeinlab4.pythatwehavegivenyouiscalledskeletoncode.YOUSHOULD
NOTCHANGEOURSKELETONCODE.Wetrytosetupthelabsinawaythatwillmakethem
intuitiveforyou;ifyouchangethecodewegiveyoubecauseitmakesyourliveeasierin
oneplace,itlikelymakesitmuchmuchhardersomewhereelse.Ifyouchangeskeleton
codeweWILLNOTgiveyouacheckoffonthatsection.

Goals
1. Practicewritingclasses
2. Understandcombiningmultipleclassestogether
3. Understandinheritanceandtheusesofit

PartI

Bytheendofthislab,wearegoingtohaveasimplifiedversionofthegameBattleship!
Download
lab4.py
.
Readthroughtheskeletoncodewehavegivenyou,andthen:

1. Fillinthe
Ship
class
a. __init__
b. get_is_sunk
c. set_is_sunk
Hint:thismightseemsimilartoPS6
2. Fillinthe
Square
class.
DoyourememberhowweexplainedagridinPS6?
Square
isaclassthatrepresentsone
squareonagrid.Laterinthelab,wewillusemanyinstancesof
Square
torepresentour
gridthatwewillplaybattleshipon.
a. __init__
b. contains_ship
c. get_is_attacked
d. get_ship
e. set_is_attacked
f. set_ship

Whenyoufillintheseclasses,remembertodeleteallofthe
pass#TODO
lines.Recallthat
gettersandsetterstypicallycanbewritteninonelineofcode.Thismeansyoushouldnotbe
writingalotofcodeineachofthesefunctionspleaseaskastaffmemberifyoufindyourself
writingmorethanafewlines!

Checkoff1(2points)
Onceyouhavefilledouttheseclasses,andhavethoroughlytestedthemtomakesuretheywork,
youshouldaddyournametotheCheckoffQueue.BepreparedtotalktoanLAabouthowyou
wrotetheclassandbepreparedtodemonstratehowtocreateaninstanceoftheclassanduse
thatinstancetocallamethod.

PartII

Thenextstepistofillinthe
Board
class.The
Board
classwillbeusedtorepresenttheboard
thatwewillplayBattleshipon.Eachinstanceof
Board
hasasetof
Squares
thatcompriseit,
andeach
Square
hastheabilitytoholda
Ship
.
Filloutthefollowing
Board
methods:

1. __init__
a. For
self.ships
,wewanttohavealistofobjectsoftype
Ship
.Thismeansthat
youneedtocreate
num_ships
instancesof
Ship
(whichhavenotbeensunkyet)
toaddto
self.ships
.Thisallhappenswithinthe
__init__
method.
b. Youwillalsoneedtomake
self.squares
adictionary.Hint:self.squaresis
similarto
make_grid
inPS6.Remember,thetopleftsquareshouldbe(0,0),
wherethefirstnumberisthecolumnnumberandthesecondnumberistherow
number.
2. get_num_cols
3. get_num_rows
4. get_squares

Checkoff2(3points)
Onceyouhavefilledoutthe
__init__
andthegettersforthisclass,andhavethoroughlytested
ittomakesureitworks,youshouldaddyournametotheCheckoffQueue.Bepreparedtotalkto
anLAabouthowyouwilluseattributes,andhowyoumadeandcanuseself.shipsand
self.squares.

Next,finishfillingoutthe
Board
classbyimplementingthefollowingmethodsaccordingtothe
provideddocstrings:
1. is_valid_square
2. place_ship
a. Note:
Ship
sareone
Square
byone
Square
.
b. Hint:Thisshouldbesimilarto
randomly_assign
inPS6!
3. update
4. all_ships_sunk
a. Hint:Thinkabouthowyouwrote
contains_vowels
inPS4.Youshould
considerusingasimilarstructurewhenimplementingthisfunction!

Makesurethatyouhave
lab4.py
,
battleship_graphics.py
,and
graphics.py
allinthe
samefolder.Ifyouhaveimplementedalloftheclassesandtheirfunctionscorrectlyand
accordingtothedocstrings,whenyouhitrun,youshouldbeabletoplayyourBattleshipgame!
Clickonanysquaretotrytoattackshipsifsuccessful,thesquarewillturnred!Ifyoudidnot
findaship,itwillturngray.Hint:youmayfinditusefultoincludeprintstatementsafterplacing
shipssoyouknowwherethesepiecesarelocatedonyourgameboard.Youcanthenusethis
informationtoensureyourgamebehavesappropriatelywhenyouclickonthecorresponding
squares.

Checkoff3(5points)
Onceyouhavefinishedfillingoutthisclass,andhavethoroughlytestedittomakesureitworks,
youshouldaddyournametotheCheckoffQueue.BepreparedtotalktoanLAaboutyourclasss

methods,howtheywork,andhowtheyareusefulwhenplayingthegame!Theywillalsoaskyou
todemonstrateplayingagametoensureyourcodeworksasexpected.

PartIII(Optional)

Note:thispartisoptionalandcompletingCheckoff4willgetyou5pointsofextracreditonyour
labifcompletedwithin24hoursoftheendofyourlabsection.Wehighlyrecommendatleast
attemptingthispartastherewilldefinitelybeaquestiononExam3whereyouwillhavetowrite
asubclass.

Now,letsmakeourgamealittlebitmorefunbyaddinganothertypeof
Square
,calleda
MinedSquare
.Whenyouattacka
MinedSquare
,itwillexplodeandtherefore,itsneighboring
squareswillalsobeattacked!

DuringWednesdayslecture,welearnedaboutinheritance.
MinedSquare
isgoingtobea
subclassorchildclassof
Square
.Toput
MinedSquare
inyourgame,completethefollowing
tasks:

1. Addanattributetoyour
Square
class,
is_mined,
whichisabooleanthatdetermines
whetherornotthe
Square
containsamine.Thisshouldalwaysstartas
False
.
2. Addagetterforthe
self.is_mined
attributetoyour
Square
class,
get_is_mined
3. Makeaclasscalled
MinedSquare
thatinheritsfrom
Square
a. MinedSquare
shouldhavean
__init__
methodthatcalls
Square
sinit
methodandthenoverwritethevalueof
self.is_mined
sothatitisalways
True
.
b. MinedSquare
shouldoverwritethe
Square
classs
set_ship.
Itshouldraisea
TypeError
ifwetrytoplacea
Ship
onthis
Square.
4. Addupdatestoyour
Board
classtohandle
MinedSquares
.
a. __init__
shouldinitialize
self.squares
sothatapproximately5%ofthe
time,youwillhavea
MinedSquare
insteadofa
Square
.
i.
Hint:thefollowingcodewillprintHi!approximately5%ofthetimeask
astaffmemberifyoudontunderstandwhy.
ifrandom.random()<0.05:

printHi!
b. place_ship
shouldbemodifiedsoifwetrytoplaceashipona
MinedSquare
,
wewillsomehowrecognizethisisnotpermittedandtrytoplacetheship
somewhereelse.Twopossiblewaystodothis:
i.
Ifyoutrytocall
MinedSquare
s
set_ship
method,itshouldthrowa
TypeError.
Wecanusetry/exceptsothatifweseethiserror,wecall
place_ship
againandtrytofinda
Square
withoutamine.
ii.
Wecanonlytrytoplaceashipiftheselected
Square
isvalid,doesnot
containaship,andisnotmined.
c. update
shouldalsocheckifa
Square
ismined.Ifitis,wealsohavetoupdateall
neighboring
Squares
.Youshouldutilizethe
get_neighbors
functionwehave
providedforyouinthe
Board
class.
5. addthefollowinglinesofcodeto
battleship_graphics.py
beforethe
else
inline
70

elifboard_squares[(col,row)].get_is_mined():
self.graphics[(col,row)].setFill(MINED_COLOR)

Whendebuggingyourgame,youmayfinditusefultoincludeprintstatementsafterplacingships
and
MinedSquares
soyouknowwherethesepiecesarelocatedonyourgameboard.Youcan
thenusethisinformationtoensureyourgamebehavesappropriatelywhenyouclickonthe
correspondingsquares.Notethat
MinedSquares
willturnblackwhentheyareattacked.

Checkoff4(5points)
Onceyouhavefinishedfillingoutthisclass,andhavethoroughlytestedittomakesureitworks,
youshouldaddyournametotheCheckoffQueue.BepreparedtotalktoanLAabouthowyour
classfunctions,inheritance,andhowitisusefulinthissituation.

Potrebbero piacerti anche