Python 3 Help






https://www.python.org/downloads/


http://invpy.com/book



For PyGame Download:
--------------------

http://www.nerdparadise.com/programming/pygame/part1

or 

http://inventwithpython.com/pygamewindowsinstall.html


To Install PyGame:

1) Use the DOS command line (go to windows programs)

2) cd [location of python3.5]

3) copy your downloaded pygame to the location of Python3.x

4) type in:  python -m pip install pygame

Do we need to download it?  
python3 -m pip install pygame
python3 -m pygame.examples.aliens

Then add to your program at the beginning:

import pygame
pygame.init()



add String methods, tuples, dictionaries

import random
number = random.randint(1, 20)


GUI programming is not standard in python

https://opensource.com/life/16/5/open-source-python-gui-frameworks

http://www.datadependence.com/2016/04/how-to-build-gui-in-python-3/

https://docs.python.org/3/library/othergui.html



Operators
Comments
import
type casts
Constants
Ranges
Hello World
Loops
Declaring Variables
Escape Sequences
Printing on the Console
Creating Functions
Functions with Arguments
Built in Functions
Lists (Arrays)
Tuples (Immutable Lists)
Dictionaries
Lists 2D(Arrays 2D)
Classes
Reading from the Console
if else statements
string
if else statements
Files
Creating Objects
Some Simple Programs
PyGame
Labs



