You are on page 1of 6

COMP1127 Introduction to Computing II

2014-2015 Semester I
Assignment
In the game Paper Strip, two players start with a strip of n white squares and they take
alternate turns. Each player is assigned auniquecolour,exceptwhite.Oneachturn,aplayer
picks two contiguous white squares and paints them in his/her assigned colour. The first
playerwhocannotmakeamoveloses.Forexample,if
n=1,therearenovalidmoves,sothefirstplayerlosesautomatically.
n=2,thereisonlyonevalidmove,afterwhichthesecondplayerloses.
n = 3, there are two valid moves, but both leave a situation where the second player
loses.
n =4,therearethreevalid movesforthefirstplayershecanwinthegamebypainting
thetwomiddlesquares.
n =5,therearefourvalidmovesforthefirstplayer(shownbelowinred)butnomatter
whatshedoes,thesecondplayer(blue)wins.

For this assignment we willwrite the codeto create our own Python basedversion of Paper
Strip,butfirstyouwillneedtolearnaboutturtlegraphics.

You will need to use a graphics library to actually draw and colour the strips. For this
assignment, you will be utilising the graphics library that comes bundled with most Python
interpreters, Tkinter. Withinthat library is what you will be using, turtlegraphics.

Be sure
you import the library(remember, justincludethecommandimportturtleat
thebeginning
of your code). The turtle is simply displayed in a separate window, as a small triangle by
default. The followingtablecontainssomeoftheturtlecommandsyouwillneedtouseforthis
assignment (I will include the function that actually draws stuff further down this document
anyway),
1


turtle.showturtle()

Maketheturtlevisible

turtle.penup()

Pullthepenup,nodrawingwhenmoving

turtle.pendown()

Pullthependown,drawingwhenmoving

turtle.goto(x,y)

Move turtle to an absolute position. If the pen is down, draw a


line. Do not change the turtles orientation. (0,0) is the default
startposition,locatedatthecentreofthedisplaywindow

turtle.left(angle)

Turnturtleleftbyangleunits

turtle.right(angle)

Turnturtlerightbyangleunits

turtle.forward(distance)

Move the turtle forwardbythespecifieddistanceinthedirection


theturtleisheaded

turtle.done()

Leavesthewindowopenuntiltheclosebuttonisselected

Try some of these out. Write a small program that starts with turtle.showturtle(), ends
with turtle.done()and

has one or more of the other commands in between. Forexample,


thefollowingbitofcodedrawsasquareinawindow.

import turtle
turtle.showturtle()
turtle.forward(50)
turtle.left(90)
turtle.forward(50)
turtle.left(90)
turtle.forward(50)
turtle.left(90)
turtle.forward(50)
turtle.done()

Experiment with turtle for a bit. When you think you've understood turtle, move ontotherest
oftheassignment.

1. Let us begin by creatingan ADT that we will use as the basicelementofourgame,a


square. The attributesof a square that we want to maintain are the point atwhichwe
willdrawit,thelengthofitssidesanditscolour.Asquaresstartingpointisa2tupleof
integers where the first integer represents the xcoordinate and the second, the
ycoordinate.Ourrepresentationofasquarewillthereforebe,

[Square,startPoint,sidelength,colour]

a. Write a constructor called makeSquarethat

accepts 3 arguments: the starting


point as a tuple, the sidelength as an integer and its colour as a string.
makeSquarereturns

a square ADT as represented above i.e. as a list where


the first element is the tag Square, followed by the starting point, sidelength
andcolourinthatorder

b. Writethefollowingselectors,
i.
getXcoord:acceptsastartingpointandreturnsitsxcoordinate
ii.
getYcoord:acceptsastartingpointandreturnsitsycoordinate
iii.
getStartPt:acceptsasquareandreturnsitsstartingpoint
iv.
getSidelength:acceptsasquareandreturnsitssidelength
v.
getColour:acceptsasquareandreturnsitscolour

c. Write a mutator called setColourthat

accepts a square and a colour and


redraws the square beginning at its current starting point and sidelength, but
withthecolourthatwaspassedasanargument.

2. drawSquareis
the functionthatactuallydrawsasquare,usingturtle,onawindowthat
willpopuponyourscreen.Includethefunctionbelowinyourcode,

def drawSquare(startPt,sidelength,colour):
angle=90
turtle.penup()
turtle.goto(startPt)
turtle.pendown()
turtle.fillcolor(colour)
turtle.begin_fill()
turtle.forward(sidelength)
turtle.left(angle)
turtle.forward(sidelength)
turtle.left(angle)
turtle.forward(sidelength)
turtle.left(angle)
turtle.forward(sidelength)
turtle.left(angle)
turtle.end_fill()
turtle.penup()

Now, from this point onwards, you should not violate any abstractions! If you do, you
willlosemarksregardlessofwhetherornotyourgameworksasitshould!

