Introduction to Web Programming

CIS 1415


This course introduces the student to the essential concepts and skills of computer programming by using Python. Students learn about data representation, algorithms, program logic, and structured and object oriented programming. Students develop their skills through application of these ideas using flowcharts, pseudocode, design, coding, and testing.

Project B1: American Flag with Turtle

Code: Project B1: American Flag with Turtle 

"""


Assessment B : Project 1

Name: Jasmine Keola

Course: CIS 1415-55

Date: 10/27/2021

Description: Draw American flag with Turtle


"""


from turtle import *


# set variables

t = Turtle()

t.speed(5000)

t.screen = Screen()

t.screen.colormode(255)

t.screen.bgcolor(200, 200, 200)

red = (178, 34, 52)

white = (255, 255, 255)

blue = (60 ,59, 110)


def stripes(level):

    """Creates stripes of American Flag.""" 

    count = 0

    stripeHeight = 26

    angle = 90

    # set long stripe variables

    if(level == 1):

        # starting coordinates

        x = -321

        y = -169

        stripes = 6

        width = 642

    # set short stripe variables

    elif(level == 2):

        # starting coordinates

        x = -64.1875

        y = -13

        stripes = 7

        width = 385.1875    

    # loop creates multiple stripes   

    for line in range(stripes):

        moveTurtle(x, y, 0)

        # odd stripes are red

        if(count % 2 == 0):

            t.color(red)

            t.fillcolor(red)

        # even stripes are white

        else:

            t.color(white)

            t.fillcolor(white)

        t.begin_fill() 

        # draws a single stripe

        for line in range(2):

            t.forward(width)

            t.left(angle)

            t.forward(stripeHeight)

            t.left(angle)

        t.end_fill()

        # increment count for stripe color

        count += 1

        # increment count for stripe location

        y += 26

    

def moveTurtle(x, y, z):

    """Pickup turtle, move, put down, and face in a direction."""

    t.up()

    t.goto(x, y)

    t.down()

    t.setheading(z)


def blueBox():

    """Creates the blue box on an American flag."""

    x = -321

    y = -13

    blueWidth = 256.8125

    blueHeight = 182

    moveTurtle(x, y, 90)

    # set blue fill color

    t.color(blue)

    t.fillcolor(blue)

    t.begin_fill()

    # create blue box

    for count in range(2):

        t.forward(blueHeight)

        t.right(90)

        t.forward(blueWidth)

        t.right(90)

    t.end_fill()


def star(level):

    """Creates stars on an American flag."""

    # star dimensions

    size = 8

    diameter = 20.8

    angle = 144

    # odd star row location start

    if(level == 1):

        x = -295

        y = 153.9

        row = 5

        col = 6

    # even star rows location start  

    elif(level == 2):

        x = -274.2

        y = 136.1

        row = 4

        col = 5

    # create multiple rows

    for r in range(row):

        # creates a single row

        for c in range(col):

            moveTurtle(x, y, 0)

            # set star fill color

            t.color(white)

            t.fillcolor(white)

            t.begin_fill()

            # create a star

            for edge in range(5):

                t.forward(size)

                t.right(angle)

                t.forward(size)

                t.right(72 - angle)

            t.end_fill()

            # incrememnt star x location, each column is spaced by twice the diameter of one star

            x += diameter * 2

        # reset x to first x location

        x -= diameter * 2 * col

        # increment y location each, each row is spaced by less than half of twice the diameter of one star

        y -= 36

        

def main():

    stripes(1)

    stripes(2)

    blueBox()

    star(1)

    star(2)

    

main()

t.hideturtle()

Project B2: Hangman

Code: Project B2: Hangman

"""


Assessment B : Project 2

Name: Jasmine Keola

Course: CIS 1415-55

Date: 10/28/2021

Description: Hangman game


"""


import random


wordList = ["engineer", "systematic", "strange", "pepper",

            "profile", "combination", "horoscope", "trance",

            "performance", "occasion", "flower", "carpet",

            "cruelty", "sympathetic", "sample", "ignite",

           "arrogant", "parade", "attraction","conflict"]


