diff --git a/hw2/compare.py b/hw2/compare.py new file mode 100644 index 0000000..f8c6087 --- /dev/null +++ b/hw2/compare.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +""" +Created on Sun Feb 2 23:52:25 2014 + +@author: ubuntu +""" + +def comp(x,y): + if x>y: + return 1 + elif x2: + print "Holy smokes, Fermat was wrong!" + else: + print "No, that doesn't work" + +def fermatPrompt(): + a = int(raw_input("input a")) + b = int(raw_input("input b")) + c = int(raw_input("input c")) + n = int(raw_input("input n")) + fermatCheck(a,b,c,n) + +fermatPrompt() diff --git a/hw2/grid.py b/hw2/grid.py new file mode 100644 index 0000000..136a845 --- /dev/null +++ b/hw2/grid.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +""" +Created on Sun Feb 2 23:20:02 2014 + +@author: ubuntu +""" + +def makeGrid(): + print ("+"+(4*" -"+" +")*2 + 4*("\n|"+" |"*2)+"\n")*2 +"+"+(4*" -"+" +")*2 + + +def makeGrid4(): + print ("+"+(4*" -"+" +")*3 + 4*("\n|"+" |"*3)+"\n")*3 +"+"+(4*" -"+" +")*3 + +makeGrid4() \ No newline at end of file diff --git a/hw3/gene_finder.py b/hw3/gene_finder.py index 06cf000..71b6090 100644 --- a/hw3/gene_finder.py +++ b/hw3/gene_finder.py @@ -2,9 +2,13 @@ """ Created on Sun Feb 2 11:24:42 2014 -@author: YOUR NAME HERE +@author: Josh Sapers and Paul Ruvolo +(from replacement code for code lost) """ +from numpy import argmax +from random import shuffle + # you may find it useful to import these variables (although you are not required to use them) from amino_acids import aa, codons @@ -25,13 +29,29 @@ def coding_strand_to_AA(dna): returns: a string containing the sequence of amino acids encoded by the the input DNA fragment """ - - # YOUR IMPLEMENTATION HERE + retval = "" + for i in range(0,len(dna),3): + for j in range(len(codons)): + if dna[i:i+3] in codons[j]: + retval += aa[j] + break + return retval def coding_strand_to_AA_unit_tests(): """ Unit tests for the coding_strand_to_AA function """ - - # YOUR IMPLEMENTATION HERE + print "input: ATGCGA, expected output: MR, actual output: " + coding_strand_to_AA("ATGCGA") + print "input: ATGCCCGCTTT, expected output: MPA, actual output: " + coding_strand_to_AA("ATGCCCGCTTT") + +def get_complementary_base(B): + """ Returns the complementary nucleotide to the specified nucleotide. """ + if B == 'A': + return 'T' + elif B == 'C': + return 'G' + elif B == 'G': + return 'C' + elif B == 'T': + return 'A' def get_reverse_complement(dna): """ Computes the reverse complementary sequence of DNA for the specfied DNA @@ -40,13 +60,15 @@ def get_reverse_complement(dna): dna: a DNA sequence represented as a string returns: the reverse complementary DNA sequence represented as a string """ - - # YOUR IMPLEMENTATION HERE + retval = "" + for i in reversed(dna): + retval += get_complementary_base(i) + return retval def get_reverse_complement_unit_tests(): """ Unit tests for the get_complement function """ - - # YOUR IMPLEMENTATION HERE + print "input: ATGCCCGCTTT, expected output: AAAGCGGGCAT, actual output: " + get_reverse_complement("ATGCCCGCTTT") + print "input: CCGCGTTCA, expected output: CCGCGTTCA, actual output: " + get_reverse_complement("CCGCGTTCA") def rest_of_ORF(dna): """ Takes a DNA sequence that is assumed to begin with a start codon and returns @@ -56,13 +78,17 @@ def rest_of_ORF(dna): dna: a DNA sequence returns: the open reading frame represented as a string """ - - # YOUR IMPLEMENTATION HERE + retval = "" + for i in range(0,len(dna),3): + if dna[i:i+3] in ['TAG', 'TAA', 'TGA']: + break + retval += dna[i:i+3] + return retval def rest_of_ORF_unit_tests(): """ Unit tests for the rest_of_ORF function """ - - # YOUR IMPLEMENTATION HERE + print "input: ATGTGAA, expected output: ATG, actual output: " + rest_of_ORF("ATGTGAA") + print "input: ATGAGATAGG, expected output: ATGAGA, actual output: " + rest_of_ORF("ATGAGATAGG") def find_all_ORFs_oneframe(dna): """ Finds all non-nested open reading frames in the given DNA sequence and returns @@ -74,13 +100,18 @@ def find_all_ORFs_oneframe(dna): dna: a DNA sequence returns: a list of non-nested ORFs """ - - # YOUR IMPLEMENTATION HERE - + retval = [] + i = 0 + while i < len(dna): + if dna[i:i+3] == 'ATG': + retval.append(rest_of_ORF(dna[i:])) + i += len(retval[-1]) + i += 3 + return retval + def find_all_ORFs_oneframe_unit_tests(): """ Unit tests for the find_all_ORFs_oneframe function """ - - # YOUR IMPLEMENTATION HERE + print "input: ATGCATGAATGTAGATAGATGTGCCC, expected output: ['ATGCATGAATGTAGA', 'ATGTGCCC'], actual output: " + str(find_all_ORFs_oneframe("ATGCATGAATGTAGATAGATGTGCCC")) def find_all_ORFs(dna): """ Finds all non-nested open reading frames in the given DNA sequence in all 3 @@ -91,13 +122,11 @@ def find_all_ORFs(dna): dna: a DNA sequence returns: a list of non-nested ORFs """ - - # YOUR IMPLEMENTATION HERE + return find_all_ORFs_oneframe(dna) + find_all_ORFs_oneframe(dna[1:]) + find_all_ORFs_oneframe(dna[2:]) def find_all_ORFs_unit_tests(): """ Unit tests for the find_all_ORFs function """ - - # YOUR IMPLEMENTATION HERE + print "input: ATGCATGAATGTAG, expected output: ['ATGCATGAATGTAG', 'ATGAATGTAG', 'ATG'], actual output: " + str(find_all_ORFs("ATGCATGAATGTAG")) def find_all_ORFs_both_strands(dna): """ Finds all non-nested open reading frames in the given DNA sequence on both @@ -106,19 +135,20 @@ def find_all_ORFs_both_strands(dna): dna: a DNA sequence returns: a list of non-nested ORFs """ - - # YOUR IMPLEMENTATION HERE + return find_all_ORFs(dna) + find_all_ORFs(get_reverse_complement(dna)) def find_all_ORFs_both_strands_unit_tests(): """ Unit tests for the find_all_ORFs_both_strands function """ - + print "input: ATGCGAATGTAGCATCAAA, expected output: ['ATGCGAATG', 'ATGCTACATTCGCAT'], actual output: " + str(find_all_ORFs_both_strands("ATGCGAATGTAGCATCAAA")) # YOUR IMPLEMENTATION HERE def longest_ORF(dna): """ Finds the longest ORF on both strands of the specified DNA and returns it as a string""" + ORFs = find_all_ORFs_both_strands(dna) + ind = argmax(map(len,ORFs)) + return ORFs[ind] - # YOUR IMPLEMENTATION HERE def longest_ORF_unit_tests(): """ Unit tests for the longest_ORF function """ @@ -132,8 +162,20 @@ def longest_ORF_noncoding(dna, num_trials): dna: a DNA sequence num_trials: the number of random shuffles returns: the maximum length longest ORF """ - - # YOUR IMPLEMENTATION HERE + #import random + ORF = "" + for i in range(num_trials): + dna_temp = [] + dna_string = "" + for char in dna: + dna_temp.append(char) + shuffle(dna_temp) + for item in dna_temp: + dna_string +=item + if len(longest_ORF(dna_string))>len(ORF): + ORF = longest_ORF(dna_string) + return len(ORF) + def gene_finder(dna, threshold): """ Returns the amino acid sequences coded by all genes that have an ORF @@ -145,5 +187,22 @@ def gene_finder(dna, threshold): returns: a list of all amino acid sequences whose ORFs meet the minimum length specified. """ - - # YOUR IMPLEMENTATION HERE \ No newline at end of file + protiens = [] + protein = "" + ORFs = find_all_ORFs_both_strands(dna) + for item in ORFs: + if len(item)>threshold: + protiens+=coding_strand_to_AA(item) + for items in protiens: + protein += items + return protein + +def search_genome_simple(DNA,aa): + + names = [] + for items in DNA: + if len(items)==3: + if aa in items[2]: + print items + names.append(items[1]) + return names \ No newline at end of file diff --git a/hw3/load.py b/hw3/load.py index b3deaf7..2eba084 100644 --- a/hw3/load.py +++ b/hw3/load.py @@ -1,4 +1,4 @@ -# -*- coding: utf-8 -*- +hw# -*- coding: utf-8 -*- """ Created on Sat Feb 1 22:02:04 2014 @@ -6,7 +6,6 @@ """ from os import path - def load_seq(fasta_file): """ Reads a FASTA file and returns the DNA sequence as a string. diff --git a/hw4/random_art.py b/hw4/random_art.py index 42075e4..b4e4a7f 100644 --- a/hw4/random_art.py +++ b/hw4/random_art.py @@ -7,17 +7,64 @@ # you do not have to use these particular modules, but they may help from random import randint +from math import * import Image - +current_depth = 1 def build_random_function(min_depth, max_depth): # your doc string goes here - + """Prints an array including function strings prod, sin_pi, cos_pi, x, y with their + repsective inputs in nested arrays. + inputs: + min_depth: the minimum depth that you want your function to reach + max_depth: the maximum depth that you want your function to reach + """ # your code goes here + global current_depth + if current_depth < min_depth: + current_depth += 1 + choices = ["prod","sin_pi","cos_pi"] + i = randint(0,len(choices)-1) + s = choices[i] + if s == "prod": + return [s,build_random_function(min_depth, max_depth),build_random_function(min_depth, max_depth)] + else: + return [s,build_random_function(min_depth, max_depth)] + + elif current_depth >= min_depth: + + if current_depth == max_depth: + current_depth += 1 + choices = ["x","y"] + i = randint(0,len(choices)-1) + s = choices[i] + else: + current_depth += 1 + choices = ["prod","sin_pi","cos_pi","x","y"] + i = randint(0,len(choices)-1) + s = choices[i] + + if s == "prod": + return [s,build_random_function(min_depth, max_depth),build_random_function(min_depth, max_depth)] + elif s=="sin_pi" or s=="cos_pi": + return [s,build_random_function(min_depth, max_depth)] + else: + return [s] + def evaluate_random_function(f, x, y): # your doc string goes here # your code goes here + if f[0] == 'prod': + return evaluate_random_function(f[1], x, y)*evaluate_random_function(f[2], x, y) + elif f[0] == 'sin_pi': + return sin(pi*evaluate_random_function(f[1], x, y)) + elif f[0] == 'cos_pi': + return cos(pi*evaluate_random_function(f[1], x, y)) + elif f[0] == 'y': + return y + elif f[0] == 'x': + return x def remap_interval(val, input_interval_start, input_interval_end, output_interval_start, output_interval_end): """ Maps the input value that is in the interval [input_interval_start, input_interval_end] @@ -27,4 +74,33 @@ def remap_interval(val, input_interval_start, input_interval_end, output_interva TODO: please fill out the rest of this docstring """ # your code goes here - \ No newline at end of file + ratio = (output_interval_end-output_interval_start)/(input_interval_end-input_interval_start) + offset = output_interval_start-input_interval_start*ratio + return val*ratio + offset + + +global current_depth +fR = build_random_function(2, 25) +current_depth = 1 +fB = build_random_function(2, 25) +current_depth = 1 +fG = build_random_function(2, 25) +print fR +print fG +print fB +im = Image.new("RGB",(350,350)) +pixels = im.load() +for i in range(0,350): + for j in range(0,350): + x = remap_interval(i, 0, 350, -1,1.) + y = remap_interval(j, 0, 350, -1,1.) + R = remap_interval(evaluate_random_function(fR, x, y),-1,1,0,256) + B =remap_interval(evaluate_random_function(fB, x, y),-1,1,0,256) + G = remap_interval(evaluate_random_function(fG, x, y),-1,1,0,256) + RBG = (R,G,B) + + pixels[i,j] = (int(R),int(G),int(B)) + +im.save("pic" + ".thumbnail", "JPEG") + + diff --git a/hw5/Reflection.pdf b/hw5/Reflection.pdf new file mode 100644 index 0000000..5f31e71 Binary files /dev/null and b/hw5/Reflection.pdf differ diff --git a/hw5/WikiRace.py b/hw5/WikiRace.py new file mode 100644 index 0000000..ad8092d --- /dev/null +++ b/hw5/WikiRace.py @@ -0,0 +1,86 @@ +# -*- coding: utf-8 -*- +""" +Spyder Editor +By Josh Sapers and Subbhash Gubba +This temporary script file is located here: +/home/josh/.spyder2/.temp.py +""" + +from bs4 import BeautifulSoup +import requests +import re +def getLinks(url): + """ + Scans through article in wikipedia and finds all hyperlinked + texts, then stores them inside a dictionary. + + Input: The article's URL + Output: A dicsatellitetionary of all links in the page. + """ + d={} + r = requests.get(url) + data = r.text + soup = BeautifulSoup(data) + for link in soup.find_all('a'): + l =link.get('href') + if l != None: + if l[0:6]=="/wiki/": + if not(":"in l or "Main_Page"in l): + d[l[6:]]="http://en.wikipedia.org"+l + return d +def compareLinks(start,prev,targetName,targetText): + """ + Recursively compares the current link's words to the goal's + words and selects the next article based similarity. + + Input: start (previous article) prev (list of all previous) + targetName (the goal) targetText (the goal's words) + Output: Name of preceding and next articles + """ + d = getLinks("http://en.wikipedia.org/wiki/"+start) + l= d.keys() + print "\n\n"+start+"\n\n\n" + + mostcommon=0 + for keys in d: + if keys.lower() == targetName.lower(): + return keys + if len(l)<100: + max=len(l) + else: + max = 100 + for i in range(0,max): + r = requests.get(d[l[i]]) + data = r.text + soup = BeautifulSoup(data) + text1 = soup.get_text() + words = re.findall("[\w]+",text1) + if targetName in words and not(l[i]in prev): + prev.append(l[i]) + return l[i]+","+ compareLinks(l[i],prev,targetName,targetText) + common = list(set(words) & set(targetText)) + if len(common)>mostcommon: + if not(l[i]in prev): + mostcommon = len(common) + nextkey = l[i] + prev.append(nextkey) + return nextkey+","+ compareLinks(nextkey,prev,targetName,targetText) + + +def Navigate(start,end): + """ + Main code, for starting the recursion. + + Input: start(beginning article) end(ending article (goal)) + Output: Prints path + """ + r1= requests.get("http://en.wikipedia.org/wiki/"+end) + data1 = r1.text + soup1 = BeautifulSoup(data1) + text1 = soup1.get_text() + words = re.findall("[\w]+",text1) + print compareLinks(start,[start],end,words) + +start = raw_input("Start") +end = raw_input("end") +Navigate(start,end) \ No newline at end of file diff --git a/hw5/tests.odt b/hw5/tests.odt new file mode 100644 index 0000000..14dff1e Binary files /dev/null and b/hw5/tests.odt differ diff --git a/hw6/LightCycle.py b/hw6/LightCycle.py new file mode 100644 index 0000000..10e82f1 --- /dev/null +++ b/hw6/LightCycle.py @@ -0,0 +1,180 @@ +# -*- coding: utf-8 -*- +""" +Created on Sat Mar 8 23:11:28 2014 + +@author: dmichael +""" + +import pygame +from pygame.locals import * +import random +import math +import time + +class LightCycleModel: + def __init__(self): + self.cycle1 = Cycle(800,500,10,(0,0,250),-1.0) + self.cycle2 = Cycle(200,500,10,(250,0,0),1.0) + self.trail1=[] + self.trail2=[] + self.trail1.append(Trail(self.cycle1.color,self.cycle1.height,0,self.cycle1.x,self.cycle1.y)) + self.trail2.append(Trail(self.cycle2.color,self.cycle2.height,0,self.cycle2.x,self.cycle2.y)) + def update(self): + """updates the cycles and the current paths for each lightcycle""" + self.cycle1.update() + self.cycle2.update() + + #enlongating the path for cycle 1 + if self.cycle1.vx>0: + self.trail1[-1].width+=self.cycle1.vx + if self.cycle1.vx<0: + self.trail1[-1].width=self.trail1[-1].width-self.cycle1.vx + self.trail1[-1].x = self.cycle1.x+self.cycle1.width + if self.cycle1.vy>0: + self.trail1[-1].height+=self.cycle1.vy + if self.cycle1.vy<0: + self.trail1[-1].height=self.trail1[-1].height-self.cycle1.vy + self.trail1[-1].y = self.cycle1.y+self.cycle1.height + + #enlongating the path for cycle 2 + if self.cycle2.vx>0: + self.trail2[-1].width+=self.cycle2.vx + if self.cycle2.vx<0: + self.trail2[-1].width=self.trail2[-1].width-self.cycle2.vx + self.trail2[-1].x = self.cycle2.x+self.cycle2.width + if self.cycle2.vy>0: + self.trail2[-1].height+=self.cycle2.vy + if self.cycle2.vy<0: + self.trail2[-1].height=self.trail2[-1].height-self.cycle2.vy + self.trail2[-1].y = self.cycle2.y+self.cycle2.height + + for path1 in self.trail1[:-1]: + #Checking for collisions with paths + if pygame.Rect(self.cycle1.x,self.cycle1.y,self.cycle1.width,self.cycle1.height).colliderect(pygame.Rect(path1.x,path1.y,path1.width,path1.height)): + #ends game if it collides + return False + for path1 in self.trail1[:]: + if pygame.Rect(self.cycle2.x,self.cycle2.y,self.cycle2.width,self.cycle2.height).colliderect(pygame.Rect(path1.x,path1.y,path1.width,path1.height)): + return False + for path2 in self.trail2[:]: + if pygame.Rect(self.cycle1.x,self.cycle1.y,self.cycle1.width,self.cycle1.height).colliderect(pygame.Rect(path2.x,path2.y,path2.width,path2.height)): + return False + for path2 in self.trail2[:-1]: + if pygame.Rect(self.cycle2.x,self.cycle2.y,self.cycle2.width,self.cycle2.height).colliderect(pygame.Rect(path2.x,path2.y,path2.width,path2.height)): + return False + #ends game if the cycle hit the edge of screen + if not(self.windowRect.contains(pygame.Rect(self.cycle1.x,self.cycle1.y,self.cycle1.width,self.cycle1.height))): + return False + if not(self.windowRect.contains(pygame.Rect(self.cycle2.x,self.cycle2.y,self.cycle2.width,self.cycle2.height))): + return False + return True + +class Cycle: + def __init__(self,x,y,thick,color,vx): + self.x = x + self.y = y + self.width = thick + self.height = thick + self.color = color + self.vx = vx + self.vy = 0.0 + + def update(self): + """Changes the location based off of the two velocities""" + self.x += self.vx + self.y += self.vy + + +class Trail: + def __init__(self,color,height,width,x,y): + self.color=color + self.height=height + self.width=width + self.x=x + self.y=y +class PyGameWindowView: + """ A view of LightCycles rendered in a Pygame window """ + def __init__(self,model,screen,size): + self.model = model + self.model.windowRect=pygame.Rect(0,0,size[0],size[1]) + self.screen = screen + def draw(self): + """draws the two cycles and all of the paths they made""" + self.screen.fill(pygame.Color(0,0,0)) + pygame.draw.rect(self.screen, pygame.Color(self.model.cycle1.color[0],self.model.cycle1.color[1],self.model.cycle1.color[2]),pygame.Rect(self.model.cycle1.x,self.model.cycle1.y,self.model.cycle1.width,self.model.cycle1.height)) + pygame.draw.rect(self.screen, pygame.Color(self.model.cycle2.color[0],self.model.cycle2.color[1],self.model.cycle2.color[2]),pygame.Rect(self.model.cycle2.x,self.model.cycle2.y,self.model.cycle2.width,self.model.cycle2.height)) + for path1 in self.model.trail1: + pygame.draw.rect(self.screen, pygame.Color(path1.color[0],path1.color[1],path1.color[2]),pygame.Rect(path1.x,path1.y,path1.width,path1.height)) + for path2 in self.model.trail2: + pygame.draw.rect(self.screen, pygame.Color(path2.color[0],path2.color[1],path2.color[2]),pygame.Rect(path2.x,path2.y,path2.width,path2.height)) + pygame.display.update() + +class Controller: + def __init__(self,model): + self.model = model + + def handle_keyboard_event(self,event): + """checks for wasd or arrow key inputs and changes the direction accordingly. Also adds + a new path when the cycle changes direction""" + if event.type != KEYDOWN: + return + if event.key == pygame.K_LEFT and self.model.cycle1.vx == 0: + self.model.cycle1.vx = -1.0 + self.model.cycle1.vy = 0.0 + self.model.trail1.append(Trail(self.model.cycle1.color,self.model.cycle1.height,0,self.model.cycle1.x+self.model.cycle1.width,self.model.cycle1.y)) + if event.key == pygame.K_RIGHT and self.model.cycle1.vx == 0: + self.model.cycle1.vx = 1.0 + self.model.cycle1.vy = 0.0 + self.model.trail1.append(Trail(self.model.cycle1.color,self.model.cycle1.height,0,self.model.cycle1.x,self.model.cycle1.y)) + if event.key == pygame.K_UP and self.model.cycle1.vy == 0: + self.model.cycle1.vx = 0.0 + self.model.cycle1.vy = -1.0 + self.model.trail1.append(Trail(self.model.cycle1.color,0,self.model.cycle1.width,self.model.cycle1.x,self.model.cycle1.y+self.model.cycle1.height)) + if event.key == pygame.K_DOWN and self.model.cycle1.vy == 0: + self.model.cycle1.vx = 0.0 + self.model.cycle1.vy = .9999 + self.model.trail1.append(Trail(self.model.cycle1.color,0,self.model.cycle1.width,self.model.cycle1.x,self.model.cycle1.y)) + else: + self.model.cycle1.vx = self.model.cycle1.vx + self.model.cycle1.vy = self.model.cycle1.vy + + if event.key == pygame.K_a and self.model.cycle2.vx == 0: + self.model.cycle2.vx = -1.0 + self.model.cycle2.vy = 0.0 + self.model.trail2.append(Trail(self.model.cycle2.color,self.model.cycle2.height,0,self.model.cycle2.x+self.model.cycle2.width,self.model.cycle2.y)) + if event.key == pygame.K_d and self.model.cycle2.vx == 0: + self.model.cycle2.vx = 1.0 + self.model.cycle2.vy = 0.0 + self.model.trail2.append(Trail(self.model.cycle2.color,self.model.cycle2.height,0,self.model.cycle2.x,self.model.cycle2.y)) + if event.key == pygame.K_w and self.model.cycle2.vy == 0: + self.model.cycle2.vx = 0.0 + self.model.cycle2.vy = -1.0 + self.model.trail2.append(Trail(self.model.cycle2.color,0,self.model.cycle2.width,self.model.cycle2.x,self.model.cycle2.y+self.model.cycle2.height)) + if event.key == pygame.K_s and self.model.cycle2.vy == 0: + self.model.cycle2.vx = 0.0 + self.model.cycle2.vy = .9999 + self.model.trail2.append(Trail(self.model.cycle2.color,0,self.model.cycle2.width,self.model.cycle2.x,self.model.cycle2.y)) +if __name__ == '__main__': + pygame.init() + + size = (1000,1000) + screen = pygame.display.set_mode(size) + + model = LightCycleModel() + view = PyGameWindowView(model,screen,size) + controller = Controller(model) + + + running = True + + while running: + for event in pygame.event.get(): + if event.type == QUIT: + running = False + if event.type == KEYDOWN: + controller.handle_keyboard_event(event) + running=model.update() + view.draw() + time.sleep(.001) + + pygame.quit() diff --git a/hw6/Tron.py b/hw6/Tron.py new file mode 100644 index 0000000..2b8411f --- /dev/null +++ b/hw6/Tron.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +""" +Created on Thu Feb 27 19:34:24 2014 + +@author: pruvolo +""" + +import pygame +from pygame.locals import * +import random +import math +import time + +class TronModel: + """ Encodes the game state of Brick Breaker """ + def __init__(self): + self.number_of_lives = 3 + self.bricks = [] + for i in range(640/110): + for j in range(240/30): + new_brick = Brick(10+110*i,10+30*j,100,20,(random.randint(0,255),random.randint(0,255),random.randint(0,255))) + self.bricks.append(new_brick) + self.paddle = Paddle(200,450,100,20) + + def update(self): + self.paddle.update() + +class Road: + """ Encodes the state of a brick in Brick Breaker """ + def __init__(self,x,y,color): + self.x = x + self.y = y + self.width = 20 + self.height = 20 + self.color = color + +class car: + """ Encode the state of the paddle in Brick Breaker """ + def __init__(self,x,y,vx,vy,color): + self.x = x + self.y = y + self.width = 20 + self.height = 20 + self.color = color + self.vx = vx + self.vy = vy + + def update(self): + self.x += self.vx + +class PyGameBrickBreakerView: + """ renders the BrickBreakerModel to a pygame window """ + def __init__(self,model,screen): + self.model = model + self.screen = screen + + def draw(self): + self.screen.fill(pygame.Color(0,0,0)) + for brick in self.model.bricks: + pygame.draw.rect(self.screen, pygame.Color(brick.color[0], brick.color[1], brick.color[2]), pygame.Rect(brick.x, brick.y, brick.width, brick.height)) + pygame.draw.rect(self.screen, pygame.Color(self.model.paddle.color[0], self.model.paddle.color[1], self.model.paddle.color[2]), pygame.Rect(self.model.paddle.x, self.model.paddle.y, self.model.paddle.width, self.model.paddle.height)) + pygame.display.update() + +class PyGameKeyboardController: + """ Manipulate game state based on keyboard input """ + def __init__(self, model): + self.model = model + + def handle_pygame_event(self, event): + if event.type != KEYDOWN: + return + if event.key == pygame.K_LEFT: + self.model.paddle.vx += -1.0 + if event.key == pygame.K_RIGHT: + self.model.paddle.vx += 1.0 + +if __name__ == '__main__': + pygame.init() + + size = (640,480) + screen = pygame.display.set_mode(size) + + model = BrickBreakerModel() + view = PyGameBrickBreakerView(model,screen) + controller = PyGameKeyboardController(model) + running = True + while running: + for event in pygame.event.get(): + if event.type == QUIT: + running = False + controller.handle_pygame_event(event) + model.update() + view.draw() + time.sleep(.001) + + pygame.quit() \ No newline at end of file diff --git a/hw6/game.py b/hw6/game.py new file mode 100644 index 0000000..4b8a107 --- /dev/null +++ b/hw6/game.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +""" +Created on Mon Mar 3 15:07:40 2014 + +@author: josh +""" + +# Import a library of functions called 'pygame' +import pygame +# Initialize the game engine +pygame.init() +#Loop until the user clicks the close button. +done = False +# Used to manage how fast the screen updates +clock = pygame.time.Clock() +# -------- Main Program Loop ----------- +while not done: +# ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT + for event in pygame.event.get(): # User did something + if event.type == pygame.QUIT: # If user clicked close + done = True # Flag that we are done so we exit this loop + elif event.type == pygame.QUIT: + print("User asked to quit.") + elif event.type == pygame.KEYDOWN: + print("User pressed a key.") + elif event.type == pygame.KEYUP: + print("User let go of a key.") +# ALL EVENT PROCESSING SHOULD GO ABOVE THIS COMMENT +# ALL GAME LOGIC SHOULD GO BELOW THIS COMMENT +# ALL GAME LOGIC SHOULD GO ABOVE THIS COMMENT +# ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT +# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT +# Limit to 20 frames per second +clock.tick(20) \ No newline at end of file diff --git a/inclass6/debugging_exercise_1.py b/inclass6/debugging_exercise_1.py index 94e0bf2..8729ef8 100644 --- a/inclass6/debugging_exercise_1.py +++ b/inclass6/debugging_exercise_1.py @@ -13,9 +13,10 @@ def cumulative_sum(L): L: the original list returns: a new list where element i is equal to the sum of element 0 through i in the original list """ - for i in range(len(L)): - L[i] = L[i-1] + L[i] - return L + V = [L(0),0,0] + for i in range(1,len(L)): + V[i] = L[i-1] + L[i] + return V if __name__ == '__main__': print cumulative_sum([1, 2, 3]) diff --git a/inclass6/debugging_exercise_2.py b/inclass6/debugging_exercise_2.py index 8df227c..d6f4d15 100644 --- a/inclass6/debugging_exercise_2.py +++ b/inclass6/debugging_exercise_2.py @@ -8,7 +8,7 @@ def factorial(n): """ Computes the factorial of the non-negative input integer n """ return_val = 1 - for i in range(n): + for i in range(1,n): return_val *= i return return_val diff --git a/inclass6/debugging_exercise_3.py b/inclass6/debugging_exercise_3.py index 402eefd..7338c11 100644 --- a/inclass6/debugging_exercise_3.py +++ b/inclass6/debugging_exercise_3.py @@ -8,10 +8,10 @@ def get_primes(n): """ Returns a list of all prime integers in the range [1,n] """ return_val = [] - isPrime = True - - for i in range(1,n+1): - for j in range(1,i): + + for i in range(2,n+1): + isPrime = True + for j in range(2,i): if i % j == 0: isPrime = False if isPrime: diff --git a/inclass6/debugging_exercise_4.py b/inclass6/debugging_exercise_4.py index 1d7c67f..1d54a8f 100644 --- a/inclass6/debugging_exercise_4.py +++ b/inclass6/debugging_exercise_4.py @@ -9,12 +9,17 @@ def get_doubles_then_triples(L): """ Returns a new list containing the original list with each element multiplied by 2 concatenated with the original list with each element multiplied by 3 """ - return get_multiple_of_list(L,2) + get_multiple_of_list(L,3) + L1 = L + L2 = L + L1 = get_multiple_of_list(L1,2) + L2 = get_multiple_of_list(L2,3) + return L1 + L2 -def get_multiple_of_list(L,n): - for i in range(len(L)): - L[i] *= n - return L +def get_multiple_of_list(L2,n): + L2 = list(L2) + for i in range(len(L2)): + L2[i] *= n + return L2 if __name__ == '__main__': print get_doubles_then_triples([1, 4, 8])