Difference between revisions of "CSC111 Programs for Week 10 2015"
(→Display Checkers) |
(→Aquarium) |
||
(One intermediate revision by the same user not shown) | |||
Line 544: | Line 544: | ||
<br /> | <br /> | ||
<br /> | <br /> | ||
+ | ==Remove Checkers, One by One== | ||
+ | <br /> | ||
+ | <source lang="python"> | ||
+ | # checkers00.py | ||
+ | # D. Thiebaut | ||
+ | # Displays checker board. Then displays 3 rows of white | ||
+ | # and black checkers pieces. | ||
+ | # Allows the user to remove checkers, one by one, by | ||
+ | # clicking on them. | ||
+ | # | ||
+ | from graphics import * | ||
+ | |||
+ | WIDTH = 680 # width of the window | ||
+ | HEIGHT= 680 # height of the window | ||
+ | SIDE = 680//8 # the side of a cell of the 8x8 board | ||
+ | |||
+ | class Piece: | ||
+ | def __init__( self, ii, jj, col ): | ||
+ | self.i = ii | ||
+ | self.j = jj | ||
+ | self.color = col | ||
+ | x = ii * SIDE + SIDE//2 | ||
+ | y = jj * SIDE + SIDE//2 | ||
+ | """ | ||
+ | self.circ1 = Circle( Point( x, y ), SIDE//2 ) | ||
+ | if col=="white": | ||
+ | self.circ1.setFill( color_rgb( 250, 250, 250 ) ) | ||
+ | else: | ||
+ | self.circ1.setFill( color_rgb( 10, 10, 10 ) ) | ||
+ | |||
+ | self.circ2 = Circle( Point( x, y ), SIDE//2 - 5 ) | ||
+ | if col=="white": | ||
+ | self.circ2.setFill( color_rgb( 230, 230, 230 ) ) | ||
+ | else: | ||
+ | self.circ2.setFill( color_rgb( 50, 50, 50 ) ) | ||
+ | """ | ||
+ | if col=="white": | ||
+ | self.image = Image( Point( x, y ), "piece2.gif" ) | ||
+ | else: | ||
+ | self.image = Image( Point( x, y ), "piece.gif" ) | ||
+ | |||
+ | def __str__( self ): | ||
+ | return "Piece: ({0:1},{1:1}) {2:1}".format( self.i, self.j, self.color ) | ||
+ | |||
+ | def draw( self, win ): | ||
+ | """ | ||
+ | self.circ1.draw( win ) | ||
+ | self.circ2.draw( win ) | ||
+ | """ | ||
+ | self.image.draw( win ) | ||
+ | |||
+ | def undraw( self ): | ||
+ | self.image.undraw() | ||
+ | |||
+ | def getI( self ): | ||
+ | return self.i | ||
+ | |||
+ | def getJ( self ): | ||
+ | return self.j | ||
+ | |||
+ | def moveToSquare( self, i, j, win ): | ||
+ | destX = i * SIDE + SIDE//2 | ||
+ | destY = j * SIDE + SIDE//2 | ||
+ | currentX = self.i * SIDE + SIDE//2 | ||
+ | currentY = self.j * SIDE + SIDE//2 | ||
+ | deltaX = destX - currentX | ||
+ | deltaY = destY - currentY | ||
+ | self.image.undraw() | ||
+ | self.image._move( deltaX, deltaY ) | ||
+ | self.image.draw( win ) | ||
+ | self.i = i | ||
+ | self.j = j | ||
+ | |||
+ | def displayBoard( win ): | ||
+ | """display an 8x8 board""" | ||
+ | for i in range( 8 ): | ||
+ | for j in range( 8 ): | ||
+ | x = i*SIDE | ||
+ | y = j*SIDE | ||
+ | rect = Rectangle( Point( x, y ), Point( x+SIDE, y+SIDE ) ) | ||
+ | if (i+j)%2 == 0: | ||
+ | rect.setFill( color_rgb( 255, 255, 255 ) ) | ||
+ | else: | ||
+ | rect.setFill( color_rgb( 100, 100, 100 ) ) | ||
+ | rect.draw( win ) | ||
+ | |||
+ | def isBlack( i, j ): | ||
+ | if (i+j)%2 == 0: | ||
+ | return False | ||
+ | else: | ||
+ | return True | ||
+ | |||
+ | def displayCheckers( win ): | ||
+ | checkers = [] | ||
+ | for i in range( 8 ): | ||
+ | for j in range( 3 ): | ||
+ | if isBlack( i, j ): | ||
+ | piece = Piece( i, j, "white" ) | ||
+ | piece.draw( win ) | ||
+ | checkers.append( piece ) | ||
+ | |||
+ | for i in range( 8 ): | ||
+ | for j in range( 5, 8 ): | ||
+ | if isBlack( i, j ): | ||
+ | piece = Piece( i, j, "black" ) | ||
+ | piece.draw( win ) | ||
+ | checkers.append( piece ) | ||
+ | return checkers | ||
+ | |||
+ | |||
+ | def getCheckerPieceAt( i, j, checkers ): | ||
+ | for piece in checkers: | ||
+ | if piece.getI() == i and piece.getJ() == j: | ||
+ | return piece | ||
+ | |||
+ | return None | ||
+ | |||
+ | def main(): | ||
+ | # open the window | ||
+ | win = GraphWin( "Checkers", WIDTH, HEIGHT ) | ||
+ | |||
+ | # display 8x8 checkers board | ||
+ | displayBoard( win ) | ||
+ | checkers = displayCheckers( win ) | ||
+ | |||
+ | # ----------------------------------------------- | ||
+ | # Animation Loop | ||
+ | # ----------------------------------------------- | ||
+ | while len( checkers ) > 0: | ||
+ | # see if the user clicked the mouse | ||
+ | mouseClick = win.checkMouse() | ||
+ | |||
+ | # if not, then keep looping and do nothing | ||
+ | if mouseClick == None: | ||
+ | continue | ||
+ | |||
+ | # mouseClick is the point that was clicked. | ||
+ | # transform the x and y of the point into i and j | ||
+ | # identifying the squares of the checkerboard | ||
+ | i = mouseClick.getX() // SIDE | ||
+ | j = mouseClick.getY() // SIDE | ||
+ | print( "User clicked on cell", i, ", ", j ) | ||
+ | |||
+ | # check to see if a checkers piece was clicked | ||
+ | piece = getCheckerPieceAt( i, j, checkers ) | ||
+ | |||
+ | if piece != None: | ||
+ | # yes, a piece was clicked! Remove it. | ||
+ | print( "User clicked on a checkers piece", piece ) | ||
+ | piece.undraw() | ||
+ | checkers.remove( piece ) | ||
+ | |||
+ | |||
+ | win.close() | ||
+ | |||
+ | main() | ||
+ | |||
+ | </source> | ||
+ | <br /> | ||
+ | ==Move Checkers== | ||
+ | <br /> | ||
+ | Here the user moves the checkers, one by one, to any place on the board. | ||
+ | <br /> | ||
+ | <source lang="python"> | ||
+ | # checkers4.py | ||
+ | # D. Thiebaut | ||
+ | # Displays the images for the checkers. | ||
+ | # | ||
+ | from graphics import * | ||
+ | |||
+ | WIDTH = 680 | ||
+ | HEIGHT= 680 | ||
+ | SIDE = 680 // 8 | ||
+ | |||
+ | class CheckersPiece: | ||
+ | def __init__( self, col, ii, jj ): | ||
+ | self.color = col | ||
+ | self.i = ii | ||
+ | self.j = jj | ||
+ | |||
+ | if col=="white": | ||
+ | self.image = Image( Point( ii*SIDE + SIDE//2, | ||
+ | jj*SIDE + SIDE//2 ), "piece2.gif" ) | ||
+ | else: | ||
+ | self.image = Image( Point( ii*SIDE + SIDE//2, | ||
+ | jj*SIDE + SIDE//2 ), "piece.gif" ) | ||
+ | def getI( self ): | ||
+ | return self.i | ||
+ | |||
+ | def getJ( self ): | ||
+ | return self.j | ||
+ | |||
+ | def draw( self, win ): | ||
+ | self.image.draw( win ) | ||
+ | |||
+ | def undraw( self ): | ||
+ | self.image.undraw() | ||
+ | |||
+ | def moveToCell( self, ii, jj ): | ||
+ | self.image.move( (ii-self.i)*SIDE, (jj-self.j)*SIDE ) | ||
+ | |||
+ | def __str__( self ): | ||
+ | s = "Piece ({0:1},{1:1}) {2:1}".format( self.i, self.j, self.color) | ||
+ | return s | ||
+ | |||
+ | def isWhiteCell( i, j ): | ||
+ | """returns True if the cell identified by (i,j) is | ||
+ | a white cell on the board. White cells correspond to | ||
+ | i+j being an even number.""" | ||
+ | if (i+j) % 2 == 0: | ||
+ | return True | ||
+ | else: | ||
+ | return False | ||
+ | |||
+ | def displayBoard( win ): | ||
+ | """display board with alternating black and white cells""" | ||
+ | for i in range( 0, 8 ): | ||
+ | for j in range( 0, 8 ): | ||
+ | x = i * SIDE | ||
+ | y = j * SIDE | ||
+ | rect = Rectangle( Point( x, y ), Point( x+SIDE, y+SIDE ) ) | ||
+ | if isWhiteCell( i, j ): | ||
+ | rect.setFill( "white" ) | ||
+ | else: | ||
+ | rect.setFill( "grey" ) | ||
+ | rect.draw( win ) | ||
+ | #Text( Point( x+side//2, y+side//2 ), | ||
+ | # "{0:1} {1:1}".format( i, j ) ).draw(win) | ||
+ | |||
+ | |||
+ | def displayCheckers( win ): | ||
+ | """ display checkers on black cells only, top and bottom 3 rows""" | ||
+ | checkers = [] | ||
+ | for i in range( 8 ): | ||
+ | # top 3 rows | ||
+ | for j in range( 0, 3 ): | ||
+ | if isWhiteCell( i, j )==False: | ||
+ | piece = CheckersPiece( "white", i, j ) | ||
+ | piece.draw( win ) | ||
+ | checkers.append( piece ) | ||
+ | |||
+ | # bottom 3 rows | ||
+ | for j in range( 5, 8 ): | ||
+ | if isWhiteCell( i, j )==False: | ||
+ | piece = CheckersPiece( "black", i, j ) | ||
+ | piece.draw( win ) | ||
+ | checkers.append( piece ) | ||
+ | |||
+ | return checkers | ||
+ | |||
+ | def getCheckersAt( i, j, checkers ): | ||
+ | for piece in checkers: | ||
+ | if piece.getI()==i and piece.getJ()==j: | ||
+ | return piece | ||
+ | return None | ||
+ | |||
+ | def main(): | ||
+ | # open the window | ||
+ | win = GraphWin( "Checkers", WIDTH, HEIGHT ) | ||
+ | |||
+ | # display 8x8 checkers board | ||
+ | displayBoard( win ) | ||
+ | |||
+ | # display the checkers on top of the board. | ||
+ | # 3 rows of white checkers on black cells | ||
+ | # and 3 rows of black checkers on white cells | ||
+ | checkers = displayCheckers( win ) | ||
+ | |||
+ | # animation loop | ||
+ | clickedPiece = None | ||
+ | while True: | ||
+ | # check if use clicked on board | ||
+ | # if not, keep looping | ||
+ | p = win.checkMouse() | ||
+ | if p==None: | ||
+ | continue | ||
+ | |||
+ | i = p.getX()//SIDE | ||
+ | j = p.getY()//SIDE | ||
+ | print( "user clicked on Cell", i, ",", j ) | ||
+ | |||
+ | piece = getCheckersAt( i, j, checkers ) | ||
+ | # is it on a piece? | ||
+ | if piece != None: | ||
+ | # if so, remember that piece as the clicked-piece | ||
+ | print( "Clicked on", piece ) | ||
+ | clickedPiece = piece | ||
+ | print( "clickedPiece is now", clickedPiece ) | ||
+ | |||
+ | else: | ||
+ | # if not on a piece, then clicked an empty cell | ||
+ | # if the clicked-piece exists, | ||
+ | if clickedPiece != None: | ||
+ | # then move it to the empty cell | ||
+ | clickedPiece.moveToCell( i, j ) | ||
+ | print( "Moved piece", clickedPiece, "to", i,",", j ) | ||
+ | # un-remember the cliked-piece | ||
+ | clickedPiece = None | ||
+ | else: | ||
+ | # if the clicked-piece does not exist | ||
+ | # then do nothing | ||
+ | continue | ||
+ | |||
+ | |||
+ | win.getMouse() | ||
+ | win.close() | ||
+ | |||
+ | main() | ||
+ | |||
+ | </source> | ||
+ | <br /> | ||
+ | |||
=Aquarium= | =Aquarium= | ||
<br /> | <br /> | ||
Line 549: | Line 861: | ||
# aquarium.gif | # aquarium.gif | ||
# D. Thiebaut | # D. Thiebaut | ||
+ | # Displays 4 fish on the image, making them move randomly around the aquarium. | ||
+ | # | ||
from graphics import * | from graphics import * | ||
− | import random | + | import random # because the fish should move randomly, horizontally and vertically. |
WIDTH = 700 # geometry of tank2.gif | WIDTH = 700 # geometry of tank2.gif | ||
HEIGHT = 517 | HEIGHT = 517 | ||
− | + | class Fish: | |
+ | """A class for the fish. Build it so that it looks as much as possible the | ||
+ | other graphics objects in Zelle's library.""" | ||
+ | def __init__( self, fileNm, xx, yy ): | ||
+ | self.fileName = fileNm | ||
+ | self.x = xx | ||
+ | self.y = yy | ||
+ | self.image = Image( Point( xx, yy ), fileNm ) | ||
+ | |||
+ | def draw( self, win ): | ||
+ | """draws the image on the graphic window.""" | ||
+ | self.image.draw( win ) | ||
+ | |||
+ | def moveRandom( self ): | ||
+ | """move the fish to the left. | ||
+ | deltax = - random.randrange( 10 ) | ||
+ | deltay = random.randrange( -3, 3 ) | ||
+ | self.image.move( deltax, deltay ) | ||
+ | x = self.image.getAnchor().getX() | ||
+ | if x < -50: | ||
+ | self.image.move( WIDTH+100, 0 ) | ||
+ | |||
def main(): | def main(): | ||
Line 564: | Line 899: | ||
background = Image( Point( WIDTH//2, HEIGHT//2 ), "tank2.gif" ) | background = Image( Point( WIDTH//2, HEIGHT//2 ), "tank2.gif" ) | ||
background.draw( win ) | background.draw( win ) | ||
+ | |||
+ | fishList = [] | ||
+ | for i in range( 4 ): | ||
+ | fish = Fish( "fish0.gif", i*100, 350 ) | ||
+ | fish.draw( win ) | ||
+ | fishList.append( fish ) | ||
+ | |||
+ | # animation loop | ||
+ | while True: | ||
+ | |||
+ | # move all fish | ||
+ | for fish in fishList: | ||
+ | fish.moveRandom() | ||
+ | |||
+ | |||
win.getMouse() | win.getMouse() | ||
Line 569: | Line 919: | ||
main() | main() | ||
+ | |||
</source> | </source> |
Latest revision as of 11:30, 10 April 2015
--D. Thiebaut (talk) 05:48, 6 April 2015 (EDT)
Contents
Skeleton Program for Displaying an Image
The program below will work with this image, named "catGlasses.gif". It should be located in the same directory where the program is saved.
# imageProcessingSkel.py
# D. Thiebaut
# A skeleton program to start doing image processing
# in Python
from graphics import *
# image geometry
# 424x18
# make the window the same geometry
WIDTH = 424
HEIGHT = 418
IMAGEFILENAME = "catGlasses.gif"
#----------------------------------------------------------------
def waitForClick( win, message ):
""" waitForClick: stops the GUI and displays a message.
Returns when the user clicks the window. The message is erased."""
# wait for user to click mouse to start
startMsg = Text( Point( win.getWidth()/2, win.getHeight()-15 ), message )
startMsg.draw( win ) # display message
win.getMouse() # wait
startMsg.undraw() # erase
def main():
# open the window
win = GraphWin( "Image Editor", WIDTH, HEIGHT )
# open the cat image
cat = Image( Point(WIDTH//2, HEIGHT//2), IMAGEFILENAME )
cat.draw( win )
waitForClick( win, "click to close" )
win.close()
main()
Skeleton Program for Processing an Image
# pixelProcessingSkel.py
# D. Thiebaut
# Simple skeleton program for processing
# the pixels of an image
from graphics import *
# image geometry
# 424x18
# make the window the same geometry
WIDTH = 424
HEIGHT = 418
IMAGEFILENAME = "catGlasses.gif"
#----------------------------------------------------------------
def waitForClick( win, message ):
""" waitForClick: stops the GUI and displays a message.
Returns when the user clicks the window. The message is erased."""
# wait for user to click mouse to start
startMsg = Text( Point( win.getWidth()/2, win.getHeight()-15 ), message )
startMsg.draw( win ) # display message
win.getMouse() # wait
startMsg.undraw() # erase
def makeRed( win, img ):
""" set the red component of all the pixels to 255, the
maximum value.
"""
global WIDTH, HEIGHT
for x in range( WIDTH ):
for y in range( HEIGHT ):
red, green, blue = img.getPixel( x, y )
img.setPixel( x, y, color_rgb(255, green, blue ) )
def main():
win = GraphWin( "Image Editor", WIDTH, HEIGHT )
img = Image( Point(WIDTH//2, HEIGHT//2), IMAGEFILENAME )
img.draw( win )
makeRed( win, img )
waitForClick( win, "click to close" )
win.close()
main()
Image Processing: Program developed in class
# pixelProcessingSkel.py
# D. Thiebaut
# Simple skeleton program for processing
# the pixels of an image
# This is the code we developed in class
from graphics import *
# image geometry
# make the window the same geometry
WIDTH = 424 #243
HEIGHT = 418 #207
IMAGEFILENAME = "catGlasses.gif" #"catHat.gif"
# other image we can play with
#WIDTH = 243
#HEIGHT = 207
#IMAGEFILENAME = "catHat.gif"
def waitForClick( win, message ):
""" waitForClick: stops the GUI and displays a message.
Returns when the user clicks the window. The message is erased."""
# wait for user to click mouse to start
startMsg = Text( Point( win.getWidth()/2, win.getHeight()-15 ), message )
startMsg.draw( win ) # display message
win.getMouse() # wait
startMsg.undraw() # erase
def saturate( x ):
"""given a color amount, 0-255, returns 0 if the amount is closer to 0 than 255,
and returns 255 if not."""
if x < 255//2:
return 0
else:
return 255
def makeRed( win, img ):
""" set the red component of all the pixels to 255, the
maximum value.
"""
global WIDTH, HEIGHT
for y in range( HEIGHT ):
win.update()
for x in range( WIDTH ):
red, green, blue = img.getPixel( x, y )
green, blue, red = red, green, blue
red = saturate( red )
green = saturate( green )
blue = saturate( blue )
img.setPixel( x, y, color_rgb(red, green, blue ))
def makeBlackAndWhite( win, img ):
""" Make the image black and white, by making each pixel
grey. A grey pixel has the same amount of red, green, and blue.
"""
global WIDTH, HEIGHT
for y in range( HEIGHT ):
win.update()
for x in range( WIDTH ):
red, green, blue = img.getPixel( x, y )
# make the pixel grey, and use the average of the 3 values
# as the amount of grey.
avg = (green+blue+red)//3
img.setPixel( x, y, color_rgb(avg, avg, avg ) )
def addBorder( win, img ):
"""add a red border at the top of the image"
for y in range( 0, 15 ):
for x in range( WIDTH ):
img.setPixel( x, y, color_rgb( 255, 0, 0 ) )
def main():
win = GraphWin( "Dominique Thiebaut", WIDTH, HEIGHT )
img = Image( Point(WIDTH//2, HEIGHT//2), IMAGEFILENAME )
img.draw( win )
makeRed( win, img )
addBorder( win, img )
waitForClick( win, "click to close" )
win.close()
main()
Playing Checkers
ChangeColorPiece.py
# changeColorPiece.py
# D. Thiebaut
# Create new checkers image with different color.
# based on piece.gif. New image saved in piece2.gif
#
from graphics import *
WIDTH = 80 # dimension of checkers piece
HEIGHT= 80
def main():
# open the window
win = GraphWin( "Checkers", WIDTH, HEIGHT )
# open image of black piece
piece = Image( Point( WIDTH//2, HEIGHT//2 ),
"piece.gif" )
piece.draw( win )
# change color of all the dark pixels
for x in range( WIDTH ):
for y in range( HEIGHT ):
r, g, b = piece.getPixel( x, y )
# don't change the color of the mostly white pixels
if r>255-10 and g>255-10 and b>255-10:
continue
# create a new color based on the r,g,b of the original pixel
newColor = color_rgb( r + (255-r)//2, g, b+(255-b)//2 )
piece.setPixel( x, y, newColor )
# save modified image into new file
piece.save( "piece2.gif" )
# close window
win.close()
main()
Checkers0.py
This program is the bare skeleton for display the board. You have to add the code inside the displayBoard() function.
# checkers0.py
# D. Thiebaut
# A first program to display an 8x8 chessboard
# in a graphic window.
#
from graphics import *
WIDTH = 600 # width of the window
HEIGHT= 600 # height of the window
SIDE = 600//8 # the side of a cell of the 8x8 board
def displayBoard( win ):
"""displays an 8x8 board in the graphic window. The board extends to the sides of the window'''
# add your code here...
return
def waitForClick( win, message ):
""" waitForClick: stops the GUI and displays a message.
Returns when the user clicks the window. The message is erased."""
# wait for user to click mouse to start
startMsg = Text( Point( win.getWidth()/2, win.getHeight()-15 ), message )
startMsg.draw( win ) # display message
win.getMouse() # wait
startMsg.undraw() # erase
def main():
# open the window
win = GraphWin( "Checkers", WIDTH, HEIGHT )
# display 8x8 checkers board
displayBoard( win )
# wait for user to click before closing everything...
waitForClick( win, "click to close" )
win.close()
main()
Display Checkers
This is a cleaned up version of the program we created in class on 4/08/15. It only displays the checkers pieces on black squares only, white pieces on the top 3 rows, black pieces on the bottom 3 rows.
# checkers4.py
# D. Thiebaut
# Displays the images for the checkers.
#
from graphics import *
WIDTH = 680
HEIGHT= 680
SIDE = 680 // 8
class CheckersPiece:
def __init__( self, col, ii, jj ):
self.color = col
self.i = ii
self.j = jj
if col=="white":
self.image = Image( Point( ii*SIDE + SIDE//2,
jj*SIDE + SIDE//2 ), "piece2.gif" )
else:
self.image = Image( Point( ii*SIDE + SIDE//2,
jj*SIDE + SIDE//2 ), "piece.gif" )
def draw( self, win ):
self.image.draw( win )
def undraw( self ):
self.image.undraw()
def isWhiteCell( i, j ):
"""returns True if the cell identified by (i,j) is
a white cell on the board. White cells correspond to
i+j being an even number."""
if (i+j) % 2 == 0:
return True
else:
return False
def displayBoard( win ):
"""display board with alternating black and white cells"""
for i in range( 0, 8 ):
for j in range( 0, 8 ):
x = i * SIDE
y = j * SIDE
rect = Rectangle( Point( x, y ), Point( x+SIDE, y+SIDE ) )
if isWhiteCell( i, j ):
rect.setFill( "white" )
else:
rect.setFill( "grey" )
rect.draw( win )
#Text( Point( x+side//2, y+side//2 ),
# "{0:1} {1:1}".format( i, j ) ).draw(win)
def displayCheckers( win ):
""" display checkers on black cells only, top and bottom 3 rows"""
checkers = []
for i in range( 8 ):
# top 3 rows
for j in range( 0, 3 ):
if isWhiteCell( i, j )==False:
piece = CheckersPiece( "white", i, j )
piece.draw( win )
checkers.append( piece )
# bottom 3 rows
for j in range( 5, 8 ):
if isWhiteCell( i, j )==False:
piece = CheckersPiece( "black", i, j )
piece.draw( win )
checkers.append( piece )
return checkers
def main():
# open the window
win = GraphWin( "Checkers", WIDTH, HEIGHT )
# display 8x8 checkers board
displayBoard( win )
# display the checkers on top of the board.
# 3 rows of white checkers on black cells
# and 3 rows of black checkers on white cells
checkers = displayCheckers( win )
win.getMouse()
win.close()
main()
Remove Checkers, One by One
# checkers00.py
# D. Thiebaut
# Displays checker board. Then displays 3 rows of white
# and black checkers pieces.
# Allows the user to remove checkers, one by one, by
# clicking on them.
#
from graphics import *
WIDTH = 680 # width of the window
HEIGHT= 680 # height of the window
SIDE = 680//8 # the side of a cell of the 8x8 board
class Piece:
def __init__( self, ii, jj, col ):
self.i = ii
self.j = jj
self.color = col
x = ii * SIDE + SIDE//2
y = jj * SIDE + SIDE//2
"""
self.circ1 = Circle( Point( x, y ), SIDE//2 )
if col=="white":
self.circ1.setFill( color_rgb( 250, 250, 250 ) )
else:
self.circ1.setFill( color_rgb( 10, 10, 10 ) )
self.circ2 = Circle( Point( x, y ), SIDE//2 - 5 )
if col=="white":
self.circ2.setFill( color_rgb( 230, 230, 230 ) )
else:
self.circ2.setFill( color_rgb( 50, 50, 50 ) )
"""
if col=="white":
self.image = Image( Point( x, y ), "piece2.gif" )
else:
self.image = Image( Point( x, y ), "piece.gif" )
def __str__( self ):
return "Piece: ({0:1},{1:1}) {2:1}".format( self.i, self.j, self.color )
def draw( self, win ):
"""
self.circ1.draw( win )
self.circ2.draw( win )
"""
self.image.draw( win )
def undraw( self ):
self.image.undraw()
def getI( self ):
return self.i
def getJ( self ):
return self.j
def moveToSquare( self, i, j, win ):
destX = i * SIDE + SIDE//2
destY = j * SIDE + SIDE//2
currentX = self.i * SIDE + SIDE//2
currentY = self.j * SIDE + SIDE//2
deltaX = destX - currentX
deltaY = destY - currentY
self.image.undraw()
self.image._move( deltaX, deltaY )
self.image.draw( win )
self.i = i
self.j = j
def displayBoard( win ):
"""display an 8x8 board"""
for i in range( 8 ):
for j in range( 8 ):
x = i*SIDE
y = j*SIDE
rect = Rectangle( Point( x, y ), Point( x+SIDE, y+SIDE ) )
if (i+j)%2 == 0:
rect.setFill( color_rgb( 255, 255, 255 ) )
else:
rect.setFill( color_rgb( 100, 100, 100 ) )
rect.draw( win )
def isBlack( i, j ):
if (i+j)%2 == 0:
return False
else:
return True
def displayCheckers( win ):
checkers = []
for i in range( 8 ):
for j in range( 3 ):
if isBlack( i, j ):
piece = Piece( i, j, "white" )
piece.draw( win )
checkers.append( piece )
for i in range( 8 ):
for j in range( 5, 8 ):
if isBlack( i, j ):
piece = Piece( i, j, "black" )
piece.draw( win )
checkers.append( piece )
return checkers
def getCheckerPieceAt( i, j, checkers ):
for piece in checkers:
if piece.getI() == i and piece.getJ() == j:
return piece
return None
def main():
# open the window
win = GraphWin( "Checkers", WIDTH, HEIGHT )
# display 8x8 checkers board
displayBoard( win )
checkers = displayCheckers( win )
# -----------------------------------------------
# Animation Loop
# -----------------------------------------------
while len( checkers ) > 0:
# see if the user clicked the mouse
mouseClick = win.checkMouse()
# if not, then keep looping and do nothing
if mouseClick == None:
continue
# mouseClick is the point that was clicked.
# transform the x and y of the point into i and j
# identifying the squares of the checkerboard
i = mouseClick.getX() // SIDE
j = mouseClick.getY() // SIDE
print( "User clicked on cell", i, ", ", j )
# check to see if a checkers piece was clicked
piece = getCheckerPieceAt( i, j, checkers )
if piece != None:
# yes, a piece was clicked! Remove it.
print( "User clicked on a checkers piece", piece )
piece.undraw()
checkers.remove( piece )
win.close()
main()
Move Checkers
Here the user moves the checkers, one by one, to any place on the board.
# checkers4.py
# D. Thiebaut
# Displays the images for the checkers.
#
from graphics import *
WIDTH = 680
HEIGHT= 680
SIDE = 680 // 8
class CheckersPiece:
def __init__( self, col, ii, jj ):
self.color = col
self.i = ii
self.j = jj
if col=="white":
self.image = Image( Point( ii*SIDE + SIDE//2,
jj*SIDE + SIDE//2 ), "piece2.gif" )
else:
self.image = Image( Point( ii*SIDE + SIDE//2,
jj*SIDE + SIDE//2 ), "piece.gif" )
def getI( self ):
return self.i
def getJ( self ):
return self.j
def draw( self, win ):
self.image.draw( win )
def undraw( self ):
self.image.undraw()
def moveToCell( self, ii, jj ):
self.image.move( (ii-self.i)*SIDE, (jj-self.j)*SIDE )
def __str__( self ):
s = "Piece ({0:1},{1:1}) {2:1}".format( self.i, self.j, self.color)
return s
def isWhiteCell( i, j ):
"""returns True if the cell identified by (i,j) is
a white cell on the board. White cells correspond to
i+j being an even number."""
if (i+j) % 2 == 0:
return True
else:
return False
def displayBoard( win ):
"""display board with alternating black and white cells"""
for i in range( 0, 8 ):
for j in range( 0, 8 ):
x = i * SIDE
y = j * SIDE
rect = Rectangle( Point( x, y ), Point( x+SIDE, y+SIDE ) )
if isWhiteCell( i, j ):
rect.setFill( "white" )
else:
rect.setFill( "grey" )
rect.draw( win )
#Text( Point( x+side//2, y+side//2 ),
# "{0:1} {1:1}".format( i, j ) ).draw(win)
def displayCheckers( win ):
""" display checkers on black cells only, top and bottom 3 rows"""
checkers = []
for i in range( 8 ):
# top 3 rows
for j in range( 0, 3 ):
if isWhiteCell( i, j )==False:
piece = CheckersPiece( "white", i, j )
piece.draw( win )
checkers.append( piece )
# bottom 3 rows
for j in range( 5, 8 ):
if isWhiteCell( i, j )==False:
piece = CheckersPiece( "black", i, j )
piece.draw( win )
checkers.append( piece )
return checkers
def getCheckersAt( i, j, checkers ):
for piece in checkers:
if piece.getI()==i and piece.getJ()==j:
return piece
return None
def main():
# open the window
win = GraphWin( "Checkers", WIDTH, HEIGHT )
# display 8x8 checkers board
displayBoard( win )
# display the checkers on top of the board.
# 3 rows of white checkers on black cells
# and 3 rows of black checkers on white cells
checkers = displayCheckers( win )
# animation loop
clickedPiece = None
while True:
# check if use clicked on board
# if not, keep looping
p = win.checkMouse()
if p==None:
continue
i = p.getX()//SIDE
j = p.getY()//SIDE
print( "user clicked on Cell", i, ",", j )
piece = getCheckersAt( i, j, checkers )
# is it on a piece?
if piece != None:
# if so, remember that piece as the clicked-piece
print( "Clicked on", piece )
clickedPiece = piece
print( "clickedPiece is now", clickedPiece )
else:
# if not on a piece, then clicked an empty cell
# if the clicked-piece exists,
if clickedPiece != None:
# then move it to the empty cell
clickedPiece.moveToCell( i, j )
print( "Moved piece", clickedPiece, "to", i,",", j )
# un-remember the cliked-piece
clickedPiece = None
else:
# if the clicked-piece does not exist
# then do nothing
continue
win.getMouse()
win.close()
main()
Aquarium
# aquarium.gif
# D. Thiebaut
# Displays 4 fish on the image, making them move randomly around the aquarium.
#
from graphics import *
import random # because the fish should move randomly, horizontally and vertically.
WIDTH = 700 # geometry of tank2.gif
HEIGHT = 517
class Fish:
"""A class for the fish. Build it so that it looks as much as possible the
other graphics objects in Zelle's library."""
def __init__( self, fileNm, xx, yy ):
self.fileName = fileNm
self.x = xx
self.y = yy
self.image = Image( Point( xx, yy ), fileNm )
def draw( self, win ):
"""draws the image on the graphic window."""
self.image.draw( win )
def moveRandom( self ):
"""move the fish to the left.
deltax = - random.randrange( 10 )
deltay = random.randrange( -3, 3 )
self.image.move( deltax, deltay )
x = self.image.getAnchor().getX()
if x < -50:
self.image.move( WIDTH+100, 0 )
def main():
# open the window
win = GraphWin( "CSC Aquarium", WIDTH, HEIGHT )
# display background
background = Image( Point( WIDTH//2, HEIGHT//2 ), "tank2.gif" )
background.draw( win )
fishList = []
for i in range( 4 ):
fish = Fish( "fish0.gif", i*100, 350 )
fish.draw( win )
fishList.append( fish )
# animation loop
while True:
# move all fish
for fish in fishList:
fish.moveRandom()
win.getMouse()
win.close()
main()