dictionary = {"title":"\nGame: Hangman", "description":"\nWelcome to Hangman! A random word has been selected.\n\

Guess the word by choosing one letter at a time.\nYou have six guesses. Good luck!\n",

              "correct":"***That letter is correct!***", "incorrect":"***That letter is not correct, try again!***",

              "win":"Congratulations you won!!!", "lose":"You are out of guesses. Game over!",

              "guessed":"***That letter has been guessed, try again!***", "invalid":"***Invalid entry, enter a letter.***", "border":'='*50, "finalBorder":'*'*50}

     

# randomly select a word from wordList

word = random.choice(wordList)

# split word into letters

letterList = list(word)

# create a list of _'s for each letter in word.

finalList = list('_'* len(word))

tries = 6

guessList = []


print(dictionary["title"])

print(dictionary["description"], "\nLength of word:", len(word))

print(' '.join(finalList), '\n')

print(dictionary["finalBorder"])



# start game loop

while True:

    # stop the game

    if(tries == 0):

        print(dictionary["border"], "\n")

        print(dictionary["lose"], "\n")

        print(dictionary["finalBorder"])

        break

    # if an '_' is not in the final list, all letters are guessed, player wins, game ends

    if('_' not in finalList):

        print(dictionary["border"], "\n")

        print(dictionary["win"])

        print("Finished word:", ''.join(finalList), "\n")

        print(dictionary["finalBorder"])

        break

    # text prompt and borders

    print(dictionary["border"])

    print("Word:", ' '.join(finalList))

    print("Turns:", tries)

    guess = input("Guess a letter: ")

    # convert guess to lower case

    guess = guess.lower()

    # if letter has already been guessed print guessed letter

    if(guess in guessList):

        print("Guessed letters:", ' '.join(guessList))

    # if letter is not alpha

    elif(guess.isalpha() == False):

        print(dictionary["invalid"])

    # if letter is valid and not guessed yet

    else:

        # add guessed letter to guessList

        guessList.append(guess)

        # if guess is correct/matches a letter in selected word

        if(guess in letterList):

            print(dictionary["correct"])

            # create a list of indexes(letter position) that match between lists.

            # required for words with multiples of one letter

            occurrences = lambda x, lyst: (y for y, z in enumerate(lyst) if z == x)

            indexes = list(occurrences(guess, letterList))

            # loop that replaces each '_' in final word with correctly guessed letter 

            for index in indexes:

                finalList[index] = guess

        # if guessed letter is incorrect/doesn't match a letter in selected word

        else:

            print(dictionary["incorrect"])

            tries -= 1

Project B3: Number Guessing

Code: Project B3: Number Guessing

"""


Assessment B : Project 3

Name: Jasmine Keola

Course: CIS 1415-55

Date: 10/29/2021

Description: Number Guessing


"""


import random


# generate 4 random digits

# could not do this in the loop or number would change with each guess.

digit1 = str(random.randint(0,9))

digit2 = str(random.randint(0,9))

digit3 = str(random.randint(0,9))

digit4 = str(random.randint(0,9))


# input loop

while True:

    # create a list of the random digits

    numList = list(digit1 + digit2 + digit3 + digit4)

    # set/reset the correct guessed number list

    correctList = []

    print('='*50)

    guess = input("Guess a 4-digit number(0000 - 9999)\nPress 'Enter' to quit: ")

    # if guess is not a number or is not 4 digits.

    if(guess.isnumeric() == False or len(guess) > 4 or len(guess) < 4):

        print("***Please enter a 4-digit number(0000 - 9999)***")

    # 'Enter' to quit game

    elif(guess == ''):

        break

    # Or quit game if correct number is guesseted

    else:

        # split guessed number into a list of each digit

        guessList = list(guess)

        # check positions of correct number vs guessed number 

        for num in range(4):

            # if numbers at a position match, add to the correctList

            if(numList[num] == guessList[num]):

                correctList.append(guessList[num])

        # if 4 numbers match, stop loop, the game is won

        if(len(correctList) == 4):

            print("Congratulations!!! You guessed the correct number:",  ''.join(numList))

            print('*'*55)

            break

        # otherwise print the number of correct numbers guessed

        else:

            # grammar for singular vs multiple

            if(len(correctList) == 1):

                print(len(correctList), "number is correct.")

            else:

                print(len(correctList), "numbers are correct.")

            # if at least one number is right, print the list of correct numbers guessed

            if(len(correctList) > 0):

                print("Numbers in the right spot:", ', '.join(correctList))

