Difference between revisions of "CSC111 Programs Created in Class 2018"

From dftwiki3
Jump to: navigation, search
(rainiest.py skeleton)
(checkers4MoveRemoveWithButton.py)
Line 3,185: Line 3,185:
 
</source>
 
</source>
 
<br />
 
<br />
 +
<br />
 +
==checkersInteractive1.py==
 +
<br />
 +
In this version we can move the piece by click on them, then clicking on an empty square.
 +
<br />
 +
::<source lang="python">
 +
# checkers00.py
 +
# D. Thiebaut
 +
# A first program to display an 8x8 chessboard
 +
# in a graphic window.
 +
#
 +
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 ):
 +
        '''moves the checker piece from where it is,
 +
        to the new position at i,j'''
 +
        # convert i, j to an x, y coordinate
 +
        destX = i * SIDE + SIDE//2
 +
        destY = j * SIDE + SIDE//2
 +
        # convert current i, j position to x,y coordinate
 +
        currentX = self.i * SIDE + SIDE//2
 +
        currentY = self.j * SIDE + SIDE//2
 +
        # compute delta between where we are (currentX,currentY) to
 +
        # where we want to be (destX,destY)
 +
        deltaX = destX - currentX
 +
        deltaY = destY - currentY
 +
        # move the image by deltaX, deltaY
 +
        self.image.move( deltaX, deltaY )
 +
        # update our current i,j position
 +
        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 waitForClick( win, message ):
 +
    """ waitForClick: stops the GUI and displays a message. 
 +
    Returns when the user clicks the window. The message is erased."""
 +
    startMsg = Text( Point( win.getWidth()/2, win.getHeight()-15 ),
 +
                    message )
 +
    startMsg.draw( win )    # display message
 +
    win.getMouse()          # wait
 +
    startMsg.undraw()      # erase
 +
 +
def checkIfCheckerPieceAt( i, j, checkers ):
 +
    '''goes through the list of checkers, and if one is
 +
    found at location i, j, then return that piece.  Otherwise
 +
    return None.'''
 +
    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
 +
    # -----------------------------------------------
 +
    clickedPiece = None
 +
    while True:           
 +
        # 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
 +
 +
        # check to see if a checkers piece was clicked
 +
        piece = checkIfCheckerPieceAt( i, j, checkers )
 +
       
 +
        if piece != None:
 +
            # yes, a piece was clicked!  Remember which one it is
 +
            clickedPiece = piece
 +
            print( "User clicked on", clickedPiece )
 +
            continue
 +
        else:
 +
            # no, no piece clicked.  So user clicked an empty
 +
            # square.  If she had clicked a piece before, then
 +
            # move that piece.  Otherwise, just don't do anything
 +
            print( "User clicked on a square at (",i,", ", j,")" )
 +
            if clickedPiece != None:
 +
                print( "Moving piece", clickedPiece, "to(",i,", ", j,")" )
 +
                clickedPiece.moveToSquare( i, j, win )
 +
                clickedPiece = None
 +
       
 +
    # wait for user to click before closing everything...
 +
    waitForClick( win, "click to close" )
 +
 +
    win.close()
 +
 +
main()
 +
 +
</source>
 
<br />
 
<br />
 
==checkers4MoveRemoveWithButton.py==
 
==checkers4MoveRemoveWithButton.py==
Line 3,400: Line 3,586:
 
</source>
 
</source>
 
<br />
 
<br />
 +
 
==rainiest.py skeleton==
 
==rainiest.py skeleton==
 
<br />
 
<br />

Revision as of 10:04, 13 April 2018

D. Thiebaut (talk) 12:30, 31 January 2018 (EST)


1/30/18

# wedWeek1.py
# D. Thiebaut
# Demo program week 1


# variables
age = 20
year = 2018

# compute year born
print( year - age )


# example of for loop
for name in [ "smith", 23, 3.14159, "hello" ]:
    print( name )

"""
challenge: print the following lines
***
Mae
*****
Alice
*******
Felicia
"""

for name in [ "Mae", "Alice", "Felicia" ]:
    print( '*' * len( name ) )
    print( name )


"""
new challenge: print the following lines
*
Mae
********
Alice
****
Felicia
**
"""

for name in [ "*", "Mae", "********", "Alice", "****", "Felicia", "**" ]:
    print( name )

02/05/18


Table of Fahrenheit to Celsius conversion

# 020518.py
# D. Thiebaut
#
# print table of temperatures
# start at 100 F down to -30 F
# in steps of 10
# using the formula: Celsius = (Farhenheit - 32 ) * 5 / 9

# print the header 
print( "Fahrenheit --> Celsius" )

# display the table of temperatures
# ranging from 100 down to -30F.
for fTemp in range( 100, -31, -10 ):
    cTemp = ( fTemp - 32 ) * 5 / 9
    print( fTemp, '-->', cTemp )

Problem: get user name and grade and display user information and grade as a bar graph.

# barGraph.py
# D. Thiebaut
# this program prompts the user for her information
# and grade and displays a bar-graph.
#
#First name?  Dominique
#Last name?   Thiebaut
#Id?          990123456
#Final grade? 90
#
#+———————————————————————————————————-———————————-+
#|Dominique Thiebaut                    990123456 |
#+———————————————————————————————————-———————————-+
#      00...10...20...30...40...50...60...70...80...90...100
#grade: #############################################
#class: ########################################
#
#

# input section
fName = input( "First name?  " )
lName = input( "Last name?   " )
Id    = input( "Id?          " )
final = input( "Final grade? " )

# output section
print( fName, lName, Id )
bar = "+———————————————————————————————————-———————————-+"
barLen = len( bar )
print( "barLen =", barLen )
nameIdLen = len( fName )+1+len( lName ) + len( Id )+1
print( "nameIdLen =", nameIdLen )

print( bar )
print( "|", fName, lName, ' '*(barLen-nameIdLen), Id, '|' )
print( bar )

2/7/18


We didn't have time to cover this problem, because of the snow storm... But it simply displays an 8 by 8 chessboard using hash tags.

# chessBoard.py
# D. Thiebaut
# displays an 8x8 chessboard, as shown below.
"""
###   ###   ###   ###   
###   ###   ###   ###   
###   ###   ###   ###   
   ###   ###   ###   ###
   ###   ###   ###   ###
   ###   ###   ###   ###
###   ###   ###   ###   
###   ###   ###   ###   
###   ###   ###   ###   
   ###   ###   ###   ###
   ###   ###   ###   ###
   ###   ###   ###   ###
###   ###   ###   ###   
###   ###   ###   ###   
###   ###   ###   ###   
   ###   ###   ###   ###
   ###   ###   ###   ###
   ###   ###   ###   ###
###   ###   ###   ###   
###   ###   ###   ###   
###   ###   ###   ###   
   ###   ###   ###   ###
   ###   ###   ###   ###
   ###   ###   ###   ###
"""
numRows = eval( input( "Number of rows?    " ) )
numCols = eval( input( "Number of columns? " ) )
white="   "
black="###"