3. Our strip of paper will consist of a user specified number of white squares. Let us
representastripasadictionarycalledstripSquarewherethekey:valuepairis,
{integer : square}

GloballydefinestripSquarebyincludingthestatementbelowinyourcode,
stripSquare=dict()

Throughoutthegamewewillneedtoaccessspecificsquaresfromourstrip.Writea
functioncalledgetSquarethatacceptsaninteger(akey)andreturnstheassociated
squarefromstripSquare

4. Write a function called drawStripthat

accepts an integerasitsargumentanddraws,
square by square, a strip of length specified by the integerargument. Forexample, if
the user specifies that a strip of length 7 squares is to be drawn, then the integer
argument would be 7 and strip of 7 contiguous squares would bedrawn in the turtle
window. Within drawStrip, specify a sidelength for the squares (if you like, you can
have the user specify this also) and then from within a loop: draw a square add the
square just drawn tostripSquare and set the starting point forthe next, contiguous
squaretobedrawn.Turtlebeginsdrawingatpoint(0,0)bydefault.

Now we will begin to write the functions that control the game play. For our version, the 2
players will be the user and the computer and play will alternatebetweenthem.Theuserwill
beofferedtheopportunitytodecidewhetherornothe/sheplaysfirst.

5. Write a function called validPlaythat

accepts 2 arguments, a players selectionand


the number of squaresin the strip.Aplayersselection isthepositionofthefirstofthe
2 contiguous squares that he/she wishes to change from white to his/her colour.
validPlaychecks

that both the selected square and thenext contiguous square are
still white. If they both are,the play is deemed valid anditreturnsTrue,otherwiseitis
notanditreturnsFalse.

6. Below is the functioncalledgetPlayerPickthat

promptsthe userforhis/herselection
of the first contiguous square for his/her play. Copy the code and include it in your
own.
def getPlayerPick(length): # only the user enters a pick
inRange=False
while not inRange:
pick=int(turtle.textinput("Your move",0))
if pick in range(length):
inRange=True
return pick

7. We need to know when the game is over. We can figure this out by determining
whether or not there are anypairs of contiguous squares remaining.Writea function
called gameOverthat

accepts the numberof squares in the strip as its argument and


determines if there areany pairs of contiguous squares thatarestillwhite.Ifthereare
thenitreturnsTrue,otherwiseitreturnsFalse.

8. Using the randintfunction

in the randomlibrary,

simulate the computer making a


selection by generating a random number that is between 0 and the number of
squaresinthestrip.

9. You also needto write a function called togglePlayerthat

switches the value of the


current player between the user and the computer. As a suggestion,youcouldcreate
another dictionary that has2elements.Thekeyisanumberthatrepresentstheplayer
whilethevalueisthecolourthatwillbeassignedtothatplayer.

10. Now, write a functioncalledmakePlaythat

acceptsaplayers(validated)selectionand
a (players) colour and redraws the 2 contiguous squares at the same position, but in
the players colour. makePlaymust

alsoupdate stripSquarewith

the new colour of


the2squares.

11. We are almost finished. It is time to put all these functions together to create our
game. Write the function playthat

accepts the number ofsquaresinthestripandthe


userschoiceofwhetherhe/shewishestoplayfirst.playdoesthefollowing,

a. drawsthestripwiththenumberofsquareschosenbytheuser
b. assigns the value of the current player to the computer or user, whoever is
playingfirst
c. whilethegameisnotoveritloopsand,
i.
allows the current player to make a play i.e. selecting the first of 2
contiguoussquarestorecolourinhis/hercolour
ii.
validates the selection. It should not proceed until the selection has
beenvalidated
iii.
makestheplaybyrecolouringthepairofcontiguoussquares
iv.
togglestheplayer
d. whenthegameisover,itreturnswhothewinneris

12. Finally, write a function thatinitiatestheplayingofthegame.Itshouldprompttheuser


for the number of squares to draw in the strip, then ask the user if he/she wishes to
play first, then call the function playthat

you wrote in part 11 above. playwould

therefore return who the winner is to this function which would then print who the
winnerisandendthegame.


Thatsit.Onceyouhaveyourgameworking,youcantrytodetermineifaparticularplayerwill
alwayswindependingonthespecificmoveand/orthenumberofsquaresinthestrip.Ihope
youhavefun!

Thisassignmentisworth15%ofyourcourseworkmark.ItisdueonNovember24th2014,at
11pm.PostyoursubmissionviaOurVLE.LookforthecontainernamedAssignment.

You are permitted to work in pairs, therefore ensure that your code has BOTH members' ID
numbersincludedasacomment.

Only one member of the pair is tosubmit. Each person may submit as a member of one (1)
programmingpaironly.Nolatesubmissionswillbeaccepted.

Nameyourfileaccordingtothefollowingconvention,

IFtheIDnumbersofthestudentsare620000001and620000002
THENthefilenameshouldbe620000001_620000002.py

You might also like