Breakout with Pygame

Code: Breakout with Pygame

import pygame

from pygame.locals import *



BLACK = (0,0,0)

GRAY = (75,75,75)

WHITE = (255,255,255)



    

class GameScreen(object):

    def __init__(self, w, h):

        pygame.init()

        self.width = w

        self.height = h


        self.screen  = pygame.display.set_mode((w,h))

        self.caption = pygame.display.set_caption("Breakout")

        self.icon = pygame.transform.scale(pygame.image.load("assets/images/icon.png"), (20, 20))

        

        self.fps = 60

        self.clock = pygame.time.Clock()      

        

        self.font = 'assets/fonts/ARCADE.TTF'

        self.life = pygame.transform.scale(pygame.image.load('assets/images/heart.png'), (32, 29))

        self.bg = pygame.image.load("assets/images/background.jpg")

        self.scoreScreen = False

        self.clicked = False

        self.intro = True

        

        pygame.display.set_icon(self.icon)       

        

    

    def drawText(self, text, font, size, color, x, y):

        fnt = pygame.font.Font(font, size)

        self.screen.blit(fnt.render(text, 1, color), (x,y))

         

         

    def setBackground(self):

        self.screen.fill(BLACK)

        pygame.draw.line(self.screen, GRAY, [0, 50], [self.width,50] , 2)

        

        

    def introScreen(self):

        self.screen.blit(self.bg,(0,0))

        self.drawText("BREAKOUT", self.font, 100, WHITE, (self.width / 2 - 200), 150)

        self.drawButton()

        

        

    def startMusic(self):  

        pygame.mixer.music.load("assets/sounds/Darker_Waves.ogg")

        pygame.mixer.music.play(-1)

        pygame.mixer.music.set_volume(0.1)        

        

        

    def displayLives(self, b):

        for i in range(b.lives):

            self.screen.blit(self.life,(self.width - (40 + 37 * i),(10)))

        self.drawText("Lives: ", self.font, 32, WHITE, self.width - 200, 12)

        

        

    def setScore(self, score):

        self.drawText("Score: " + str(score), self.font, 32, WHITE, 10, 12)        



    def setHighScore(self, points):

        while True:

            self.name = input("Enter initials: ")

            if(len(self.name) > 3 or len(self.name) < 3):

                print("Must enter 3 characters.")

            else:

                break     

        self.score = (self.name + ' '*5 + str(points))

        f = open("scoresList.txt",'a')

        f.write(self.score + '\n')

        f.close()

        self.scoreScreen = True

      

        

    def getHighScores(self):

        y = 225

        count = 0

        self.sortedList = []

        #displays text on score screen

        self.drawText("PRESS SPACE TO CONTINUE", self.font, 32, WHITE, (self.width / 2 - 190), 15)         

        self.drawText("HIGH SCORES", self.font, 50, WHITE, (self.width / 2 - 140), 150)

        self.drawText(("Player" + ' '*5 + "Score"), self.font, 40, WHITE, (self.width / 2 - 150), y)

       

        #open file and reads score list

        f = open("scoresList.txt", 'r')        

        self.highScores = f.readlines()

        f.close()

        #reverse sorts the score list

        self.highScores = sorted(self.highScores, key=lambda x: int(x[8:][:-1]), reverse = True)

        #strips new line character

        for element in self.highScores:

            self.sortedList.append(element.strip())


        #displays a numbered list of top 10 scores

        for line in self.sortedList:

            count +=1

            if(count < 11):

                y += 32

                print(str(count) + '. ' + str(line))

                self.drawText(str(count) + '. ' + str(line), self.font, 40, WHITE, (self.width / 2 - 150), y)


    def drawButton(self):

        self.button_w = 201

        self.button_h = 57

        self.start = pygame.transform.scale(pygame.image.load('assets/images/start.png'), (self.button_w, self.button_h))

        self.hover = pygame.transform.scale(pygame.image.load('assets/images/hover.png'), (self.button_w, self.button_h))

        

        self.x = self.width / 2 - (self.button_w / 2)

        self.y = self.height * (3/4)

        self.rect = Rect(self.x, self.y, self.button_w, self.button_h)   

           

        mouse = pygame.mouse.get_pos()  

        

        for click in pygame.event.get():          

            if(click.type == pygame.QUIT):

                pygame.quit()              

            if(click.type == pygame.MOUSEBUTTONDOWN):              

                if(self.x <= mouse[0] <= self.x + self.button_w and self.y <= mouse[1] <= self.y + self.button_h):

                    self.clicked = True

                    self.intro = False

                        

        if(self.x <= mouse[0] <= self.x + self.button_w and self.y <= mouse[1] <= self.y + self.button_h):

            self.screen.blit(self.hover, self.rect)

          

        else:

            self.screen.blit(self.start, self.rect)    

             


    def update(self):

        self.setBackground()

        self.clock.tick(self.fps)