(see https://www.tutorialspoint.com/python3 for more help)

===================
===================

Operators

===================
===================

Arithmetic Operators ( +, -, /, //, *, **)
# / produces a float, where as // produces an whole number (floors it)

Relational Operators (==, !=, >, <, >=, <=)

Logical Operators (and, or, not )

Bitwise Operators (&, |, ^, ~, <<, >>)

Assignment Operators (=, +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, |=)



===================
===================

Comments

===================
===================

# This is a comment
 
''' Python comments can also
    span multiple lines
if you use 3 single quotes to start
and 3 single quotes to end
'''

 
""" Python comments can also use
double quotes to start and end a String
or a comment.
    A String that
spans multiple lines.
"""
 
========================
========================

import

========================
========================



Python built in functions:
abs, divmod, cmp, coerce, float, hex, int, max, min, oct,
pow, round




The math module provides more functions

from math import *

acos, asin, atan, atan2, ceil, cos, cosh, e, exp, fabs, floor, fmod,
frexp, hypot, ldexp, log, log10, mod, pi, pow, sin, sinh, sqrt, tan,
tanh


NumPy has a lot more at www.scipy.org



Support for Complex Numbers are built in.
Use j for the square root of -1

(3+2j)


Complex Number functions
------------------------
import cmath

acos, acosh, asin, asinh, atan, atanh, cos, cosh, e, exp, log, log10,
pi, sin, sinh, sqrt, tan, tanh.

import cmath

cmath.sqrt(-1)
1j



Other functions
---------------
ord(ch)			# ordinal value of 1 character string
hex(integer)    # returns as a string the hex number 
oct(integer)	# returns as a string the octal number




# play sounds (print("\a") does not work in 3)
----------------------------------------------
import winsound         # for sound  
import time             # for sleep


winsound.Beep(440, 250) # frequency, duration
time.sleep(0.25)        # in seconds (0.25 is 250ms)

winsound.Beep(600, 250)
time.sleep(0.25)




===================
===================

type casts

===================
===================




x = 12
float(x) # x is now 12.0

x = 12.5
int(x)  # x is now 12

str(12) # this is now "12"


x = int(input("Enter a first number: "))
y = int(input("Enter a second number: "))




===================
===================

Constants

===================
===================



from named_constants import Constants

>>> class Colors(Constants):
...     black = 0
...     red = 1
...     white = 15
...
>>> c = Colors.black
>>> c == 0
True
>>> c
Colors.black
>>> c.name()
'black'
>>> Colors(0) is c
True



#const.py
class Constants:
    @classmethod
    get_vara(cls):
        return 1


#app.py
from const import Constants
print(Constants.get_vara())

#output
1





===================
===================

Ranges

===================
===================




num = int(input("Tell me a number: "))
for i in range(num):
	print("Hello")


range(5) is equivalent to range(0, 5)
range(2,6)—     2,3,4,5
range(6,2)—     no values
range(2,8,2)—   2,4,6
range(2,9,2)—   2,4,6,8
range(6,2,-1)—  6,5,4,3


for i in range(6):
	print(i, end=" ") # prints 0, 1, 2, 3, 4, 5

	
for i in range(2, 6):
	print(i, end=" ") # prints 2, 3, 4, 5

	
for i in range(2, 7, 2):
	print(i, end=" ") # prints 2, 4, 6

	
for ch in "Programming is fun!":
	print("the next character is", ch)


s = "Programming is fun!"
len_s = len(s)
for i in range(len_s):
	print("the next character is", s[i])





===================
===================

Hello World

===================
===================


print("Hello World")



===================
===================

Declaring Variables

===================
===================




Types:
------
int
float
list
tuple
dictionary
range




x = 5   # int 5 is assigned to the storage box called x

y = 5.2 # float 5.2 is assigned to the storage box called y

s = "Hello World"      # string "Hello World" is assigned to s
str = 'Hello World'    # string "Hello World" is assigned to str

counter = 100          # An integer assignment
miles   = 1000.0       # A floating point
name    = "John"       # A string

print (counter)
print (miles)
print (name)




=======================
=======================

Escape Sequences

=======================
=======================

Escape sequence Meaning
=======================


\\		\ character
\' ' character
\" " character
\n Newline
\t Horizontal tab



=======================
=======================

Printing on the Console

=======================
=======================



print ("Hello World")
print(3 * 2 + 7*3)



a = 1
b = 2
c = a/b
print(a, "/", b, "=", c)
s = str(a) + "/" + str(b) + "=" + str(c)
print(s)


resultAsString = input("What grade on the test do you want ")
print("Congrats on your " + resultAsString)
NOTE: You can not mix types when using the + operator as a join



resultAsInt = int(input("What grade on the test do you want "))
print("Congrats on your " + resultAsInt)
NOTE: You can not mix types when using the + operator as a join
      So, the second statement would give you an exception (crash)
resultAsInt = int(input("What grade on the test do you want "))
print("Congrats on your " + str(resultAsInt))


result = input("What city do you live in? ")
print("You live in " + result)


resultGrade = int(input("What grade did you get? "))
print(resultGrade)


resultGradeAsString = input("What grade did you get? ")
resultGradeAsInt = int(resultGradeAsString)
print(resultGradeAsInt)


song = input("What is your favorite song: ")
print(song)


band = input("What is your favorite band: ")
print(band)


name = input("What is your name? ")
age = int(input("What is your age? "))
ageOlder = age+25
print("Hi", name, "! In 25 years you will be", ageOlder, "!")




====================
====================

Loops

====================
====================



num = int(input("Tell me a number: "))
for i in range(num):
	print("Hello")


range(5) is equivalent to range(0, 5)
range(2,6)—2,3,4,5
range(6,2)—no values
range(2,8,2)—2,4,6
range(2,9,2)—2,4,6,8
range(6,2,-1)—6,5,4,3



for ch in "Programming is fun!":
	print("the next character is", ch)


s = "Programming is fun!"
len_s = len(s)
for i in range(len_s):
	print("the next character is", s[i])


	
secret = "code"
guess = input("Guess a word: ")
tries = 1
while guess != secret:
	print("You tried to guess", tries, "times")
	guess = input("Guess again: ")
	tries += 1
print("You got it!")



 
====================
====================

Creating Functions or Methods

====================
====================



Example 1:
----------

def printEndOfLine( ):
	print (end="")
	return
	
	
# call statement
print("Hello World")
printEndOfLine( )


Example 2:
----------

def printStars( ):
	print ("***********************")
	return
	
	
# call statement
printStars( )  




	


 
=================================
=================================

Functions with Arguments

=================================
=================================




Example 1:
----------

def printStr( str ):
	print (str)
	return
	
	
# call statement
print("Hello World")




Example 2:
----------

def sqr( number ):
	x = number * number
	return x

	
# call statement
print( sqr(3))  # prints 9




Example 3:
----------

def modifyList( list, index, value ):
	list[index] = value
	return
	
# call statement
myList = [1, 1, 2, 3, 5]
modifyList(myList, 5, 8)






 
=================================
=================================

Built in Functions

=================================
=================================



Built in functions:
-------------------
abs, divmod, cmp, coerce, float, hex, int, max, min, oct,
pow, round




The math module
---------------
from math import *

acos, asin, atan, atan2, ceil, cos, cosh, e, exp, fabs, floor, fmod,
frexp, hypot, ldexp, log, log10, mod, pi, pow, sin, sinh, sqrt, tan,
tanh


NumPy has a lot more at www.scipy.org



Support for Complex Numbers are built in.
-----------------------------------------

Use j for the square root of -1

(3+2j)

import cmath

acos, acosh, asin, asinh, atan, atanh, cos, cosh, e, exp, log, log10,
pi, sin, sinh, sqrt, tan, tanh.

import cmath
cmath.sqrt(-1)
1j



=================================
=================================

Lists (Arrays)

=================================
=================================



NOTE: Strings are really just Lists of characters,
      so all of these commands work with Strings 
	  as well.
	  
	  
Example 1:
----------
fiboList = [1, 1, 2, 3, 5, 8, 13]


#slicing:
---------
print(fiboList[0])   # prints 1
print(fiboList[1])   # prints 1
print(fiboList[2])   # prints 2
print(fiboList[5])   # prints 8
print(fiboList[6])   # prints 13
print(fiboList[0:7]) # prints [1, 1, 2, 3, 5, 8, 13]
print(fiboList[2:7]) # prints [2, 3, 5, 8, 13]
print(fiboList[2:4]) # prints [2, 3]


#modifying:
-----------
fiboList[0] = 0
fiboList[7] = 21



Methods for a List:
-------------------
	fiboList.count(1)      # returns 2
	fiboList.index(1)      # returns 0
	fiboList.index(2)      # returns 2
	fiboList.remove(2)     # 2 is gone
	fiboList.insert(2, 2)  # 2 is back
	fiboList.reverse()     # it is reversed
	fiboList.reverse()     # original order is back
	fiboList.sort()        # sorts small to large
	fiboList.append( 89 )  # adds new element to end of list
	fiboList.pop( )        # removes and returns last element in list
	fiboList.insert(0, 1)  # inserts a new element at position 0

	
functions:
----------
	len(fiboList)     # returns 7
	max(fiboList)     # returns 13
	min(fiboList)     # returns 1
	  
	  
	  
	del fiboList[2]
	fiboList + [21, 34, 55]  # concatenation
	  


Example 2:
----------

vowelList = ["a", "e", "i", "o", "u"]

if "a" in vowelList:
	print ("a is a vowel")

	
# the for loop below prints a e i o u
for x in vowelList:
	print(x, end=" ");	

	
# prints [a, e]
print (vowelList[0:2])


Example 3:
----------

courseList = ["Computer Science", "Algebra"]

# the for loop below prints 
# Computer Science Algebra

for x in courseList:
	print(x, end=" ");	

# prints Computer Science
print (courseList[0])

	



=================================
=================================

Tuples (Immutable Lists)

=================================
=================================


	  

Tuples are basically immutable Lists.
The parenthesis are optional.  You could
represent a point with a tuple.

	  
Example 1:
----------
fiboList = (1, 1, 2, 3, 5, 8, 13)

print(fiboList[0])  # prints 1
print(fiboList[1])  # prints 1
print(fiboList[2])  # prints 2
print(fiboList[5])  # prints 8
print(fiboList[6])  # prints 13
print(fiboList[0:7]) # prints [1, 1, 2, 3, 5, 8, 13]





Methods for a Tuple:
-------------------
	fiboList.count(1)      # returns 2 for # of 1's 
	fiboList.index(1)      # returns 0 index of 1st 1
	fiboList.index(2)      # returns 2 index of 2 is 2


	
functions:
----------
	len(fiboList)     # returns 7
	max(fiboList)     # returns 13
	min(fiboList)     # returns 1
	  
	  
	  
	del fiboList[2]  # error
	fiboList + [21, 34, 55]  # concatenation
	  


Example 2:
----------

vowelList = "a", "e", "i", "o", "u"

if "a" in vowelList:
	print ("a is a vowel")

	
# the for loop below prints a e i o u
for x in vowelList:
	print(x, end=" ");	

	
# prints (a, e)
print (vowelList[0:2])



Example 3:
----------

courseList = ("Computer Science", "Algebra")

# the for loop below prints 
# Computer Science Algebra

for x in courseList:
	print(x, end=" ");	

#prints Computer Science
print (courseList[0])

	



=================================
=================================

Dictionary

=================================
=================================


	  

A dictionary has key-value pairs.
The keys cannot be changed, but the
values can be changed.

	  
Example 1:
----------
dictionary = ['House':'Casa', 'Hi':'Hola', 'You':'Tu']

len(dictionry)  # returns 3

print(dictionary['House'])  # prints Casa
print(dictionary['Hi'])     # prints Hola
print(dictionary['You'])    # prints Tu

del dictionary['House']  # removes entry with key 'House'

dictionary.clear() # clears the dictionary

dictionary.has_key('Hi')  # returns True

dictionary.keys()  # returns a list of all of the keys

dictionary.values()  # returns a list of all of the values


for word in dictionary.keys():
	print(word, dictionary[word])
	
	
for word in dictionary.values():
	print(word)
	


Example 2:
----------






Example 3:
----------


	


=================================
=================================

Lists 2D (Arrays 2D)

=================================
=================================




Example 1:
----------

print("Two Dimensional Arrays")
print()
print()



a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(a[0])  # prints row 0 elements [1, 2, 3]
print(a[1])  # prints row 1 elements [4, 5, 6]
print(a[2])  # prints row 2 elements [7, 8, 9]


print(a[0][0])  # prints row 0 col 0 element
print(a[0][1])  # prints row 0 col 1 element
print(a[0][2])  # prints row 0 col 2 element


for r in range(len(a)):
	for c in range(len(a[r])):
		print(a[r][c], end=' ') # stay on row
	print() # move to next row


print()
print()

# Another way (for each loop)
for row in a:
    for element in row:
        print(element, end=' ') # stay on row
    print() # move to next row

print()
print()



Example 2:
----------

n = 3
m = 4
a = []
for i in range(n):
    a.append([0] * m)



# the first line of input is the number of rows of the array
n = int(input()) 
a = []
for i in range(n):
    row = input().split()
    for i in range(len(row)):
        row[i] = int(row[i])
    a.append(row)

    



=================================
=================================

Classes

=================================
=================================




Example 1:
----------

class Student:
	
	# constructor to initialize instance variables
	def __init__(self, firstName, lastName, id, grade):
		# instance variables created and assigned a value
		self.firstName = firstName
		self.lastName = lastName
		self.id = id
		self.grade = grade
		
	def getFirstName(self):
		return self.firstName
			
	def getLastName(self):
		return self.lastName

	def getName(self):
		return self.firstName + " " + self.lastName
		
	def getGrade(self):
		return self.grade

	def setGrade(self, grade):
		self.grade = grade
		

student1 = Student("Tom", "Baker", "76788", 95)
student2 = Student("Sue", "Smart", "66549", 100)
		
print("Student 1 is " + student1.getName())
print("Student 2 is " + student2.getName())
			
# create an empty array
studentList = []

# append a Student object to the list
studentList.append(student1)

# append a Student object to the list
studentList.append(student2)


# now print out the students
# using a for each loop
print()
for student in studentList:
        print("%-15s  %4d" % (student.getName(), student.getGrade()), sep="")
print()



# now print out the students using the
# studentList reference and indexing
print()
for i in range(len(studentList)):
        print("%-15s  %4d" % (studentList[i].getName(), studentList[i].getGrade()), sep="")
print()


	
	
Example 2:
----------

class Point:

	def __init__(self, x, y):
		self.x = x
		self.y = y
		
	def getX(self):
		return self.x
		
	def getY(self):
		return self.y
	

class Line:
	def __init__(self, p1, p2):
		self.p1 = p1
		self.p2 = p2
		
	def getSlope(self):
		if self.p1.getX() == self.p2.getX():
			return "Undefined"
		return  (self.p1.getY() - self.p2.getY()) / (self.p1.getX() - self.p2.getX())
    
point1 = Point(3, 5)
point2 = Point(6, 7)


	


=================================
=================================

Reading from the Console

=================================
=================================




firstName = input(" First Name: ")
lastName  = input(" Last Name: ")
age = int(input("Age: "))


x = int(input("Enter a first number: "))
y = int(input("Enter a second number: "))


var1, var2 = input("enter two numbers (separate with a space):").split()
print(var1)
print(var2)

var = input("enter two numbers (separate with a space or a comma):")
var = var.strip()            # strip off leading and trailing white space
var = var.replace(",", " ")  # replace any comma with a space
var = var.replace("   "," ") # replace 3 spaces with a single space
var = var.replace("  "," ")  # replace 2 spaces with a single space
var1, var2 = var.split()     # now split at the space


NOTE: raw_input("Enter your name: ")
      does NOT exist in Python 3


=================================
=================================

if else statements

=================================
=================================



x = int(input("Enter a first number: "))
y = int(input("Enter a second number: "))
if x > 0:
	print("Your number is positive.")
if x < 0:
	print("Your number is negative.")
if x == 0:
	print("Your number is zero.")

if x < 0 and y < 0:
	print("both negative")


if type(x) != int or type(y) != int:
	print("You did not enter integers")
elif x > 0 and y > 0:
	print("both numbers are positive")
elif x < 0 and y < 0:
	print("both numbers are negative")
else:
	print("numbers have opposite sign")




=================================
=================================

string

=================================
=================================



"Hello World"  # this is a string ""

'Hello World'  # this is a string '


Functions:
----------

s = "Hello World"

len(s)                # returns 11  


String methods:
---------------

s = "Hello World"

x = s.find("lo")      # returns 3

x = s.find("Lo")      # returns -1

b = s.isdigit()       # returns true  or false

b = s.isnumeric()     # returns true or false

s = s.lower()         # returns all lower case

s = s.upper()         # returns all upper case

s = s.strip()         # strips white space 

s2 = s[2:5]           # returns "llo"

s2 = s[6:]            # returns "World"

var str = "12 17 5"
print (str.split( ))  # prints ['12', '17', '5']

str = "12,17,5"
print (str.split(',',1)) # prints ['12', '17', '5']



=================================
=================================

Reading from and Writing to files

=================================
=================================




Example 1:
----------

# Open a file
fo = open("foo.txt", "w")
fo.write( "Python is a great language.\nYeah its great!!\n")

# Close opend file
fo.close()



Example 2:
----------

# Open a file
fo = open("foo.txt", "r")

str = fo.read()
print ("Read String is : ", str)

# Close opened file
fo.close()



Example 3:
----------

# Open a file
fo = open("foo.txt", "r")
for line in fo:
    print(line, end='\n')
# Close opened file
fo.close()







================
================

Creating Objects

================
================



Example 1:
----------

class Employee:
   'Common base class for all employees'
   empCount = 0

   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
   
   def displayCount(self):
     print ("Total Employee %d" % Employee.empCount)

   def displayEmployee(self):
      print ("Name : ", self.name,  ", Salary: ", self.salary)


#This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
#This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)




Example 2:
----------

class JustCounter:
   __secretCount = 0  # similar to a private variable __
  
   def count(self):
      self.__secretCount += 1
      print (self.__secretCount)

counter = JustCounter()
counter.count()
counter.count()
print (counter.__secretCount)




Example 3:
----------

class Parent:        # define parent class
   
   parentAttr = 100
   
   def __init__(self):
      print ("Calling parent constructor")

   def parentMethod(self):
      print ('Calling parent method')

   def setAttr(self, attr):
      Parent.parentAttr = attr

   def getAttr(self):
      print ("Parent attribute :", Parent.parentAttr)

class Child(Parent): # define child class
   def __init__(self):
      print ("Calling child constructor")

   def childMethod(self):
      print ('Calling child method')

c = Child()          # instance of child
c.childMethod()      # child calls its method
c.parentMethod()     # calls parent's method
c.setAttr(200)       # again call parent's method
c.getAttr()          # again call parent's method



Example 4:
----------

class Parent:        # define parent class
   def myMethod(self):
      print ('Calling parent method')

class Child(Parent): # define child class
   def myMethod(self):
      print ('Calling child method')

c = Child()          # instance of child
c.myMethod()         # child calls overridden method






Simple Programs-Reading from the Console

===================
===================




resultGrade = int(input("What grade did you get? "))
print(resultGrade)







===================
===================
A Simple Program
===================
===================




===================
===================
A Simple Program
===================
===================



===================
===================
A Simple Program
===================
===================



===================
===================
A Simple Program
===================
===================





=================================
=================================

PyGame


=================================
=================================



import pygame, sys
from pygame.locals import *

# Set up pygame.
pygame.init()

# Set up the window.
windowSurface = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption('Hello world!')

# Set up the colors.
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# Set up fonts.
basicFont = pygame.font.SysFont(None, 48)

# Set up the text.
text = basicFont.render('Hello world!', True, WHITE, BLUE)
textRect = text.get_rect()
textRect.centerx = windowSurface.get_rect().centerx
textRect.centery = windowSurface.get_rect().centery

# Draw the white background onto the surface.
windowSurface.fill(WHITE)

# Draw a green polygon onto the surface.
pygame.draw.polygon(windowSurface, GREEN, ((146, 0), (291, 106), (236, 277), (56, 277), (0, 106)))

# Draw some blue lines onto the surface.
pygame.draw.line(windowSurface, BLUE, (60, 60), (120, 60), 4)
pygame.draw.line(windowSurface, BLUE, (120, 60), (60, 120))
pygame.draw.line(windowSurface, BLUE, (60, 120), (120, 120), 4)

# draw a blue circle onto the surface.
pygame.draw.circle(windowSurface, BLUE, (300, 50), 20, 0)

# Draw a red ellipse onto the surface.
pygame.draw.ellipse(windowSurface, RED, (300, 250, 40, 80), 1)

# Draw the text's background rectangle onto the surface.
pygame.draw.rect(windowSurface, RED, (textRect.left - 20, textRect.top - 20, textRect.width + 40, textRect.height + 40))

# Get a pixel array of the surface.
pixArray = pygame.PixelArray(windowSurface)
pixArray[480][380] = BLACK
del pixArray

# Draw the text onto the surface.
windowSurface.blit(text, textRect)

# Draw the window onto the screen.
pygame.display.update()

# Run the game loop.
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()






	
import pygame, random, sys

from pygame.locals import *



WINDOWWIDTH = 600 
WINDOWHEIGHT = 600 
TEXTCOLOR = (0, 0, 0) 
BACKGROUNDCOLOR = (255, 255, 255) 
FPS = 60 
PLAYERMOVERATE = 5

playerX = WINDOWWIDTH/2
playerY = WINDOWHEIGHT/2

moveLeft = False
moveRight = False
moveUp = False
moveDown = False



# quit the program
def terminate(): 
    pygame.quit()
    sys.exit()

	
# wait on welcome screen
def waitForPlayerToPressKey():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE: 
                    terminate()
                return
				

				
def setMoveToAllFalse():
    global moveLeft
    global moveRight
    global moveUp
    global moveDown
    
    moveLeft = moveRight = moveUp = moveDown = False
    return

	
def drawText( text, font, surface, x, y):
    textobj = font.render( text, 1, TEXTCOLOR)
    textrect = textobj.get_rect()
    textrect.topleft = (x, y)
    surface.blit( textobj, textrect)



pygame.init()

mainClock = pygame.time.Clock()


# windowSurface represents the monitor
# you can also add , pygame.FULLSCREEN)
# but reset playerX and playerY

windowSurface = pygame.display.set_mode(( WINDOWWIDTH, WINDOWHEIGHT))

pygame.display.set_caption(' Your Title ')

pygame.mouse.set_visible( False)

font = pygame.font.SysFont( None, 48)

# gameOverSound = pygame.mixer.Sound('gameover.wav')

# play background music
# pygame.mixer.music.load('background.mid')

# load the player's image
playerImage = pygame.image.load('android.png')

playerRect = playerImage.get_rect()


# Show the "Start" screen

windowSurface.fill( BACKGROUNDCOLOR)

drawText(' My Game ', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))

drawText(' Press a key to start. ', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 2))