bar1 = ""
bar2 = ""
for i in range( numCols//2 ):
    bar1 = bar1 + white + black
    bar2 = bar2 + black + white

for i in range( numRows//2 ):
    # display 2 lines of squares
    # alternating the colors
    # 5    ###   ###   ###   ###
    #     ###   ###   ###   ###
    #     ###   ###   ###   ###
    #  ###   ###   ###   ###   
    #  ###   ###   ###   ###   
    #  ###   ###   ###   ###   
    for n in range( 3 ):
        print( bar1 )
    for n in range( 3 ):
        print( bar2 )


2/9/18


# barGraph.py
# D. Thiebaut
# this program prompts the user for her information
# and grade and displays a bar-graph.
#
#First name?  Dominique
#Last name?   Thiebaut
#Id?          990123456
#Final grade? 90
#
#+———————————————————————————————————-———————————-+
#|Dominique Thiebaut                    990123456 |
#+———————————————————————————————————-———————————-+
#      00...10...20...30...40...50...60...70...80...90...100
#grade: #############################################
#class: ########################################
#
#

# box geometry
bar = "+———————————————————————————————————-———————————-+"
barLen = len( bar )

# input section
fName      = input( "First name? " )
fNameLen   = len( fName )
lName      = input( "Last name?  " )
lNameLen   = len( lName )
Id         = input( "Id?         " )
IdLen      = len( Id )
numSpaces  = barLen -3 -(fNameLen+1+lNameLen+IdLen)
grade      = eval( input( "Final grade? " ) )
classGrade = 80

# output section
print( bar )
print( '|' + fName, ' ', lName, ' '*(numSpaces), Id, ' |', sep='' )
print( bar )

# print the scale
print( "      00...10...20...30...40...50...60...70...80...90...100" )

# print the student grade as a bar
numHashTags = grade // 2
print( "grade:", '#' * numHashTags )

#print the class grade as a bar
numHashTags = classGrade // 2
print( "class:", '#' * numHashTags )


2/12/18


# teller.py
# D. Thiebaut
# simulates teller machine program
# prompts user, displays number of bills

# input amount to withdraw (use eval)
amount = eval( input( "Amount to withdraw? " ) )
amount = abs( amount )
print( "Amount:", amount )


# compute number of bills, 20, 10, 5, 1
no20s  = amount // 20
amount = amount % 20  # leftover after giving out all the 20s 

no10s  = amount // 10 
amount = amount % 10 # leftover after giving out all the 10s 

no5s   = amount // 5
amount = amount % 5 # leftover after giving out all the 5s 

no1s   = amount


# display number of bills
print( no20s, "$20-bill(s)" )
print( no10s, "$10-bill(s)" )
print( no5s, "$5-bill(s)" )
print( no1s, "$1-bill(s)" )


2/14/18


# generate a table of the powers of 2
"""
    0    1
    1    2
    2    4
    3    8
    4   16
    5   32
    6   64
    7  128
    8  256
    9  512
1234567890123
"""
for i in range( 10 ):
    print( "{0:5}{1:5}".format( i, 2**i ) )


# display the following table:
# 1: len(Doc    )= 3
# 2: len(Grumpy )= 6
# 3: len(Happy  )= 5
# 4: len(Sleepy )= 6
# 5: len(Dopey  )= 5
# 6: len(Bashful)= 7
# 7: len(Sneezy )= 6

count = 1
for name in ["Doc", "Grumpy", "Happy", 
                    "Sleepy", "Dopey", "Bashful",
                    "Sneezy" ]:
    print( "{0:1}: len({1:<7})= {2:1}"
            .format( count, name, len(name) ) )
    count = count + 1


2/16/18


# accumulate.py
# D. Thiebaut
# solution programs for 2/16/18

# --------------------------------------
# sum of all the numbers from 1 to 100
total = 0
#print( "initial total:", total )
for i in range( 0, 100+1, 5):
    #print( i, total )
    total = total + i
    #print( "after sum:", i, total )
    #print()

print( total )

# --------------------------------------
# average of [100, 95,100, 90, 60, 85]
total = 0
count = 0
for i in [100, 95,100, 90, 60, 85]:
    total = total + i
    print( "i =", i )
    count = count + 1
    print( "count = ", count )
    
print( "total = ", total, "count = ", count )
print( "average = ", total/count )


# --------------------------------------
a = "#"
b = "+"
final = ""
# from numbers to string
print( "before loop: a=", a, "b=", b )
for i in   [1,2,1,1,3,4]:
    #print( i * a, end="", sep="" )
    print( "i=", i, "a=", a, "b=", b )
    final = final + i*a
    print( "final =", final )
    a, b = b, a

print( "final string = ", final )


2/19/18


Different ways to print all the strings in a list.

def main():
    farm = ["pig", "dog", "horse", "hen" ]

    #--------------------------------------------------
    print( "method 1" )
    print( """pig
dog
horse
hen""" )

    #--------------------------------------------------
    print( "method 2" )
    print( farm )
    
    #--------------------------------------------------
    print( "method 3" )
    print( "pig\ndog\nhorse\nhen" )
    
    #--------------------------------------------------
    print( "method 4" )
    print( list( farm ) )

    #--------------------------------------------------
    print( "method 5" )
    print( farm[0], farm[1], farm[2], farm[3] )
    
    #--------------------------------------------------
    print( "method 6" )
    print( farm[0], farm[1], farm[2], farm[3], sep="\n" )
    
    #--------------------------------------------------
    print( "method 7" )
    for n in [0,1,2,3]:
       print( farm[n] )

    #--------------------------------------------------
    print( "method 8" )
    for animal in farm:
            print( animal )

    #--------------------------------------------------
    print( "method 9" )
    for animal in farm:
        for c in range( len( animal ) ):
            print( animal[c], sep="", end="")
        print(" " )
        
    #--------------------------------------------------
    print( "method 10" )
    for i in range( len( farm ) ):
        print( farm[i] )

    #--------------------------------------------------
    print( "method 11" )
    for i in range( -1, -len(farm), -1 ):
            print( farm[ i ] )

    #--------------------------------------------------
    print( "method 12" )
    for i in range( -1, -len(farm)-1, -1 ):
            print( farm[ i ] )

    #--------------------------------------------------
    print( "method 13" )
    for i in range( -len(farm), 0, 1 ):
            print(farm[i] )

main()


02/21/18


>>> name = "H:/Documents/solutionsHw4.doc"

>>> name
'H:/Documents/solutionsHw4.doc'
>>> drive = name[0:2]
>>> drive
'H:'
>>> name
'H:/Documents/solutionsHw4.doc'
>>> ext = name[-3: ]
>>> ext
'doc'
>>> newName = name[0:-3]
>>> newName
'H:/Documents/solutionsHw4.'
>>> newName = name[0:-3] + "txt"
>>> newName
'H:/Documents/solutionsHw4.txt'
>>> fname = "Alex"
>>> lname = "Booth"
>>> account = fname[0:1] + lname
>>> account
'ABooth'
>>> account = fname[0] + lname
>>> account
'ABooth'


>>> date = "02212018"
>>> wanted = "21 Feb 2018"
>>> date
'02212018'
>>> wanted
'21 Feb 2018'
>>> months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun"
	   ,"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]
>>> months
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
>>> months[1]
'Feb'
>>> months[2]
'Mar'
>>> months = ["Dummy", 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
>>> months[2]
'Feb'
>>> day = date[2:4]
>>> day
'21'
>>> month = date[0:2]
>>> month
'02'
>>> int( month )
2
>>> months[ int( month ) ]
'Feb'
>>> date
'02212018'
>>> year = date[4: ]
>>> year
'2018'
>>> print( day, months[ int( month ) ], year )
21 Feb 2018
>>> date
'02212018'
>>> day
'21'
>>> month
'02'
>>> year
'2018'
>>> months
['Dummy', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
>>> months[ int( month ) ]
'Feb'


>>> fname = "Maria"
>>> lname = "Luce"
>>> name = fname + lname
>>> name
'MariaLuce'
>>> for i in range( len( name ) ):
	print( i )

	
0
1
2
3
4
5
6
7
8
>>> for i in range( len( name ) ):
	print( i, name[0:i] )

	
0 
1 M
2 Ma
3 Mar
4 Mari
5 Maria
6 MariaL
7 MariaLu
8 MariaLuc

>>> for i in range( len(name ) ):
	print( i, name[0:i+1] )

	
0 M
1 Ma
2 Mar
3 Mari
4 Maria
5 MariaL
6 MariaLu
7 MariaLuc
8 MariaLuce
>>> for i in range( len( name ) ):
	print( name[0:i+1] )

	
M
Ma
Mar
Mari
Maria
MariaL
MariaLu
MariaLuc
MariaLuce


>>> farm = [ "pig", "dog", "cat" ]
>>> farm
['pig', 'dog', 'cat']
>>> farm[0]
'pig'
>>> farm[1]
'dog'
>>> farm[-1]
'cat'
>>> 
>>> 
>>> farm[ 0 ] = "horse"
>>> farm
['horse', 'dog', 'cat']
>>> farm[2] = "mouse"
>>> farm
['horse', 'dog', 'mouse']
>>> farm[-1] = "cat"
>>> farm
['horse', 'dog', 'cat']
>>> name = "Smith College"
>>> 
>>> 
>>> 
>>> 
>>> name[0]
'S'
>>> name[-1]
'e'
>>> name[2]
'i'
>>> name[0] = 'Z'
Traceback (most recent call last):
  File "<pyshell#94>", line 1, in <module>
    name[0] = 'Z'
TypeError: 'str' object does not support item assignment   <--- strings are immutable!
>>> farm2 = ( "cat", "dog", "mouse" )
>>> farm2[1]
'dog'
>>> farm2[1] = "horse"
Traceback (most recent call last):
  File "<pyshell#97>", line 1, in <module>
    farm2[1] = "horse"
TypeError: 'tuple' object does not support item assignment
>>> animal = "horse"
>>> animal[0] = 'H'
Traceback (most recent call last):
  File "<pyshell#99>", line 1, in <module>
    animal[0] = 'H'
TypeError: 'str' object does not support item assignment
>>> animal = 'H' + animal[1: ]
>>> animal
'Horse'



>>> greeting = "hello there"
>>> greeting.upper()
'HELLO THERE'
>>> greeting
'hello there'
>>> greeting = greeting.upper()
>>> greeting
'HELLO THERE'
>>> lname = "Max"
>>> fname = "Joe"
>>> fname[0] + lname
'JMax'
>>> account = fname[0] + lname
>>> account
'JMax'
>>> account = account.lower()
>>> account
'jmax'
>>> title = "CSC111 Intro to CS"
>>> title.center( 60 )
'                     CSC111 Intro to CS                     '
>>> title
'CSC111 Intro to CS'
>>> print( title.center( 60 ) )
                     CSC111 Intro to CS                     
>>> name = "alex booth"
>>> name.capitalize()
'Alex booth'
>>> name
'alex booth'
>>> name.title()
'Alex Booth'
>>> name = "MICKEY MOUSE"
>>> name.capitalize()
'Mickey mouse'
>>> name.title()
'Mickey Mouse'
>>> name
'MICKEY MOUSE'
>>> name = name.title()
>>> name
'Mickey Mouse'
>>> name.find( 'z' )
-1
>>> name.find( 'o' )
8
>>> name.find( 'M' )
0
>>> name.find( 'c' )
2
>>> name.find( "ou" )
8
>>> name
'Mickey Mouse'
>>> name.replace( "Mickey", "Minnie" )
'Minnie Mouse'
>>> name
'Mickey Mouse'
>>> name.replace( "Mouse", "Cat" )
'Mickey Cat'
>>> name
'Mickey Mouse'
>>> name.replace( 'M', 'Z' )
'Zickey Zouse'
>>> name
'Mickey Mouse'
>>>


2/23/18


# examples
# D. Thiebaut

line = "The quick red fox jumped over the lazy brown sleeping dog"
line.split( " " )   # that's a space



poem = """Chocolate
Chocolate is the first luxury.
It has so many things wrapped up in it:
Deliciousness in the moment,
childhood memories,
and that grin-inducing
feeling of getting a reward for being good.
--Mariska Hargitay"""

Working with Text Files


Here's the text to store in the text file called chocolate.txt. You can use Notepad or TextEdit to do that. Make sure you use ".txt" as the extension, and select "plain text" or "plain ASCII" as the format.

Strength is the capacity to break

a Hershey bar into four pieces

with your bare hands - and then

eat just one of the pieces.

-Judith Viorst


And here's the program that reads this file

# readChocolateFile.py
# D. Thiebaut
# Opens a text file and displays it contents.
# Note: you need to have a file called chocolate.txt
# in the same directory/folder where you have saved
# this program!!!
@

def main():
    # open file
    file = open( "chocolate.txt", "r" )

    # read each line from file and display it
    for line in file:
        print( line )

    # close the file
    file.close()

main()

2/26/18


# readChocolateFile.py
# D. Thiebaut
# Opens a text file and displays it contents.
# Note: you need to have a file called chocolate.txt
# in the same directory/folder where you have saved
# this program!!!


def main():
    # open file
    file = open( "chocolate.txt", "r" )

    # read each line from file and display it
    for line in file:
        print( line.strip() )

    # close the file
    file.close()

main()

# ----------------------------------------------------------------------


def singHappyBirthday( minion ):
    print( "Happy birthday to you" )
    print( "Happy birthday to you" )
    print( "Happy birthday, dear", minion )
    print( "Happy birthday to you" )
    print( )
    
def main():
    for minion in [ "Dave", "Stuart", "Jerry", "Jorge" ]:
        singHappyBirthday( minion )

main()

# ----------------------------------------------------------------------

# DaveEats.py
# D. Thiebaut


def DaveEats( fruit ):
    print( "Dave opens their mouth" )
    print( "and eats the", fruit )
    print()



def main():
    for fruit in [ "banana", "apple", "orange" ]:
        DaveEats( fruit )
        
    
main()

# ----------------------------------------------------------------------

# printBarSayHello.py
# D. Thiebaut


def printBar():
    print( 60 * '-' )


def sayHello():
    print( )
    print( "Hello, and welcome!" )
    print( )

def main():
    printBar()
    printBar()

main()
 

# ----------------------------------------------------------------------

3/2/2018


functionBootCamp2


# functionBootCamp2.py
# D. Thiebaut

def cutDNA( DNA, marker ):
    DNA = DNA.upper()
    marker = marker.upper()
      
    index = DNA.find( marker )
    index2 = index + len( marker )
    leftOver = DNA[ index2: ]
    return leftOver

def main():
    dna = "ACGTTTA"
    marker = "G"

    print( cutDNA( dna, marker ) )

    print( cutDNA( "AAAAATTTT", "at" ) )

main()


bootCamp3.py



Program developed in Class


The assignment is to write a program that gets lines from a text file, representing a memo, and words from another text file, representing words to censure out of the memo. The program then takes both list of strings and blocks out all the bad words from the memo.

def block( bad, line ):
    """ takes a line and a bad word and replaces
    the bad word with xs"""
    xbad = "x" * len( bad )
    line = line.replace( bad, xbad )
    return line

def getMemo():
    memo = [ "Send 10 tons of burgers to White House",
             "before midnight", "That's a lot of burgers!" ]
    return memo

def getBad():
    bad = [ "burger", "tons", "House" ]
    return bad

def processMemo( lines, bad ):
    newLines = [ ]
    for line in lines:
        line = block( bad, line )
        newLines.append( line )
    return newLines

def main():
    lines = getMemo( )
    bads   = getBad()

    for bad in bads:
        lines = processMemo( lines, bad )

    for line in lines:
        print( line )
        
main()


Good Preparation for Homework #5


The same program is developed in several steps (versions) below. We start with a very simplified version of what we have to implement, and one step at a time we add more functionality, using functions.

Version 1


# censureText.py
# D. Thiebaut
# This program opens two text files,
# one containing lines of text, the other one
# containing a list of words to remove,
# and prints the contents of the first file
# with words blocked out.

def getMemo():
    """gets the memo to be censured"""
    return "Please deliver 10 burgers and 1 bottle of ketchup"

def getBadWord():
    """gets the word to block out"""
    return "burger"

def main():
    # get a line of text, and a bad word 
    line = getMemo( )
    bad  = getBadWord( )

    # modify line by removing the bad word
    line = line.replace( bad, "x" )
    print( line )
    
main()

Version 2


In this version, we create a new function called block() that gets a line and a bad word, and replaces the bad word in line by a series of xs. Block() returns the new version of the line.

The main program now calls block() to block out the bad word in the line, gets the line back and prints it.

# censureText.py
# D. Thiebaut
# This program opens two text files,
# one containing lines of text, the other one
# containing a list of words to remove,
# and prints the contents of the first file
# with words blocked out.

def getMemo():
    """gets the memo to be censured"""
    return "Please deliver 10 burgers and 1 bottle of ketchup"

def getBadWord():
    """gets the word to block out"""
    return "burger"

def block( line, bad ):
    # create a word with 'x' the same length
    # as the bad word
    badx = "x" * len( bad )

    # modify the line and replace bad with "xx...x"
    line = line.replace( bad, badx )
    return line
    
def main():
    # get a line of text, and a bad word 
    line = getMemo( )
    bad  = getBadWord( )

    # modify line by removing the bad word
    line = block( line, bad )

    # display the resulting line
    print( line )
    
main()


Version 3


In this version, instead of working with just one word, we work with a list of bad words. We change the name of getBadWord() to getBadWords() to reflect the fact that it is returning a list of words. We now have for loop in the main program to iterate through all the bad words.

You may want to remove the #-sign in the main program to see what is happening with the code.

# censureText.py
# D. Thiebaut
# This program opens two text files,
# one containing lines of text, the other one
# containing a list of words to remove,
# and prints the contents of the first file
# with words blocked out.

def getMemo():
    """gets the memo to be censured"""
    return "Please deliver 10 burgers and 1 bottle of ketchup"

def getBadWords():
    """gets the word to block out"""
    badWords = [ "burger", "ketchup" ]
    return badWords

def block( line, bad ):
    # create a word with 'x' the same length
    # as the bad word
    badx = "x" * len( bad )

    # modify the line and replace bad with "xx...x"
    line = line.replace( bad, badx )
    return line
    
def main():
    # get a line of text, and a bad word 
    line = getMemo( )
    badWords  = getBadWords( )

    # modify line by removing the bad word
    for bad in badWords:
        #print( "blocking out word:", bad )
        #print( "line before:      ", line )
        line = block( line, bad )
        #print( "line after:       ", line )
        #print()

    # display the resulting line
    print( line )
    
main()


Output
blocking out word: burger
line before:       Please deliver 10 burgers and 1 bottle of ketchup
line after:        Please deliver 10 xxxxxxs and 1 bottle of ketchup

blocking out word: ketchup
line before:       Please deliver 10 xxxxxxs and 1 bottle of ketchup
line after:        Please deliver 10 xxxxxxs and 1 bottle of xxxxxxx

Please deliver 10 xxxxxxs and 1 bottle of xxxxxxx


Version 4


We're making the code more modular by taking some code from main and packaging into a new function, called blockAllWordsInOneLine().
No new behavior is brought in, just moving some code out of main to keep main short and easy to read.

# censureText.py
# D. Thiebaut
# This program opens two text files,
# one containing lines of text, the other one
# containing a list of words to remove,
# and prints the contents of the first file
# with words blocked out.

def getMemo():
    """gets the memo to be censured"""
    return "Please deliver 10 burgers and 1 bottle of ketchup"

def getBadWords():
    """gets the word to block out"""
    badWords = [ "burger", "ketchup" ]
    return badWords

def block( line, bad ):
    # create a word with 'x' the same length
    # as the bad word
    badx = "x" * len( bad )

    # modify the line and replace bad with "xx...x"
    line = line.replace( bad, badx )
    return line

def blockAllWordsInOneLine( line, badWords ):
    """ gets one line and a list of bad words and
    blocks out all the bad words in the line.  Returns
    the edited line.
    """
    for bad in badWords:
        line = block( line, bad )
    return line

def main():
    # get a line of text, and a bad word 
    line = getMemo( )
    badWords  = getBadWords( )

    # modify line by removing the bad word
    line = blockAllWordsInOneLine( line, badWords )
        
    # display the resulting line
    print( line )
    
main()


Version 5


We now make the function getMemo() return a list of lines, rather than just one line.
The main program must be changed, since it is now getting a list of strings rather than one string. A for-loop is all that we need. Not much change, but much more powerful program!

# censureText.py
# D. Thiebaut
# This program opens two text files,
# one containing lines of text, the other one
# containing a list of words to remove,
# and prints the contents of the first file
# with words blocked out.

def getMemo():
    """gets the memo to be censured"""
    memo = [ "Please deliver 10 burgers and 1 bottle of ketchup",
             "Make it 20 burgers and a caisse of ketchup",
             "burgers and ketchup are the best food!" ]
    
    return memo

def getBadWords():
    """gets the word to block out"""
    badWords = [ "burger", "ketchup" ]
    return badWords

def block( line, bad ):
    # create a word with 'x' the same length
    # as the bad word
    badx = "x" * len( bad )

    # modify the line and replace bad with "xx...x"
    line = line.replace( bad, badx )
    return line

def blockAllWordsInOneLine( line, badWords ):
    """ gets one line and a list of bad words and
    blocks out all the bad words in the line.  Returns
    the edited line.
    """
    for bad in badWords:
        line = block( line, bad )
    return line

def main():
    # get a line of text, and a bad word 
    lines = getMemo( )
    badWords  = getBadWords( )

    for line in lines:
        # modify line by removing the bad word
        line = blockAllWordsInOneLine( line, badWords )
        
        # display the resulting line
        print( line )
    
main()


Please deliver 10 xxxxxxs and 1 bottle of xxxxxxx
Make it 20 xxxxxxs and a caisse of xxxxxxx
xxxxxxs and xxxxxxx are the best food!


Version 6


In this version we change the getMemo() function so that it gets the lines of the memo from the file memo.txt. This file is already defined in the same directory where we save our programs. For this example, memo.txt contains the following lines:

We need 10 tons of burgers and 1 ton of ketchup 
sent to the President before midnight.


# censureText.py
# D. Thiebaut
# This program opens two text files,
# one containing lines of text, the other one
# containing a list of words to remove,
# and prints the contents of the first file
# with words blocked out.

def getMemo():
    """gets the memo to be censured from the file memo.txt"""
    #memo = [ "Please deliver 10 burgers and 1 bottle of ketchup",
    #         "Make it 20 burgers and a caisse of ketchup",
    #         "burgers and ketchup are the best food!" ]

    # open the file for reading
    file = open( 'memo.txt', 'r' )

    # add each line of the file to memo (list)
    memo = []
    for line in file:
        memo.append( line.strip() )

    # close the file
    file.close()

    # return the list of string read from the file
    return memo

def getBadWords():
    """gets the word to block out"""
    badWords = [ "burger", "ketchup" ]
    return badWords

def block( line, bad ):
    # create a word with 'x' the same length
    # as the bad word
    badx = "x" * len( bad )

    # modify the line and replace bad with "xx...x"
    line = line.replace( bad, badx )
    return line

def blockAllWordsInOneLine( line, badWords ):
    """ gets one line and a list of bad words and
    blocks out all the bad words in the line.  Returns
    the edited line.
    """
    for bad in badWords:
        line = block( line, bad )
    return line

def main():
    # get a line of text, and a bad word 
    lines = getMemo( )
    badWords  = getBadWords( )

    for line in lines:
        # modify line by removing the bad word
        line = blockAllWordsInOneLine( line, badWords )
        
        # display the resulting line
        print( line )
    
main()


Output


We need 10 tons of xxxxxxs and 1 ton of xxxxxxx
sent to the President before midnight.


Version 7


Since we were successful getting the lines from file for the memo, we are doing the same thing for the bad words.

The file badwords.txt contains the following words:

burger
ketchup
President


# censureText.py
# D. Thiebaut
# This program opens two text files,
# one containing lines of text, the other one
# containing a list of words to remove,
# and prints the contents of the first file
# with words blocked out.

def getMemo():
    """gets the memo to be censured from the file memo.txt"""
    #memo = [ "Please deliver 10 burgers and 1 bottle of ketchup",
    #         "Make it 20 burgers and a caisse of ketchup",
    #         "burgers and ketchup are the best food!" ]

    # open the file for reading
    file = open( 'memo.txt', 'r' )

    # add each line of the file to memo (list)
    memo = []
    for line in file:
        memo.append( line.strip() )

    # close the file
    file.close()

    # return the list of string read from the file
    return memo

def getBadWords():
    """gets the list of words to block out from file"""
    # open the file for reading
    file = open( 'badwords.txt', 'r' )

    # add each line of the file to list of bad words
    bads = []
    for line in file:
        bad = line.strip()
        bads.append( bad )
        
    # close the file
    file.close()

    # return the list of string read from the file
    return bads


def block( line, bad ):
    # create a word with 'x' the same length
    # as the bad word
    badx = "x" * len( bad )

    # modify the line and replace bad with "xx...x"
    line = line.replace( bad, badx )
    return line

def blockAllWordsInOneLine( line, badWords ):
    """ gets one line and a list of bad words and
    blocks out all the bad words in the line.  Returns
    the edited line.
    """
    for bad in badWords:
        line = block( line, bad )
    return line

def main():
    # get a line of text, and a bad word 
    lines = getMemo( )
    badWords  = getBadWords( )

    for line in lines:
        # modify line by removing the bad word
        line = blockAllWordsInOneLine( line, badWords )
        
        # display the resulting line
        print( line )
    
main()


Output
We need 10 tons of xxxxxxs and 1 ton of xxxxxxx
sent to the xxxxxxxxx before midnight.


03/09/18


libraryDemo.py


# libraryDemo.py
# D. Thiebaut

from myLibrary import *

def main():
    lines = [ "Soon there'll be lunch", "Spring into action",
              "Break bad habits!" ]

    for line in lines:
        print( getFirstWordOf( line ), end=" " )

    print()

main()


myLibrary.py


# myLibrary.py
# D. Thiebaut


def getFirstWordOf( line ):
    '''receives a line assumed not to be empty
    and returns its first words.  Uses whitespace
    to split the line into words.
    '''
    words = line.strip().split()
    return words[0]


NQueens.py


#! /opt/local/bin/python
# D. Thiebaut
# Usage:
#   nqueens.py N
# where N is the number of queens wanted, i.e. the dimension
# of the board.
# The program will look for the first available solution where N queens
# can be put on the board such that they cannot take each other.

import sys
import time
QUEEN = -10
EMPTY = 0

class timePerfClass:
    """A class to keep track of processor and user time.
    use by first calling start(), then stop(), then 
    printElapsed()"""

    def __init__(self):
        self.clockStart = time.clock() # init all 4 counters
        self.clockEnd   = time.clock() # to current time
        self.timeStart  = time.time()
        self.timeEnd    = time.time()

    def start( self ):
        """set the start counters to current time"""
        self.clockStart = time.clock()
        self.timeStart  = time.time()

    def stop( self ):
        """set the end counters to current time"""
        self.clockEnd   = time.clock()
        self.timeEnd    = time.time()

    def printElapsed( self ):
        """print the difference between end and start counters"""
        print "processor time:   ", (self.clockEnd-self.clockStart), "sec"
        print "user time     :   ", (self.timeEnd-self.timeStart), "sec"


def makeBoard( N ):
    """create a 2-D array of ints with dimension N
    Returns the 2D array"""
    board = []
    for i in range( N ):
        board.append( [] )
        for j in range( N ):
            board[i].append( EMPTY )
    return board
    
def goHome():
    """when used  in a terminal window that supports ANSI codes,
    brings the cursor back to top left position"""
    sys.stderr.write( "\x1b[0;0H" )

def displaySolution( board ):
  """display the solution, in the form of a series of column numbers"""
  list = []
  for i in range( len( board ) ):
      for j in range( len( board ) ):
          if board[ i ][ j ]==QUEEN:
              list.append( str( j ) )
  print "Solution = ", ','.join( list )

def displayBoard( board, home=False ):
    """display the 2D array, showing empty cells as .
    and queens as Q"""
    if home: goHome()
    for i in range( len( board ) ):
        for j in range( len( board ) ):
            if board[i][j]==QUEEN: 
               print 'Q',
            else: 
               print '.',
        print
    displaySolution( board )
    
def markLowerBoard( board, row, col, offset ):
    """Once a queen is positioned at location (row,col), 
    all the cells on a lower diagonal and lower vertical
    of this queen must be marqued as unavailable so that
    another queen cannot be put in this place"""

    N = len( board )
    diagleft = col-1
    diagright = col+1
    # mark all lower rows on diagonals and vertical
    for r in range( row+1, N ):
        if diagleft >=0:  board[r][diagleft] += offset
        if diagright <N:  board[r][diagright] += offset
        board[r][col] += offset
        diagleft  -= 1
        diagright += 1

def tryRow( board, row,  N, display=False ):
    """ put a queen on give row, and recursively try all queens
    on successive rows"""
    if row >= N:
       return True #we found a solution!

    if display:
        displayBoard( board, True )
    for col in range( N ):
        if board[row][col] == EMPTY:
            # put a queen here
            board[ row ][ col ] = QUEEN
            markLowerBoard( board, row, col, +1 )
            ok = tryRow( board, row+1, N )
            if not ok:
                # backtrack
                board[ row ][ col ] = EMPTY
                markLowerBoard( board, row, col, -1 )
            else:
                return True
    return False           
           
       
# ---------------------------------------------------------------------------
def main():
    if len( sys.argv ) < 2:
        print "Syntax: nqueens.py N"
        print "        where N is the # of queens"
        return

    #--- start measurement ---
    perf = timePerfClass()
    perf.start()

    #--- get dimension, create board, and solve! ---
    N = int( sys.argv[1] )
    board = makeBoard( N )
    ok = tryRow( board, 0, N )

    #--- stop measurement ---
    perf.stop()
    perf.printElapsed()
    
    if ok:
         print "Success!"
         displayBoard( board )

if __name__=="__main__":
    main()



03/19/18


facebookNews.txt


This file is taken from a news article published on 3/18/2018 about Facebook.

Lawmakers in the United States and Britain are calling on Facebook chief executive Mark Zuckerberg 
to explain how the names, preferences and other information from tens of millions of users ended up 
in the hands of a data analysis firm connected with President Trump's 2016 campaign.

The demands came in response to news reports Saturday about how the firm, Cambridge Analytica, used 
a feature once available to Facebook app developers to collect information on 270,000 people and, 
in the process, gain access to data on tens of millions of their Facebook friends  few, if any, 
of whom had given explicit permission for this sharing.


emails.txt


Lauryn@smith.edu
Amaris@smith.edu
Lujun@smith.edu
Cora@smith.edu
smithy@umass.edu
Olive@smith.edu
Giuliana@smith.edu
Marina@smith.edu
Aliyah@smith.edu
Itzel@hampshire.edu
Rui@smith.edu
Perla@smith.edu
Julissa@smith.edu
Linda@smith.edu
Carolina@smith.edu
Beatrice@smith.edu
Carly@smith.edu
Iris@umass.edu
Lu@smith.edu
Armani@smith.edu
Julianna@smith.edu
Mattie@smith.edu
Diya@smith.edu
Maria@smith.edu
Payten@smith.edu
Caroline@amherst.edu
Gemma@smith.edu
Jade@smith.edu
Scarlet@smith.edu
Alejandra@smith.edu
Phoebe@smith.edu
Harper@smith.edu
Tianna@smith.edu
Litzy@smith.edu
Adison@mtholyoke.edu
Isabell@smith.edu
Yuliana@smith.edu
Lillian@smith.edu
Callie@smith.edu
Hadley@smith.edu
Camille@smith.edu
Tara@smith.edu
Desirae@smith.edu
Miya@smith.edu
Laura@smith.edu
Leticia@smith.edu
Emily@smith.edu
Krista@smith.edu
Ashtyn@smith.edu
Alina@smith.edu
Tiara@smith.edu
Cameron@smith.edu
Amaya@smith.edu
Jewel@smith.edu
Brenda@smith.edu
Angel@smith.edu
Anahi@smith.edu
Lara@smith.edu
Regina@smith.edu
Mylie@smith.edu
Kyra@smith.edu
Lindsay@smith.edu
Katherine@smith.edu
Raven@smith.edu
Chloe@smith.edu
Wendy@smith.edu
Amara@smith.edu
Adelyn@smith.edu
Sharon@smith.edu
Carlee@smith.edu
Aisha@smith.edu
Chana@smith.edu
Paisley@smith.edu
Amelie@smith.edu
Dixie@smith.edu
America@smith.edu
Karla@smith.edu
Alana@smith.edu
Dulce@smith.edu
Marlene@smith.edu
Serena@smith.edu
Annabel@smith.edu
Karley@smith.edu
Lyla@smith.edu
Sandra@smith.edu
Breanna@smith.edu
Gracelyn@smith.edu
Crystal@smith.edu
Taniya@smith.edu
Jazmin@smith.edu
Madalyn@smith.edu
Holly@smith.edu
Janiya@smith.edu
Paige@smith.edu
Jaylene@smith.edu
Cecelia@smith.edu
Jaylynn@smith.edu
Tori@smith.edu
Madeline@smith.edu
Aliza@smith.edu
Rebekah@smith.edu
Kimora@smith.edu
Mayra@smith.edu
Shea@smith.edu
Ana@smith.edu
Britney@smith.edu
Aleena@smith.edu
Yaritza@smith.edu
Bridget@smith.edu
Lindsey@smith.edu
Ava@smith.edu
Yareli@smith.edu
Violet@smith.edu
Londyn@smith.edu
Tatum@smith.edu
Patience@smith.edu
Ayana@smith.edu
Lizbeth@smith.edu
Madison@smith.edu
Elisabeth@smith.edu
Halle@smith.edu
Hallie@smith.edu
Ashley@smith.edu
Evelyn@smith.edu
Evelin@smith.edu


writeThankYous.py


# writeThankYous.py
# D. Thiebaut

def writeFile( fileName, name, amount ):
    file1 = open( fileName, "w" )
    thankYou = "Dear {0:1}, thank you very much for your gift of ${1:1}!\n".format( name, amount )
    file1.write( thankYou )
    file1.close()
    
def main():
    names = [("Alex", 100), ("Joe", 10), ("Fifi", 50)]

    for name, amount in names:
        #print( tuple )
        #name = tuple[0]
        #amount = tuple[1]
        #print( "name = ", name, "amount = ", amount )
        fileName = name + ".txt"
        writeFile( fileName, name, amount )

main()

readEmails2.py


# readEmails.py
# D. Thiebaut

def writePoem( fileName, text ):
    file3 = open( fileName, "w" )
    file3.write( text )
    file3.close()
    
def numberOfLines( fileName ):
    file1 = open( fileName, "r" )
    text = file1.read().strip()
    file1.close()
    lines = text.split( "\n"  )
    return len( lines )
    
def main():
    #print( "number of emails = ", numberOfLines( "emails.txt" ) )
    text = """The quick red fox
    jumped over the lazy brown dog"""
    writePoem( "poem.txt", text )
    
    
main()


03/21/18

randomColor1.py


# randomColor1.py
# your name here
# generates a rectangle with a random width
# and height, and a given color on the screen.

from graphics import *
from random import *

def main():
    win = GraphWin("Lab 7", 600,600)

    # create rectangle with these 2 corners
    r = Rectangle( Point(50,50), Point(300,300) )

    # create a color from 3 different RGB values
    red   = randint( 0, 255 )
    green = randint( 0, 255 )
    blue  = randint( 0, 255 )
    color = color_rgb( red, green, blue )

    # set the rectangle's color with this color
    r.setFill( color )

    # draw the rectangle
    r.draw( win )

    # wait for user to click on the window before closing
    win.getMouse()
    win.close()
    
main()


animation.py


# animation.py
# D. Thiebaut
# Moves a red circle on the graphics window.
# Waits for user to click the mouse in order to stop.
from graphics import *

def main():
    win = GraphWin( "Lab 7 Moving ball", 600, 400 )

    # create and draw a red circle
    center = Point( 100, 100 )
    circ     = Circle( center, 30 )
    circ.setFill( 'red' )
    circ.draw( win )

    # set initial direction of ball
    dx = 1.5
    dy = 0.25
    
    # move ball on screen
    while win.checkMouse() == None:
        circ.move( dx, dy )
        #x = circ.getCenter().getX()
        #y = circ.getCenter().getY()
    
    win.close()    # Close window when done

main()


3/23/18


tellerWithIfsPrep.py

# teller.py
# D. Thiebaut
# simulates teller machine program
# prompts user, displays number of bills

def getAmount():
    # get amount from user
    amount = eval( input( "Amount to withdraw? " ) )
    amount = abs( int( amount ) )
    
    # return valid amount
    return amount

def breakDown( amount, denom ):
    numBills = amount // denom
    amount   = amount % denom
    return numBills, amount

def display( numBills, denom ):
    print( "{0:2} ${1:1}-bill(s)".format( numBills, denom ) )

def main():
    # get amount from user
    amount = getAmount()
    print( "Amount:", amount )

    # break it down into 20, 10, 5, and 1 $bills
    no20s, amount = breakDown( amount, 20 )
    no10s, amount = breakDown( amount, 10 )
    no5s,  no1s   = breakDown( amount, 5 )

    # display number of bills
    display( no20s, 20 )
    display( no10s, 10 )
    display( no5s,  5 )
    display( no1s,  1 )

main()


stopForLoop.py

# stopForLoop.py
# D. Thiebaut
# (there are better ways to do this,
# but when we don't know about the
# "break" statement, this will do!

def main():

    plays = [ "SS", "PP", "PS", "SP", "PR", "RR", "RR" ]

    count = 0
    for players in plays:
        if count < 3:
            print( "processing", players )
            
        count = count + 1

main()


filterVowels.py

# filterVowels.py
# D. Thiebaut
# gets a string from user
# and keep only the vowels in the string

def main():
    answer = input( "> " ).strip().lower()
    valid = ""
    for letter in answer:
        if letter in [ 'a', 'e', 'i', 'o', 'u' ]:
            valid = valid + letter

    print( "valid letters = ", valid )

main()


RPSSkeleton.py


# RPSSkeleton.py
# D. Thiebaut
# implements a skeleton game of Rock, Paper, Scissors

# 3 constants indicating the output of 1 play
PLAYER1WINS = 1
PLAYER2WINS = 2
TIE = 0

def check( P1, P2 ):
    '''given two upper case letters in P1, and P2 equal to
    "R", "S", or "P", decides which of P1 or P2 is the winner.'''

    # tie?
    if P1 == P2:
        return TIE
    else:
        # no tie, so check for all other possible combinations
        # of P1 and P2.
        if P1 == "R":
            if P2 == "S":
                return PLAYER1WINS
            else:
                return PLAYER2WINS
        if P1 == "S":
            if P2 == "R":
                return PLAYER2WINS
            else:
                return PLAYER1WINS
        if P1 == "P":
            if P2 == "S":
                return PLAYER2WINS
            else:
                return PLAYER1WINS
            
            
            
def main():
    # keep track of the score of each player
    score1 = 0
    score2 = 0

    # create a list of possible plays...
    plays = [ "RR", "RS", "SP", "PP", "PR" ]

    # evaluate the outcome of each play in the list
    for play in plays:
        #play = input( "> " ).strip().upper()
        print( "play = ", play )

        # define Player 1 and Player 2
        P1 = play[0]
        P2 = play[1]

        # output will be PLAYER1WINS, PLAYER2WINS, or TIE
        outcome = check( P1, P2 )

        # display who the winner is
        if outcome == PLAYER1WINS:
            print( "Player 1 wins" )
            score1 = score1 + 1
        if outcome == PLAYER2WINS:
            print( "Player 2 wins" )
            score2 = score2 + 1
        if outcome == TIE:
            print( "It's a tie!" )

        # update the user with the current score
        print( "Player1:", score1, "  Player2:", score2 )
        
main()


3/26/18


distanceDemo.py


# distanceDemo.py
# D. Thiebaut
# A simple program that tests a function returning
# the distance between 2 graphic points (using the
# graphics.py library)
from math import *
from graphics import *

def distance( x1, y1, x2, y2 ):
    '''returns the distance between two points with
    coordinates (x1,y1) and (x2,y2)'''
    return sqrt( (x1-x2)*(x1-x2) +
                 (y1-y2)*(y1-y2) )

def distanceP( p1, p2 ):
    '''returns the distance between two graphics
    points'''
    x1, y1 = p1.getX(), p1.getY()
    x2, y2 = p2.getX(), p2.getY()
    return distance( x1, y1, x2, y2 )

def main():
    point1 = Point( 3, 5 )  # difference in x = 4
    point2 = Point( 7, 8 )  # difference in y = 3 ==> distance is 5
    d = distanceP( point1, point2 )
    print( "distance =", d )

main()


Eliza1.py


# Eliza1.py
# D. Thiebaut
# A very short beginning program for Eliza
from time import sleep
from os import system

# --------------------------------------------------------------------------
# just print the string to the console
# will be transformed to something better later...
def myprint( string ):
    print( string )
    #system('say ' + string )
    #sleep( 0.5 )
    
# sayGoodBye
# say goodbye to the user.
def sayGoodBye( name ):
    myprint( "Good bye " + name )

# isGoodBye
# checks to see if what the user said is one of the keywords for
# ending the conversation.
def isGoodBye( userAnswer ):
    if userAnswer.lower().strip() in [ "bye", "goodbye", "ciao" ]:
        return True
    else:
        return False

def greetings():
    myprint( "Hello there!" )
    myprint( "What is your name?" )
    name = input( "> " )
    myprint( "Welcome " + name )
    return name

# --------------------------------------------------------------------------
# main function
# --------------------------------------------------------------------------                   
def main():

     # greet user and get her name
     userName = greetings()
     
     # conversation: get user input, and respond
     for i in range( 1000 ):

         # get user's statement
         userAnswer = input( "> " )

         # if it is a goodbye statement, exit the loop
         if isGoodBye( userAnswer ) == True:
             break

         # tell the user to continue speaking
         myprint( "Please tell me more..." )


     # if we're here, it's because the loop stopped.
     # say goodbye to the user
     sayGoodBye( userName )
            
         
main()


Eliza2.py


# Eliza2.py
# D. Thiebaut (created in class on 3/28)
# A very short beginning program for Eliza
from time import sleep
from os import system
from random import choice

# --------------------------------------------------------------------------
# just print the string to the console
# will be transformed to something better later...
def myprint( string ):
    print( string )
    #system('say ' + string )
    #sleep( 0.5 )
    
# sayGoodBye
# say goodbye to the user.
def sayGoodBye( name ):
    myprint( "Good bye " + name )

# isGoodBye
# checks to see if what the user said is one of the keywords for
# ending the conversation.
def isGoodBye( userAnswer ):
    if userAnswer.lower().strip() in [ "bye", "goodbye", "ciao" ]:
        return True
    else:
        return False

def greetings():
    myprint( "Hello there!" )
    myprint( "What is your name?" )
    name = input( "> " )
    myprint( "Welcome " + name )
    return name

# --------------------------------------------------------------------------
# main function
# --------------------------------------------------------------------------                   
def main():

     prompts = ["Please go on...", "Please tell me more...",
            "Interesting... Go on, please", 
            "Yes?  Really? Go on",
            "Weird... I'm not sure what to think of that..." ]

     family = [ "mother", "father", "brother", "sister" ]
     
     # greet user and get her name
     userName = greetings()
     
     # conversation: get user input, and respond
     for i in range( 1000 ):

         # get user's statement
         userAnswer = input( "> " )

         # if it is a goodbye statement, exit the loop
         if isGoodBye( userAnswer ) == True:
             break # break out of for-loop

         familyMatter = False
         for word in family:
             if userAnswer.lower().find( word ) != -1:
                 familyMatter = True

         if familyMatter == True:
             myprint( "tell me more about your family" )
         else:
             # tell the user to continue speaking
             myprint( choice( prompts ) )


     # if we're here, it's because the loop stopped.
     # say goodbye to the user
     sayGoodBye( userName )
            
         
main()

3/30/18


YesNo.py


# get a YES/NO answer from user
def getAnswerYesNo():
   x = input( "Continue (Yes/No)? " ).upper()
   while x != "NO" and x != "YES":
       print( "Invalid input, must be YES or NO" )
       x = input( "Continue (Yes/No)? " ).upper()
   return x

def getAnswerYesNo2():
   x = input( "Continue (Yes/No)? " )
   while not x.upper() in [ "NO", "YES", "NOPE", "YEAH" ]:
       print( "Invalid input, must be YES or NO" )
       x = input( "Continue (Yes/No)? " )
   return x

def main():
    ans = getAnswerYesNo()    
    print( ans )                

    ans = getAnswerYesNo2()    
    print( ans )                

main()


Eliza3.py


# Eliza3.py
# D. Thiebaut
# This version of Eliza implements reflection and detection
# of negative comments
from time import sleep
from os import system
from random import choice

# --------------------------------------------------------------------------
# just print the string to the console
# will be transformed to something better later...
def myprint( string ):
    print( string )
    # system('say ' + string )
    # sleep( 0.5 )
    
# sayGoodBye
# say goodbye to the user.
def sayGoodBye( name ):
    myprint( "Good bye " + name )

# isGoodBye
# checks to see if what the user said is one of the keywords for
# ending the conversation.
def isGoodBye( userAnswer ):
    if userAnswer.lower().strip() in [ "bye", "goodbye", "ciao" ]:
        return True
    else:
        return False

def greetings():
    myprint( "Hello there!" )
    myprint( "What is your name?" )
    name = input( "> " )
    myprint( "Welcome " + name )
    return name

# --------------------------------------------------------------------------
# main function
# --------------------------------------------------------------------------                   
def main():

     prompts = ["Please go on...", "Please tell me more..." ]
     negPrompts = [ "My, my, why so negative?", "Really?", "Why not?" ]
     family = [ "mother", "father", "brother", "sister" ]
     
     # greet user and get her name
     userName = greetings()
     
     # conversation: get user input, and respond
     timeToStop = False
     while timeToStop==False:

         # get user's statement
         userAnswer = input( "> " )

         # if it is a goodbye statement, exit the loop
         if isGoodBye( userAnswer ) == True:
             timeToStop = True
             continue

         # is the patient talking about a family member?
         for word in family:
             if userAnswer.lower().find( word ) != -1:
                 myprint( "tell me more about your family" )
                 continue


         # reflection
         # "I XXXX you" --> "You XXXX me?"
         words = userAnswer.strip().split()
         if len( words )==3 and words[0]=="I" and words[2]=="you":
             myprint( "You " + words[1] + " me?" )
             prompts.append( "Is that why you " + words[1] + " me?" )
             continue
             
         # negative answers
         if userAnswer.upper() in [ "NO", "NEVER", "NOPE", "NADA", "NON" ]:
             myprint( choice( negPrompts ) )
             continue
         
         # if we're here, it's because none of the tests above were true,
         # and we didn't detect a negative answer, a family matter, or a
         # reflection.  So we just print a random prompt.
         myprint( choice( prompts ) )


     # if we're here, it's because the loop stopped.
     # say goodbye to the user
     sayGoodBye( userName )
            
         
main()


4/2/18


readCSV.py


# readCSVFile.py
# D. Thiebaut
# Example of a program that reads a CSV file
# and displays some of its contents.

def readCSV( fileName ):
    file = open( fileName, 'r' )
    Records = [ ]
    lines = file.readlines()
    for line in lines:
        #words = line.replace( '"','').strip().split( ',' )
        words = line.replace( '"','').strip().split( ',' )
        Records.append( words )
    file.close()
    return Records

def main():
    fileName = input( "File name? " )
    recs = readCSV( fileName )
    for i in range( len( recs ) ):
        record = recs[i]
        # record is a tuple
        # join each word in the tuple by a tab, and print
        # resulting string
        print( "Record ", i, "=", "\t".join( record ) )

main()


dieClass.py


# dieClass.py
# D. Thiebaut
# A class for the definition of a simple
# die, with any number of sides

# libraries
from random import *

# a class for a die
class Die:
    def __init__( self, n ):
         self.noSides = n
         self.value   = 1

    def roll( self ):
         self.value = randrange( 1, self.noSides+1 )

    def getValue( self ):
         return self.value


playDice.py


# playDice.py
# D. Thiebaut
# Uses the Class.py class
# and plays with a few dice

from dieClass import Die

def main():
    # Create 2 dice, one with 6 sides
    d1 = Die( 6 )
    d2 = Die( 8 )

    for play in range( 10 ):
        print( "\nPlay No.", play+1 )
        # Roll both dice
        d1.roll( )
        d2.roll( )

        # display their value
        print( "Die 1: ",  d1.getValue() )
        print( "Die 2: ",  d2.getValue() )

main()


Main Program for Cat Objects


# cats1.py
# D. Thiebaut
# Define a Cat class, and
# use it to create a collection of
# cats.

# -----------------------------------------------------------
# add class definition here!


# -----------------------------------------------------------
# main program
def main():
    """ main program.  Creates a list of cats and displays
    groups sharing the same property.
        Minou, 3, vac, stray
        Max, 1, not-vac, Burmese
        Gizmo, 2, vac, Bengal
        Garfield, 4, not-vac, Orange Tabby
    """
    cats = []
    cat = Cat( "Minou", "stray", True, 3 )
    cats.append( cat )
    
    cats.append( Cat( "Max", "Burmese", False, 1 ) )
    cats.append( Cat( "Gizmo", "Bengal", True, 2 ) )
    cats.append( Cat( "Garfield", "Orange Tabby", False, 4 ) )

    # print the list of all the cats
    print( "\nComplete List:" )
    for cat in cats:
        print( cat )

   


main()


4/4/18

cats.py with class


class Cat:
    def __init__( self, na, vacc, bre, ag ):
        self.name       = na
        self.vaccinated = vacc
        self.breed      = bre
        self.age        = ag

    def isVaccinated( self ):
        return self.vaccinated

    def getName( self ):
        return self.name

    def getAge( self ):
        return self.age
    
    def __str__( self ):
        vacc = "vaccinated"
        if self.vaccinated == False:
            vacc = "not vaccinated"
        return "{0:20}:==>{1:1}, {2:1}, {3:1} yrs old".format(
            self.name, self.breed, vacc, self.age )
    
def main():
    cats = [ ]
    
    # Minou, 3, vac, stray
    cat1 = Cat( "Minou", False, "stray", 3 )
    cats.append( cat1 )
    # Print if cat is vaccinated or not
    if cat1.isVaccinated():
        print( cat1.getName(), "is vaccinated" )
    else:
        print( cat1.getName(), "is not vaccinated" )
    """
    Minou, 3, vac, stray
    Max, 1, not-vac, Burmese
    Gizmo, 2, vac, Bengal
    Garfield, 4, not-vac, Orange Tabby"""

    cats.append( Cat( "Max", False, "Burmese", 1 ) )
    cats.append( Cat( "Gizmo", True, "Bengal", 2 ) )
    cats.append( Cat( "Garfield", False, "Orange Tabby", 4 ) )

    for cat in cats:
        if cat.getAge() >= 2 and not cat.isVaccinated():
            print( cat )
    
    
main()

4/6/18

Car Class. Version 1


# carClass.py
# D. Thiebaut
# Example program where we create a class for a car
# made of a body (rectangle) and two wheels.

from graphics import *

N = 5 # number of cars

class Car:
    '''a definition for a car made of a rectangle
    and two circles'''

    def __init__( self, topLeft, width, height ):
        '''constructor.  Builds a car from topLeft point,
        width, and height'''

        # save reference point and height and width  
        self.topLeft = topLeft
        self.width   = width
        self.height  = height
        
        # create bottom-right point P1
        x1 = topLeft.getX()
        y1 = topLeft.getY()
        P2 = Point( x1+width, y1+height )

        # create body
        self.body = Rectangle( topLeft, P2 )

        # create two wheels
        center1 = Point( x1+40, y1+height )
        self.wheel1 = Circle( center1, 20 )
        center2 = Point( x1+width-40, y1+height )
        self.wheel2 = Circle( center2, 20 )

        # define colors
        self.body.setFill( "yellow" )
        self.wheel1.setFill( "black" )
        self.wheel2.setFill( "black" )

    def draw( self, win ):
        '''draw the car on the window '''
        self.body.draw( win )
        self.wheel1.draw( win )
        self.wheel2.draw( win )

    def move( self, dx, dy ):
        ''' move the car (body and wheels) by dx, dy '''
        self.body.move( dx, dy )
        self.wheel1.move( dx, dy )
        self.wheel2.move( dx, dy )
        
def main():
    win = GraphWin( "Moving cars", 600, 400 )

    # create N cars
    cars = [ ]
    for i in range( N ):
        car1 = Car(  Point( 30,60*i ), 190, 40 )
        cars.append( car1 )

    # draw N cars
    for car1 in cars:
        car1.draw( win )

    # move N cars 20 dx pixels to the right
    dx = 10
    dy = 0
    for i in range( 20 ):
        for car1 in cars:
           car1.move( dx, dy )
      
    # wait for user to click the mouse 
    win.getMouse()
    win.close()    # Close window when done

main()


A more advanced Car class


# carClassDemo.py
# D. Thiebaut
# A program that defines a class for cars,
# and a demo main program that displays
# several cars.

# import all graphic objects
from graphics import *
from random import randrange

# constants
N = 5 # number of cars

class Car:
    """Definition for a car with a body and two wheels"""

    def __init__(self, win, topLeft, width, height ):
        """constructs a car made of 1 rectangle with top-left
        point topLeft, dimension width x height, and two wheels
        away from left and right by 10 pixesl"""
        # save width and height of car
        self.width = width
        self.height = height
        
        # create bottom-right point
        x1 = topLeft.getX()
        y1 = topLeft.getY()
        P2 = Point( x1+width, y1+height )

        # body is a rectangle between topLeft and P2
        self.body = Rectangle( topLeft, P2 )
        self.body.setFill( "yellow" )

        # create wheel #1
        center1 = Point( x1+20, y1+height )
        self.wheel1 = Circle( center1, 20 )
        self.wheel1.setFill( "black" )

        # create wheel #2
        center2 = Point( x1+width-20, y1+height )
        self.wheel2 = Circle( center2, 20 )
        self.wheel2.setFill( "black" )

        # create random speed
        self.dx = randrange( -100, 100 )/10

        # save window width (so that a car can detect
        # that it's going outside the left or right
        # margins)
        self.windowWidth = win.getWidth()

    def setFill( self, color ):
        '''sets the color of the body of the car'''
        self.body.setFill( color )
        
    def draw( self, win ):
        """draw the car on the window"""
        self.body.draw( win )
        self.wheel1.draw( win )
        self.wheel2.draw( win )
            
    def move( self ):
        """move the body and wheels of the car by dx"""
        self.body.move( self.dx, 0 )
        self.wheel1.move( self.dx, 0 )
        self.wheel2.move( self.dx, 0 )

        # is P1 outside the right margin?
        x = self.body.getP1().getX()
        if x > self.windowWidth:
            # yes! move the car to the left of the left margin
            self.body.move( -self.windowWidth-self.width, 0 )
            self.wheel1.move( -self.windowWidth-self.width, 0 )
            self.wheel2.move( -self.windowWidth-self.width, 0 )
            
        x = self.body.getP2().getX()
        # is P2 outside the left margin?
        if x < 0:
            # yes!  move the car to the right of the right margin
            self.body.move( +self.windowWidth+self.width, 0 )
            self.wheel1.move( +self.windowWidth+self.width, 0 )
            self.wheel2.move( +self.windowWidth+self.width, 0 )

def main():
        # open graphic window
        win = GraphWin( "Car Park", 700, 600 )

        # create a list of N cars
        cars = [ ]
        for i in range( N ):
            car =  Car( win, Point( randrange(1,700),
                                    randrange(1,500) ),
                        randrange( 100, 200),
                        randrange( 30, 50 ) ) 
            car.setFill( color_rgb( randrange( 0, 100 ),
                                    randrange( 100, 200 ),
                                    randrange( 100, 200 ) ) )
            cars.append( car )

        # draw all cars
        for car in cars:
            car.draw( win )

        # animation loop: move all the cars, until
        # user clicks mouse
        while True:
            if win.checkMouse(): break
            for car in cars:
                car.move( )
                         
        # wait for mouse-click
        win.getMouse()
        win.close()

main()


4/9/18


CatGlasses.gif


catGlasses.gif, 424 × 418


FlowersSmith.gif


FlowersSmith.gif, 661 × 255


CatHat.gif


catHat.gif, 243 × 207


imageProcessingSkel.py


# 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

def main():
    # open the window
    win = GraphWin( "CSC111 Image Viewer", WIDTH, HEIGHT )

    # get the file name from the user
    fileName = "catGlasses.gif" #input( "Image name? " )
    print()
    
    # open the cat image
    cat = Image( Point(WIDTH//2, HEIGHT//2), fileName )
    cat.draw( win )

    # wait for user to click the mouse...
    win.getMouse()

    # and close the window
    win.close()

main()


ImageProcessingRedSaturate.py


# ImageProcessingRedSaturate.py
# D. Thiebaut
# A skeleton program to start performing some image processing
# in Python.  Here we set pixels redder, and saturate the colors.

from graphics import *
from random import *


#WIDTH  = 661   # width and height of flowers.gif
#HEIGHT = 255

#WIDTH  = 424  # width and height for CatGlasses.gif
#HEIGHT = 418

WIDTH  = 243   # width and height for catHat.gif
HEIGHT = 207

def saturate( col ):
    '''given a color between 0 and 255, return 0 if the color
    is less than half 255, or 255 otherwise.  This will saturate
    the color'''
    if col < 255/2:
        return 0
    else:
        return 255

def makeRed( img, win ):
    '''given an image of geometry WIDTH x HEIGHT, touches
    all the pixels of the image and sets their RED component to
    255.'''

    for x in range( WIDTH ):
        win.update()
        for y in range( HEIGHT ):
            red, green, blue = img.getPixel( x, y )

            red = 255 

            # other possible transformations:
            #red = saturate( red )
            #green = randint( 0, 255 )
            #blue  = saturate( blue )
            img.setPixel( x, y, color_rgb( red, green, blue ) )
            

def drawBorder( img, win ):
    '''draws the beginning of a border at the top of the
    image.  The border is 20 pixels high, and red.'''
    for x in range( WIDTH ):
        for y in range( 20 ):
            img.setPixel(x,y, color_rgb( 255, 0, 0 ) )
        
def main():
    # open the window
    win = GraphWin( "CSC111 Image Viewer", WIDTH, HEIGHT )

    # get the file name from the user
    #fileName = "flowers.gif" #input( "Image name? " )
    #fileName = "CatGlasses.gif"
    fileName = "catHat.gif"
    print()
    
    # open the cat image
    cat = Image( Point(WIDTH//2, HEIGHT//2), fileName )
    cat.draw( win )

    # change the pixels to max red
    makeRed( cat, win )
    
    # change the pixels to max red
    drawBorder( cat, win )
    win.update()
    
    # wait for user to click the mouse...
    win.getMouse()

    # and close the window
    win.close()

main()


4/11/18


ImageProcessingCopy.py


# imageProcessingCopy.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

# catHatLong.gif
# 729 × 207

WIDTH  = 729          # 3 times the width of the cat
CATWIDTH = WIDTH // 3 # just the cat
HEIGHT = 207

def copy( win, img, srcX, offset, width ):
    '''copy part of the image starting at srcX, width pixels
    horizontally, at srcX+offset. Copies whole height of pixels.'''
    for x in range( srcX, srcX + width ):
        win.update()
        for y in range( 0, HEIGHT ):
            r,g,b = img.getPixel( x, y )
            color = color_rgb( r,g,b )
            img.setPixel( x+offset, y, color )
            
def main():
    # open the window
    win = GraphWin( "CSC111 Image Viewer", WIDTH, HEIGHT )

    # get the file name from the user
    fileName = "catHatLong.gif" #input( "Image name? " )
    print()
    
    # open the cat image
    cat = Image( Point(WIDTH//2, HEIGHT//2), fileName )
    cat.draw( win )

    # replicate the cat, from 0 to 1 CATWIDTH away,
    # copy CATWIDTH pixels, horizontally
    copy( win, cat, 0, CATWIDTH, CATWIDTH )
    copy( win, cat, 0, CATWIDTH*2, CATWIDTH )
    
    # wait for user to click the mouse...
    win.getMouse()

    # and close the window
    win.close()

main()


checkers0.py


# 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 8x8 cells covering the whole window."""   
    for i in range( 8 ):
        for j in range( 8 ):
            x = i * SIDE   # the coordinates of the top-left corner of a cell
            y = j * SIDE
            rect = Rectangle( Point( x, y ), Point( x+SIDE, y+SIDE ) )
            rect.setFill( color_rgb( 50, 200, 50 ) )
            #rect.setFill( color_rgb( 255-(i+j)*10, i*j*3,  255-i*j*3 ) )
            rect.draw( win )
            
#----------------------------------------------------------------
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()


checkers2_incomplete.py


# checkers2.py
#
from graphics import *

WIDTH = 600
HEIGHT= 600
SIDE  = 600 // 8

# ------------------------------------------------------------
class CheckersPiece:
    '''a class for a checkers piece.  Made of 2 circles
    of different colors.  Can be light grey if white piece,
    or dark grey if black piece'''
    
    def __init__( self, color, i, j, win ):
        '''creates a piece at i, j, and draws it on window'''
        
        self.color = color
        self.i     = i
        self.j     = j
        self.circ1 = Circle( Point( (i+0.5)*SIDE, (j+0.5)*SIDE ),
                             (SIDE//2)-5 )
        self.circ2  = Circle( Point( (i+0.5)*SIDE, (j+0.5)*SIDE ),
                             (SIDE//2)-10 )
        if color=="black":
            self.circ1.setFill( "black" )
            self.circ2.setFill( "darkgrey" )
        else:
            self.circ1.setFill( "lightgrey" )
            self.circ2.setFill( "white" )
            
        self.circ1.draw( win )
        self.circ2.draw( win )
# ------------------------------------------------------------

        
def isBlack( i, j ):
    '''given the row and column of a square,
    returns True if the square is black.  False otherwise.
    '''
    if (i+j)%2==0:
        return True
    return False

def isWhite( i, j ):
    '''returns True if square at i,j is white'''
    return not isBlack( i, j )

        
def displayBoard( win ):
        
    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 isWhite(i, j):
                rect.setFill( "white" )
            else:
                rect.setFill( "grey" )
            rect.draw( win )
 
def displayCheckers( win ):
    # display checkers
    # add code here!
    # ...
    
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 )

    # 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
    whites, blacks = displayCheckers( win )
                       
    waitForClick( win, "click to close" )

    win.close()

main()



4/13/18


checkers4.py


Make sure you download these two gif images first, and store them in the same directory where you will store your checkers4.py program. The left image is called piece.gif and the one on the right piece2.gif.
Piece.gif     Piece2.gif

# 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, color, i, j, win ):
        self.color = color
        self.i     = i
        self.j     = j
        if color=="white":
            self.image = Image( Point( i*SIDE + SIDE//2,
                                       j*SIDE + SIDE//2 ), "piece2.gif" )
        else:
            self.image = Image( Point( i*SIDE + SIDE//2,
                                       j*SIDE + SIDE//2 ), "piece.gif" )
            
        self.image.draw( win )

    def undraw( self ):
        self.image.undraw()
        
def displayBoard( win ):
    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 isWhite( 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 isBlack( 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."""
    return (i+j) % 2 == 0

def isWhite( i, j ):
    return not isBlack( i, j)

def displayCheckers( win ):
    # display checkers
    checkers = []
    for i in range( 8 ):
        for j in range( 0, 3 ):
            if isBlack( i, j ):
                checkers.append( CheckersPiece( "white", i, j, win ) )

        for j in range( 5, 8 ):
            if isBlack( i, j ):
                checkers.append( CheckersPiece( "black", i, j, win ) )
    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()



checkersInteractive1.py


In this version we can move the piece by click on them, then clicking on an empty square.

# checkers00.py
# D. Thiebaut
# A first program to display an 8x8 chessboard
# in a graphic window.
# 
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 ):
        '''moves the checker piece from where it is,
        to the new position at i,j'''
        # convert i, j to an x, y coordinate
        destX = i * SIDE + SIDE//2
        destY = j * SIDE + SIDE//2
        # convert current i, j position to x,y coordinate
        currentX = self.i * SIDE + SIDE//2
        currentY = self.j * SIDE + SIDE//2
        # compute delta between where we are (currentX,currentY) to
        # where we want to be (destX,destY)
        deltaX = destX - currentX
        deltaY = destY - currentY
        # move the image by deltaX, deltaY
        self.image.move( deltaX, deltaY )
        # update our current i,j position
        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 waitForClick( win, message ):
    """ waitForClick: stops the GUI and displays a message.  
    Returns when the user clicks the window. The message is erased."""
    startMsg = Text( Point( win.getWidth()/2, win.getHeight()-15 ),
                     message )
    startMsg.draw( win )    # display message
    win.getMouse()          # wait
    startMsg.undraw()       # erase

def checkIfCheckerPieceAt( i, j, checkers ):
    '''goes through the list of checkers, and if one is
    found at location i, j, then return that piece.  Otherwise
    return None.'''
    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
    # -----------------------------------------------
    clickedPiece = None
    while True:            
        # 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

        # check to see if a checkers piece was clicked
        piece = checkIfCheckerPieceAt( i, j, checkers )
        
        if piece != None:
            # yes, a piece was clicked!  Remember which one it is
            clickedPiece = piece
            print( "User clicked on", clickedPiece )
            continue
        else:
            # no, no piece clicked.  So user clicked an empty
            # square.  If she had clicked a piece before, then
            # move that piece.  Otherwise, just don't do anything
            print( "User clicked on a square at (",i,", ", j,")" )
            if clickedPiece != None:
                print( "Moving piece", clickedPiece, "to(",i,", ", j,")" )
                clickedPiece.moveToSquare( i, j, win )
                clickedPiece = None
        
    # wait for user to click before closing everything...
    waitForClick( win, "click to close" )

    win.close()

main()


checkers4MoveRemoveWithButton.py


CheckerBoardWithButton.png


# checkers4MoveRemoveWithButton.py
# D. Thiebaut
# A first program to display an 8x8 chessboard
# in a graphic window.
# 
from graphics import *

WIDTH = 680       # width of the window
HEIGHT= 680+30    # height of the window (30 for border at bottom)
SIDE  = 680//8    # the side of a cell of the 8x8 board

class Button:
    def __init__( self, x, y, w, h, caption ):
        self.box = Rectangle( Point( x, y ), Point(x+w, y+h) )
        self.box.setFill( "lightgrey" )
        self.caption = Text( Point( x+w//2, y+h//2), caption )

    def draw( self, win ):
        self.win = win
        self.box.draw( win )
        self.caption.draw( win )

    def isClicked( self, point ):
        x = point.getX()
        y = point.getY()
        x1, y1 = self.box.getP1().getX(), self.box.getP1().getY()
        x2, y2 = self.box.getP2().getX(), self.box.getP2().getY()
        return x1 <= x <= x2 and y1 <= y <= y2
    
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 waitForClick( win, message ):
    """ waitForClick: stops the GUI and displays a message.  
    Returns when the user clicks the window. The message is erased."""
    startMsg = Text( Point( win.getWidth()/2, win.getHeight()-15 ),
                     message )
    startMsg.draw( win )    # display message
    win.getMouse()          # wait
    startMsg.undraw()       # erase

def checkIfCheckerPieceAt( 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 the Quit button
    quitButton = Button( WIDTH-60, HEIGHT-25, 50, 20, "Quit" )
    quitButton.draw( win )
    
    # display 8x8 checkers board
    displayBoard( win )
    checkers = displayCheckers( win )

    # -----------------------------------------------
    # Animation Loop
    # -----------------------------------------------
    clickedPiece = None
    while True:
        # did the user press the D key?
        key = win.checkKey()
        if key in ['D', 'd'] and clickedPiece != None:
            print( "User pressed 'D' and a piece is selected" )
            clickedPiece.undraw()
            checkers.remove( clickedPiece )
            clickedPiece = None
            continue
            
        # see if the user clicked the mouse
        mouseClick = win.checkMouse()

        # if not, then keep looping and do nothing
        if mouseClick == None:
            continue

        # did user click on the Quit button?
        if quitButton.isClicked( mouseClick ):
            print( "User pressed Quit" )
            break
        
        # 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

        # check to see if a checkers piece was clicked
        piece = checkIfCheckerPieceAt( i, j, checkers )
        
        if piece != None:
            # yes, a piece was clicked!  Remember which one it is
            clickedPiece = piece
            print( "User clicked on", clickedPiece )
            continue
        else:
            # no, no piece clicked.  So user clicked an empty
            # square.  If she had clicked a piece before, then
            # move that piece.  Otherwise, just don't do anything
            print( "User clicked on a square at (",i,", ", j,")" )
            if clickedPiece != None:
                print( "Moving piece", clickedPiece, "to(",i,", ", j,")" )
                clickedPiece.moveToSquare( i, j, win )
                clickedPiece = None
        
    # wait for user to click before closing everything...
    #waitForClick( win, "click to close" )

    win.close()

main()


rainiest.py skeleton


# rainiest.py
# D. Thiebaut
# Takes the data file for the town of Cardiff, in the UK,
# stored at this URL:# http://cs.smith.edu/~dthiebaut/UKTemperatures/
# then outputs the rainiest month and year.


def getWebData( URL ):
    '''
    gets the list of lines from the Web page at URL.
    This solution was found in the Python docs, at
    https://docs.python.org/3/howto/urllib2.html
    '''
    # import the library for accessing Web URLs
    from urllib.request import urlopen

    # attempt to get the Web page
    try:
        f = urlopen( URL )
        text = f.read().decode('utf-8')
    except urllib.error.URLError as e:
        # if error, print error message and
        # return empty list
        print( "ERROR!\n", e.reason )
        return []
    
    # return the list of lines
    lines = text.split( "\n" )
    return lines


def main():
    # get the lines of text from the Cardiff data file
    lines = getWebData( "http://cs.smith.edu/~dthiebaut/"
                        +"UKTemperatures/cardiffdata.txt" )

    # create an empty list of tuples.  The tuples will have
    # the format ( rainAmount, year, month )
    allRainTuples = []

    # go through each line and split it into words,
    # then add a tuple to the list of tuples
    for line in lines :
        
        # to be completed at a later time...


    # sort the list of tuples from least rainy to rainiest
    allRainTuples.sort()

    # display the information (raw format... could be improved)
    print( "rainiest: ", allRainTuples[-1] )

main()


emails.txt


Just a list of fake 5-col email addresses.

Lauryn@smith.edu
Amaris@smith.edu
Lujun@smith.edu
Cora@smith.edu
smithy@umass.edu
Olive@smith.edu
Giuliana@smith.edu
Marina@smith.edu
Aliyah@smith.edu
Itzel@hampshire.edu
Rui@smith.edu
Perla@smith.edu
Julissa@smith.edu
Linda@smith.edu
Carolina@smith.edu
Beatrice@smith.edu
Carly@smith.edu
Iris@umass.edu
Lu@smith.edu
Armani@smith.edu
Julianna@smith.edu
Mattie@smith.edu
Diya@smith.edu
Maria@smith.edu
Payten@smith.edu
Caroline@amherst.edu
Gemma@smith.edu
Jade@smith.edu
Scarlet@smith.edu
Alejandra@smith.edu
Phoebe@smith.edu
Harper@smith.edu
Tianna@smith.edu
Litzy@smith.edu
Adison@mtholyoke.edu
Isabell@smith.edu
Yuliana@smith.edu
Lillian@smith.edu
Callie@smith.edu
Hadley@smith.edu
Camille@smith.edu
Tara@smith.edu
Desirae@smith.edu
Miya@smith.edu
Laura@smith.edu
Leticia@smith.edu
Emily@smith.edu
Krista@smith.edu
Ashtyn@smith.edu
Alina@smith.edu
Tiara@smith.edu
Cameron@smith.edu
Amaya@smith.edu
Jewel@smith.edu
Brenda@smith.edu
Angel@smith.edu
Anahi@smith.edu
Lara@smith.edu
Regina@smith.edu
Mylie@smith.edu
Kyra@smith.edu
Lindsay@smith.edu
Katherine@smith.edu
Raven@smith.edu
Chloe@smith.edu
Wendy@smith.edu
Amara@smith.edu
Adelyn@smith.edu
Sharon@smith.edu
Carlee@smith.edu
Aisha@smith.edu
Chana@smith.edu
Paisley@smith.edu
Amelie@smith.edu
Dixie@smith.edu
America@smith.edu
Karla@smith.edu
Alana@smith.edu
Dulce@smith.edu
Marlene@smith.edu
Serena@smith.edu
Annabel@smith.edu
Karley@smith.edu
Lyla@smith.edu
Sandra@smith.edu
Breanna@smith.edu
Gracelyn@smith.edu
Crystal@smith.edu
Taniya@smith.edu
Jazmin@smith.edu
Madalyn@smith.edu
Holly@smith.edu
Janiya@smith.edu
Paige@smith.edu
Jaylene@smith.edu
Cecelia@smith.edu
Jaylynn@smith.edu
Tori@smith.edu
Madeline@smith.edu
Aliza@smith.edu
Rebekah@smith.edu
Kimora@smith.edu
Mayra@smith.edu
Shea@smith.edu
Ana@smith.edu
Britney@smith.edu
Aleena@smith.edu
Yaritza@smith.edu
Bridget@smith.edu
Lindsey@smith.edu
Ava@smith.edu
Yareli@smith.edu
Violet@smith.edu
Londyn@smith.edu
Tatum@smith.edu
Patience@smith.edu
Ayana@smith.edu
Lizbeth@smith.edu
Madison@smith.edu
Elisabeth@smith.edu
Halle@smith.edu
Hallie@smith.edu
Ashley@smith.edu
Evelyn@smith.edu
Evelin@smith.edu