_____________________________________________________________________________________________________________________


import pygame

from pygame.locals import *



class Ball(object):

    def __init__(self, w, h, x, y, radius, sp_x, sp_y):

        self.screen_w = w

        self.screen_h = h

        self.resetBall(x, y, radius, sp_x, sp_y)

        self.points = 0

        self.lives = 3

        

        self.brickHit = pygame.mixer.Sound("assets/sounds/clink-high.mp3")  

        self.paddleHit = pygame.mixer.Sound("assets/sounds/clink-low.mp3")   

        self.loss = pygame.mixer.Sound("assets/sounds/lose.wav")

        self.win = pygame.mixer.Sound("assets/sounds/win.mp3")

        

        

    def draw(self,g):

        g.screen.blit(self.ball, self.cir)

        

       

    def move(self, p, w, g):

        collisionThresh = 5        

        wallDestroyed = 1

        rowCount = 0

        #checking if ball collides with blocks in wall

        for row in w.blocks:

            itemCount = 0

            for item in row:

                if(self.cir.colliderect(item[0])):

                    self.points += 10

                    pygame.mixer.Sound.play(self.brickHit)

                    #checking top collision

                    if(abs(self.cir.bottom - item[0].top) < collisionThresh and self.speed_y > 0):

                        self.speed_y *= -1

                    #checking bottom collision

                    if(abs(self.cir.top - item[0].bottom) < collisionThresh and self.speed_y < 0):

                        self.speed_y *= -1

                    #checking left collision

                    if(abs(self.cir.right - item[0].left) < collisionThresh and self.speed_x > 0):

                        self.speed_x *= -1

                    #checking right collision

                    if(abs(self.cir.left - item[0].right) < collisionThresh and self.speed_x < 0):

                        self.speed_x *= -1

                    #reduce block strength

                    if(w.blocks[rowCount][itemCount][1] > 1):

                        w.blocks[rowCount][itemCount][1] -= 1

                    else:

                        w.blocks[rowCount][itemCount][0] = (0,-100,0,0)

                #check each block to see if wall is destroyed

                if(w.blocks[rowCount][itemCount][0] != (0,-100,0,0)):

                    wallDestroyed = 0

                

                itemCount += 1

            rowCount += 1

            

            #player has won the game

            if(wallDestroyed == 1):

                self.gameOver = 1

                pygame.mixer.Sound.play(self.win)

                           

        #outer wall collisions

        if(self.cir.left < 0 or self.cir.right > self.screen_w):

            self.speed_x *= -1

        if self.cir.top < 50:

            self.speed_y *= -1

        if(self.cir.bottom > self.screen_h):

            self.lives -= 1

            #kept losing two lives at once for no apparenet reason except changing different values(row, cols, ball speed)

            pygame.time.delay(200)

            self.gameOver = -1     

            

       #game over

        if(self.lives <= 0):

            self.gameOver= -2

            pygame.mixer.Sound.play(self.loss)

        

        self.cir.x += self.speed_x

        self.cir.y += self.speed_y

        

        #check for collisions with paddle

        if(self.cir.colliderect(p)): 

            #checks for collision with paddle top - collision thresh keep ball from getting stuck in paddle

            pygame.mixer.Sound.play(self.paddleHit)

            if(abs(self.cir.bottom - p.rect.top) < collisionThresh and self.speed_y > 0):

                self.speed_y *= -1

                #increases speed(up to 5) if paddle moves in same direction as the ball

                self.speed_x += p.direction            

                if(self.speed_x > self.speedMax):

                    self.speed_x = self.speedMax

                elif(self.speed_x < 0 and self.speed_x < -self.speedMax):

                    self.speed_x = -self.speedMax

            else:

                self.speed_x *= -1


        return self.gameOver

    

    

    def resetBall(self, x, y, radius, sp_x, sp_y):

        self.ballRadius = radius

        #centers the ball on paddle

        self.x = x - self.ballRadius 

        self.y = y

        self.speed_x = sp_x

        self.speed_y = sp_y

        self.speedMax = 7   

        self.ball = pygame.transform.scale(pygame.image.load('assets/images/ball-gray.png'), (self.ballRadius * 2, self.ballRadius * 2))

        self.cir = self.ball.get_rect()

        self.cir.center = (self.x, self.y)

        self.gameOver = 0

       


    def resetGame(self):

        self.lives = 3

        self.gameOver = 0

        self.points = 0