pygame.display.update() # draw the screen on the monitor

waitForPlayerToPressKey()  # wait for a key press



while True:

    # Set up the start of the game.
    score = 0
    playerRect.topleft = (playerX, playerY)
    setMoveToAllFalse()
	
    # play the background music
    # pygame.mixer.music.play(-1, 0.0)

    finished = False;
    while not finished: 
        # The game loop runs while the game part is playing.
        score += 1

        # moveLeft = moveRight = moveUp = moveDown = False
        # setMoveToAllFalse()
        
        for event in pygame.event.get():
		
            if event.type == QUIT:
                terminate()
		
            if event.type == KEYDOWN:
                if event.key == K_LEFT or event.key == K_a:
                    setMoveToAllFalse()
                    moveLeft = True
                if event.key == K_RIGHT or event.key == K_d:
                    setMoveToAllFalse()
                    moveRight = True
                if event.key == K_UP or event.key == K_w:
                    setMoveToAllFalse()
                    moveUp = True
                if event.key == K_DOWN or event.key == K_s:
                    setMoveToAllFalse()
                    moveDown = True
                if event.key == K_ESCAPE:
                    finished = True
                    
            #if event.type == MOUSEMOTION:
            #    playerRect.centerx = event.pos[0]
            #    playerRect.centery = event.pos[1]


        # Move the player around
        if moveLeft and playerRect.left > 0:
            playerX = playerX - 5
            playerRect.topleft = (playerX, playerY)

        if moveRight and playerRect.right < WINDOWWIDTH:
            playerX = playerX + 5
            playerRect.topleft = (playerX, playerY)
        if moveUp and playerRect.top > 0:
            playerY = playerY - 5
            playerRect.topleft = (playerX, playerY)
        if moveDown and playerRect.bottom < WINDOWHEIGHT:
            playerY = playerY + 5
            playerRect.topleft = (playerX, playerY)


        # Draw the game world on the window.
        windowSurface.fill( BACKGROUNDCOLOR)

        # Draw the score.
        drawText(' Score: %s' % (score), font, windowSurface, 10, 0)
		
        # Draw the player's rectangle.
        windowSurface.blit( playerImage, playerRect)
		
        # update the monitor
        pygame.display.update()

        mainClock.tick(FPS)

        if score >= 2000:
            break

    # Stop the game and show the "Game Over" screen.

    # pygame.mixer.music.stop()
    # gameOverSound.play()

    drawText(' GAME OVER', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
    drawText(' Press a key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
    pygame.display.update()
    waitForPlayerToPressKey()
    # gameOverSound.stop()





Other commands:

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)



windowSurface.fill( WHITE)

pygame.draw.line( windowSurface, BLUE, (60, 60), (120, 60), 4)

pygame.draw.circle( windowSurface, BLUE, (300, 50), 20, 0)

pygame.draw.ellipse( windowSurface, RED, (300, 250, 40, 80), 1)

pygame.draw.rect( windowSurface, RED, (20, 20, 40, 40))

pygame.draw.polygon( windowSurface, GREEN, (( 146, 0), (291, 106), (236, 277), (56, 277), (0, 106)))



pixArray = pygame.PixelArray( windowSurface)
pixArray[480][380] = BLACK
del pixArray


# update the monitor
pygame.display.update()







=================================
=================================

Labs


=================================
=================================

Quad Form

Area of a Rectangle

Volume of a Sphere

Roman Numerals

Fibonacci

Student Grades
(average, standard deviation, semester grades, ...)

Tic-Tac-Toe

Hangman

Encrypt Data

Magic Squares


Matrix Battle:


Checkers:



Tax Table