_____________________________________________________________________________________________________________________


import pygame

from pygame.locals import *


class Paddle(object):


    def __init__(self, w, h, width, speed):

    

        self.screen_w = w

        self.screen_h = h

        

        self.paddle_w = width

        self.paddle_h = 20


        #starting location of paddle on screen

        self.x = int((self.screen_w /2) - (self.paddle_w /2))

        self.y = self.screen_h - (self.paddle_h * 2)

        

        self.paddle = pygame.transform.scale(pygame.image.load('assets/images/paddle.png'), (self.paddle_w, self.paddle_h))        

        self.rect = Rect(self.x, self.y, self.paddle_w, self.paddle_h)       

        self.speed = speed        

        self.direction = 0

        

    def move(self):

        #resets direction of paddle

        self.direction = 0

        key = pygame.key.get_pressed()

        if(key[pygame.K_LEFT] and self.rect.left > 10):

            self.rect.x -= self.speed

            self.direction = -1

        if(key[pygame.K_RIGHT] and self.rect.right < self.screen_w - 10):

            self.rect.x += self.speed

            self.direction = 1

        

    def draw(self, g):

        g.screen.blit(self.paddle, self.rect)

    

    def update(self):

        self.x = int((self.screen_w /2) - (self.paddle_w /2))

        return self.x

_____________________________________________________________________________________________________________________


import pygame

from pygame.locals import *



class Wall(object):

    def __init__(self, width, rows, cols):

                

        self.rows = rows

        if(self.rows > 10):

            self.rows = 10

        self.cols = cols

        self.width = width // cols

        self.height = 35


        self.r = pygame.transform.scale(pygame.image.load("assets/images/red.png"), (self.width, self.height))

        self.g = pygame.transform.scale(pygame.image.load("assets/images/green.png"), (self.width, self.height))

        self.b = pygame.transform.scale(pygame.image.load("assets/images/blue.png"), (self.width, self.height))

        

            

    def createWall(self):

        self.blocks = []

        singleBlock = []

        for row in range(self.rows):

            blockRow = []

            for col in range(self.cols):

                #x and y positions of blocks

                block_x = col * self.width - 50

                block_y = row * self.height + 150

                rect = pygame.Rect(block_x, block_y, self.width, self.height)

                if(row < self.rows * (1/6)):

                    strength = 3

                elif(row < self.rows * (1/2)):

                    strength = 2

                else:

                    strength = 1

                singleBlock = [rect, strength]

                blockRow.append(singleBlock)

                

            self.blocks.append(blockRow)


            

    def drawWall(self, g):

        for row in self.blocks:

            for block in row:

                #assign block color based on strength

                if(block[1] == 3):

                    img = self.b

                elif(block[1] == 2):

                    img = self.g

                elif(block[1] == 1):

                    img = self.r


                g.screen.blit(img,block[0])


_____________________________________________________________________________________________________________________


import pygame

from pygame.locals import *

from gamescreen import GameScreen

from wall import Wall

from paddle import Paddle

from ball import Ball


BLACK = (0,0,0)

WHITE = (255,255,255)

RED = (255,0,0)

GREEN = (0,255,0)




def main():

    #define variables

    w = 600

    #kept getting an error using 'w' in defining some instances but using width worked

    width = w

    h = 750

    rows = 4

    cols = 12

    paddleSpeed = 20

    paddleWidth = 175

    ballSpeed_x = 4

    ballSpeed_y = -4

    ballRadius = 10

    

    live_ball = False

    gameOver = 0

    

    #create instances

    g = GameScreen(w, h)

    p = Paddle(w, h, paddleWidth, paddleSpeed)  

    b = Ball(w, h, (p.x + paddleWidth // 2 + ballRadius), (p.y - ballRadius), ballRadius, ballSpeed_x, ballSpeed_y)

    w = Wall(w, rows, cols)

    intro = g.intro

    play = True    

    g.startMusic()

    w.createWall()

    

    #game loop

    while(play):

        #intro screen

        if(intro):

            g.introScreen()

            g.drawButton()

            if(g.clicked):

                b.resetGame()  

                w.createWall()                 

                gameOver = 0

                intro = False

                live_ball = False

                

        #if ball is active or waiting to be launched with lives remaining

        elif(gameOver == 0 or gameOver == -1):

            g.clicked = False

            g.update() 

            g.setScore(b.points)

            g.displayLives(b)

            w.drawWall(g)

            p.draw(g)

            b.draw(g)

            

            #when the ball is in play

            if(live_ball):

                p.move()

                b.move(p,w,g)         

                gameOver = b.move(p,w,g)

                

                if(gameOver != 0):

                    live_ball = False

                    #puts ball on the center of the baddle

                    b.resetBall((p.rect.x + paddleWidth // 2 + ballRadius), 

                    (p.y - ballRadius), ballRadius, ballSpeed_x, ballSpeed_y)

                

            #when the ball is in not in play

            if(not live_ball):        

                g.drawText("PRESS SPACE TO LAUNCH", g.font, 32, WHITE, (width / 2 - 190), 80)                        

           

        #if win or lose       

        elif(gameOver == -2 or gameOver == 1):      

            if(gameOver == 1):

                g.drawText("YOU WON!!!", g.font, 75, GREEN, (width / 2 - 160), 80)

            elif(gameOver == -2):

                g.drawText("GAME OVER", g.font, 75, RED, (width / 2 - 170), 80)   

                

            if(g.scoreScreen == False):                            

                g.setHighScore(b.points)

                g.screen.fill(BLACK)

                g.getHighScores()

                

        #key events       

        key = pygame.key.get_pressed()          

        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                play = False  

            #starts ball

            if(pygame.key.get_pressed()[pygame.K_SPACE] and live_ball == False):

                live_ball = True

                if(g.scoreScreen):                    

                    intro = True  

                    g.scoreScreen = False                   

                                           

        pygame.display.update()

    pygame.quit()         

     

main()

Previous Page