import pygame, math from pygame import * DISPLAY = (800,640) DEPTH = 32 FLAGS = 0 ############################################################## # Classes! class Entity(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) ############################################################## class Player(Entity): def __init__(self, x, y): Entity.__init__(self) self.xvel = 0 self.yvel = 0 self.onGround = False self.image = Surface((32, 32)) self.image.convert() self.image.fill(Color("#FF0000")) self.rect = Rect(x, y, 32, 32) ############################################################## def update(self, up, down, left, right, platforms): if up: # Only jump if on the ground if self.onGround: self.yvel -= 10 if down: pass if left: self.xvel = -5 if right: self.xvel = 5 if not self.onGround: # Only accelerate with gravity if in the air self.yvel += 0.3 # Max falling speed if self.yvel > 30: self.yvel = 30 if not (left or right): self.xvel = 0 # Increment in x direction self.rect.left += self.xvel # Do x-axis collisions self.collide(self.xvel, 0, platforms) # Incrememnt in y direction self.rect.top += self.yvel # Assuming we're in the air self.onGround = False; # Do y-axis collisions self.collide(0, self.yvel, platforms) ############################################################## def collide(self, xvel, yvel, platforms): for p in platforms: if sprite.collide_rect(self, p): if isinstance(p, ExitBlock): event.post(event.Event(QUIT)) if xvel > 0: self.rect.right = p.rect.left if xvel < 0: self.rect.left = p.rect.right if yvel > 0: self.rect.bottom = p.rect.top self.onGround = True self.yvel = 0 if yvel < 0: self.rect.top = p.rect.bottom ############################################################## class Platform(Entity): def __init__(self, x, y): Entity.__init__(self) self.image = Surface((32, 32)) self.image.convert() self.image.fill(Color("#DDDDDD")) self.rect = Rect(x, y, 32, 32) def update(self): pass ############################################################## class ExitBlock(Platform): def __init__(self, x, y): Platform.__init__(self, x, y) self.image.fill(Color("#0033FF")) ######################################################################################################################### def main(): pygame.init() screen = display.set_mode(DISPLAY, FLAGS, DEPTH) display.set_caption('Use arrows to move!') timer = time.Clock() up = down = left = right = False bg = Surface((32, 32)) bg.convert() bg.fill(Color("#000000")) entities = pygame.sprite.Group() player = Player(32, 32) platforms = [] ############################################################## x = y = 0 level = [ "PPPPPPPPPPPPPPPPPPPPPPPPP", "P P", "PP P", "P PP P", "P PPP P", "P PPPP P", "P PPPPP P", "P PPPPP P", "P P", "P P", "P PP", "P P P", "P PPPPP P", "P PPP P", "P EEE P", "P P", "P P P", "P P", "P P", "PPPPPPPPPPPPPPPPPPPPPPPPP",] ############################################################## for row in level: for col in row: if col == "P": p = Platform(x, y) platforms.append(p) entities.add(p) if col == "E": e = ExitBlock(x, y) platforms.append(e) entities.add(e) x += 32 y += 32 x = 0 ############################################################## entities.add(player) running = True while running: timer.tick(100) for e in pygame.event.get(): if e.type == QUIT: running = False if e.type == KEYDOWN and e.key == K_UP: up = True if e.type == KEYDOWN and e.key == K_DOWN: down = True if e.type == KEYDOWN and e.key == K_LEFT: left = True if e.type == KEYDOWN and e.key == K_RIGHT: right = True if e.type == KEYUP and e.key == K_UP: up = False if e.type == KEYUP and e.key == K_DOWN: down = False if e.type == KEYUP and e.key == K_LEFT: left = False if e.type == KEYUP and e.key == K_RIGHT: right = False ############################################################## # Draw the background for y in range(20): for x in range(25): screen.blit(bg, (x * 32, y * 32)) # Update the player, draw everything else player.update(up, down, left, right, platforms) entities.draw(screen) pygame.display.flip() ############################################################## main() pygame.quit() ##############################################################
Showing posts with label picker. Show all posts
Showing posts with label picker. Show all posts
Python | Pygame | True
All I can say, is finally.
Python | LINE!
So I wrote this nifty lil piece of code:
with open('speech.txt') as f: for i in f: i = i.rstrip() line = input('line: ') if line == 'LINE!': print('{}'.format(i.rstrip())) elif line != i: print('No! {}'.format(i.rstrip())) print('Good!')
I'm sure this will help me revising for exams or something in the future!!!
Python | Science
I can honestly say, this is the funnest piece of code, i've ever written, don't ask why, it just is.
n = {} for line in open('periodic_table.txt'): number, element = line.split() n[number] = element n2 = {} for line in open('periodic_table.txt'): element, number = line.split()[::-1] n2[element] = number n.update(n2) q = input('Enter element number or element name: ') while q: try: if q.isdigit(): print('Element number {} is {}'.format(q,n[q])) else: print('Element number for {} is {}'.format(q,n[q])) except: print("That's not an element!") q = input('Enter element number or element name: ')
Python | Nifty lil thang
Well, this could come in useful soon.
n = {} for line in open('french.txt'): english, french = line.split() n[english] = french n2 = {} for line in open('french.txt'): french, english = line.split()[::-1] n2[french] = english n.update(n2) for k, v in n.items(): print(k, ':', v)
Python | Revision test | Chemistry
Hopefully this will help me
while 1: a = 'NaCO3 + 2HCl -> 2NaCl + H2O + CO2' b = 'Pb(NO3) + 2Kl -> Pbl2 + 2KNO3' c = 'Zn + 2HCl -> ZnHCl2 + H2' aa = input("What's the WE for Sodium carbonate + Hydrochloric acid? ") if aa == a: print('correct!') else: print('no') bb = input("What's the WE for Pottasium iodide + Lead nitrate? ") if bb == b: print('correct!') else: print('no') cc = input('What\'s the WE for Hydrochloric acid + Zinc metal? ') if cc == c: print('correct!') else: print('no')
Python | NCSS Week 3
So, I got 100% second week in a row..... hehehehehheheheh ok,
here are the notes in which I used, PLUS at the very bottom is the problem that took me the longest to solve, I bet the solution is way shorter than my response, but whoooo carrreesssss
here are the notes in which I used, PLUS at the very bottom is the problem that took me the longest to solve, I bet the solution is way shorter than my response, but whoooo carrreesssss
# Looping over characters # Time to combine some of our skills. We want to use our understanding # of strings, the len function and while loops to print out each # character of a string, one per line ''' word = 'Grok' i = 0 while i < len(word): print(i, word[i]) i += 1 ''' # String methods # Since we're discussing strings, let's go over some more useful # string methods. We've seen how to call a method on a string object, (like upper) # and introduced a couple of string methods for converting # strings to uppercase and lowercase, and replacing bits of # a string with other strings. ''' s = 'hello world' print(s.startswith('hello')) print(s.endswith('rld')) ''' # Removing whitspace from around a string. ''' s = ' abc ' print(s.strip()) print(s.lstrip()) print(s.rstrip()) s = 'hello world' print(s.find('w')) print(s.find('x')) ''' # Finding factots - the problem # Let's look at a worked example using loops. We want to write a program # to find all the factors of 540. A factor of a number n is an int # that can be multiplied by another int to give n. For example, the factors # of 9 are; 1,2,4 and 8 since: ''' 1 x 8 = 8 2 x 4 = 8 ''' # And the factors of 24 are 1,2,3,4,6,8,12 and 24: ''' 1 x 24 = 24 2 x 12 = 24 3 x 8 = 24 4 x 6 = 24 ''' # One way of finding factors is to use your calculator and checking all the numbers less # than n one by one, This works well for small numbers (like 24) # but quicly becomes impractical for larger numbers (like 540). # Can you solve it faster using Python? # Finding factots - the algorithm # The first step in solving a programming problem is work out # the algorithm or method that we need to follow. # The simplest approuch is to mimic what you would do by hand # using your calculatr | Cheching each number one by one is called # brute force solution, Computers are so fast at doing basic calculations # that the brute force solution is often a good one for problems like this. # Let's write down the individual steps we need to follow: # 1. Choose the first number to test, start with 1: # 2. See if that number divided evenly into 540 using the modulus # operator, if it does print it out as a factor: # 3. Choose the next number by adding 1 to your last choice: # 4. If your number to test is greater than 540 then you have finished, # otherwise go back to step 2. # HA, i did it by myself wotofit ''' i = 1 x = 54324235435 while i <= x: if x % i == 0: print(i) i += 1 ''' # When a for loops is best # Every problem that can be solved using a while loop can also be # solved using a for loop (and vice versa) So how do you know # which one to use? # Generall, when you know how many iteratios you need ( either a set # number ot to iterate through a list) it is easier to use a for loop) # For example ''' colours = ['red', 'blue', 'green'] for i in colours: print(i) ''' # When a while loop is best # Generally, when you don't know how many iterations you need, # and you want to keep looping while some condition is true # a while loop is better, for example: ''' sum = 0 limit = 10 i = 0 while sum < limit: sum += i print(i, sum) i += 1 ''' # Storing multiple values # Imagine writing a program to store a ranking of your favourite # authors. Given what you know so far, you would use a seperate # variable for each author's name and mention each variable to print them ''' authors = ["J.K. Rowling", "P. Pullman", "S. Collins"] print(authors[0]) print(authors[1]) print(authors[2]) authors = ["J.K. Rowling", "P. Pullman", "S. Collins"] for author in authors: print(author) ''' ''' numbers = input('What are ur fave numbers: ') nums = numbers.split() for i in nums: print (i) ''' # Phonic tester ''' line = None while line != '': line = input('Line: ') if line == '': break phonic = line.split() start = phonic[0] start_4 = phonic [3] a = start[0] if start_4.startswith(a): print('Good!') else: print("That's not right!") ''' # Accessing list elements # List items can be accessed using indexing (a.k.a subscripting) ''' colours = ['red', 'blue', 'green', 'yellow'] print(colours[1]) print(colours[-1]) ''' # Modifying list elements # You may remember from earlier that strings are # Immutable, which means that you cannot change their value. # If you try to alter a character in a string, Python will # Complain with a type error! # Lists are different. List elements can be modified by assigning to # Subscripts: ''' colours = ['red', 'blue', 'green', 'yellow'] colours[0] = 'crimson' colours[-2] = 'lime' print(colours) ''' # Appending and sorting # There are various list methods that can be used to modify lists. # The append methos adds an item to the end of the list: ''' numbers = ['one', 'two', 'three'] numbers.append('four') print(numbers) ''' # The sort() method sorts the items in order, e.g. string in # alphabetical order and numbers in ascending order. ''' pets = ['dog','mouse','fish','cat'] pets.sort() print(pets) ''' # The reverse() method sorts the items in reverse order: ''' pets = ['dog','mouse','fish','cat'] pets.reverse() print(pets) ''' # Reversing a list # The reverse method reverses the order of the entire list. # Just like the string methods we saw last week, notice that calls # to list method name, seperated by a dot, e.g. pets.reverse() # Any other values the method needs to do its job is provided in a # normal way e.g 'cat' is given as an extra argument inside the round # brackets inn pets.append('cat') # Unlike methods applied to strings, notice that these methods modify # the original lists rather than creating new ones and so they don't return # a value. You can tell this because there is no output when you type them into # the interpreter, so we need to put pets on a separate line to see what happened # to our list. # Looping with append # Say we want to sort some books for the library catalogue. We ask the user which books they # are returning (one at a time), and then want to print them out in alphabetical order. ''' books = [] book = None while book != '': book = input('What book are you returning? ') books.append(book) books.sort() for i in books: print(i) ''' # List of characters and words # Lists can be constructed from strings using the list builtin function ''' print(list('hello')) ''' # Splitting on other characters # You can also split strings using other characters, or strings, as the seperator, For example # sometimes you may want to split a string using the colon character ':' ''' text = input('text: ') line = text.split(':') for i in line: print(i) ''' # Creating sublists from lists # Slicing also works like on strings to create a new sublist: ''' a = ['red','blue','green','yellow'] less = a[:2] print(less) ''' # This is useful for checking if a word is in a string: ''' words = ['the', 'fox', 'jumped', 'over', 'the', 'dog'] print('jumped' in words) ''' # Joinging a list of strings # Another useful string method is join which joins a list of strings back together using # a string as a seperator ''' sep = ':' val = ['a','b','c','d'] print(sep.join(val)) ''' # Splitting and joining # You'll often see a literal string (like the space ' ') used: ''' val = ['a','b','c','d'] print('.'.join(val)) ''' # This is handy when you want to remove duplicate spaces from use input. ''' msg = input('Enter your letters: ') letters = msg.split() print('.'.join(letters)) ''' # If the user enters a series of letters with extra spaces between them, # the program removes these spaces and prints them out with a single space separating each. # Checking if a word is alphabetical, reversed, or not in any order. ''' word = input('Word: ') word = word[0].lower() + word[1:].lower() al = list(word) al2 = al.sort() al3 = ''.join(al) al_2 = al.reverse() al_3 = ''.join(al) alpha = al3 revd = al_3 same = word[0] * len(word) if word == alpha: print('alphabetical') elif word == revd: print('reverse alphabetical') elif word != alpha or revd: print('not alphabetical in any way') ''' # Like Yoda, you speak # Yoda speaks in a bit of a strange way. Imagine you wanted to write a program to speak like # Yoda. Your program reads in four words from the user and moves them around to create a # sentence that sounded like Yoda # he is your father # --> # your father he is # Using a list structure makes this program quite easy to write. Lets write on that # reads in a single line of text and moves the words around using lists. Like always we first # break the problem down into smaller steps: # 1. Read the line of text # 2. Seperate the line into a list of two words # 3. Change the words to Yoda-speak order # 4. Print out the new text. ''' line = input('You say: ') yoda = line.split() yoda = yoda[2] + ' ' + yoda[3] + ' ' + yoda[0] + ' ' + yoda[1] print('Yoda says: ', yoda) ''' rule = [] broken = [] tb = 0 tr = 0 line = ' ' while line: lines = input('Line: ') line = lines.split() for word in line: if 'ie' in word: if 'cie' in word: tb += 1 elif word.count('cie') > 1: tb += 1 elif word.count('ie') > 1: tr += 1 elif 'ie' in word: tr += 1 if 'ei' in word: if 'cei' in word: tr += 1 elif word.count('cei') > 1: tr += 1 elif word.count('ei') > 1: tb += 1 elif 'ei' in word: tb += 1 print('Number of times the rule helped: {0}'.format(tr)) print('Number of times the rule was broken: {0}'.format(tb))
Python | Guessing game
I've got to stop making these, JOKES
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | from tkinter import * from random import * app = Tk() app.title('Guess the number') app.geometry('400x300') ment = IntVar() num = randint(1, 10) def rand(): ges = ment.get() if ges > num: l = Label(app, text='{} is too high!'.format(ges)).place(x=165, y=70) elif ges < num: l = Label(app, text='{} is too low!'.format(ges)).place(x=165, y=70) elif ges == num: l = Label(app, text='{} is correct!'.format(ges)).place(x=165, y=70) return la = Label(app, text='Guess the secret number between 1 and 10!').pack() guess = Entry(textvariable=ment).pack() guess_button = Button(app, text='Guess!', command=rand).pack() app.mainloop() |
Python | Guess the secret number!
Upon learning about the 'random' module, I made a little guessing game, enjoy..
1 2 3 4 5 6 7 8 9 10 11 12 | import random x = random.randint(1, 100) while 1: v = int(input('Guess the number between 1 and 100!: ')) if v == x: print('That\'s right! The secret number is ', x) elif v > x: print('That\'s too high!') elif v < x: print('That\'s too low!') else: print('Please choose a number between 1 and 100!!') |
Python | Notes/Classes
This is just something I might print when I get the chance.. ok
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 | #Replacing Text. (REGEX) import re #Defining the 're' module def main(): #Defining a function 'main' - (can be anything) try: #Trying function below, if it is true, it will execute. v = input('What file would you like to run: ') a = input('What text would you like to highlight: ') b = input('What would you like to change it to: ') fh = open (v) #Assigning the variable 'fh' to opening a file 'rotf.txt' pattern = re.compile(a, re.IGNORECASE) #Assigning 'pattern' to a function, which chooses the text and ignores case. for line in fh: #Printing a chosen object in a way defined below. if re.search(pattern, line): #If it finds 'pattern' excute code below it. print(pattern.sub(b, line), end='') #Prints the sentece containing 'pattern' and swaps chosen word with 'pattern.sub' except IOError as e: #If file is not found, print text below and type of error. print('Sorry, file not found!', e) #main() #Calling the 'main' function written above. #________________________________________________________________________________________________# #Checking file name, and if it exists. (RECURSION) def open_file(): #Defining the 're' module try: #If code below is true, try will excute file = input('What file would you like to open: ') #Assigning file to user's choice for line in readlines(file): print(line.strip()) #Printing the file except IOError as e: #If no such file, print this error print('sorry file not found!', e) #What will execute if 'file' is False except ValueError as e: #If bad file name. e.g. '.dic' when it's '.doc' print('bad filename!', e) #What will execute if bad file name def readlines(filename): #A function that will let the user choose a file if filename.endswith('.txt'): #Making sure the filename ends with '.txt' fh = open(filename) #Assigning 'fh' to what the users file choice is return fh.readlines() #Returning the file, with the readlines function else: raise ValueError('File name must end in .txt!') #If bad file name, this executes #open_file() #Calling the function above. #________________________________________________________________________________________________# #Classes class Animal: def talk(self): print('i have something to say') #Default function for 'talk' def walk(self): print('hey, im walking here') #Default function for 'walk' def clothes(self): print('i have nice clothes') #Default function for 'clothes' class Dog(Animal): #Calling a class named 'Dog' and telling it it's an animal def bark(self): #Default result for 'bark' print('woof!') def walk(self): #Default resault for 'walk' (in Dog() only!) super().walk() #Tells the function to use the Default result for walk print('strut!') class Duck(Animal): #Calling a class names dog and assigning it to 'Animal' def clothes(self): #Defining it's 'clothes' print('I have brown and white fur') def Main(): Max = Dog() #Assigning 'Max' to Dog() which can be used later on. Max.bark() #Max's bark Max.walk() #Max's walk Max.clothes() #Max's clothes donald = Duck() #Assigning 'donald' to Duck() donald.walk() #donald's walk donald.talk() #donald's talk donald.clothes() #donald's clothes #Main() #Calling the Main() function #________________________________________________________________________________________________# #Classes class Duck(): #Introduces the definition of a class. def __init__(self, **kwargs): #This is a constructor self.variables = kwargs def quack(self): #Function that prints a line of text. print('Quaaack!') def walk(self): #Function that prints a line of text. print('Walks like a duck.') def set_color(self, color): #Function that sets the color self.variables['color'] = color def get_color(self): #Function that gets the color return self.variables.get('color', None) def set_variable(self, k, v): #K and V represent the var and it's value self.variables[k] = v def get_variable(self, k): #Function that returns what is written return self.variables.get(k, None) def duck(): donald = Duck(feet = 2) #Setting the VAR 'feet' to '2' donald.set_variable('color', 'blue') #Setting the VAR 'color' to 'blue' print(donald.get_variable('feet')) #Printing 'feet' print(donald.get_variable('color')) #Printing 'color' #duck() #________________________________________________________________________________________________# #Classes class Duck: def quack(self): print('Quaaack!') def walk(self): print('Walks like a duck!') def bark(self): print('the duck can not bark!') def fur(self): print('the duck has feathers!') class Dog: def bark(self): print('woof') def fur(self): print('The dog has brown and black fur!') def walk(self): print('Walks like a dog!') def quack(self): print('The dog barks') def animal(): donald = Duck() fido = Dog() in_the_forest(donald) in_the_pond(fido) def in_the_forest(dog): dog.bark() dog.fur() def in_the_pond(duck): duck.quack() duck.walk() #animal() #________________________________________________________________________________________________# #Classes(generator) class inc_range: def __init__(self, *args): numargs = len(args) if numargs < 1: raise TypeError('requires at least one arg') elif numargs == 1: self.stop = args[0] self.start = 0 self.step = 1 elif numargs == 2: (self.start, self.stop) = args self.step = 1 elif numargs == 3: (self.start, self.stop, self.step) = args else: raise TypeError('expected at most 3 arguments, got {}'.format(numargs)) def __iter__(self): i = self.start while i <= self.stop: yield i i += self.step def main(): o = inc_range(0, 30000) for i in o: print(i, end = ' ') #main() #________________________________________________________________________________________________# #Decorators class Duck: def __init__(self, **kwargs): self.properties = kwargs def quack(self): print('Quaaack!') def walk(self): print('Walks like a duck.') def get_properties(self): return self.properties def get_property(self, key): return self.properties.get(key, None) @property def color(self): self.properties.get('color', None) @color.setter def color(self, c): self.properties['color'] = c @color.deleter def color(self): del self.properties['color'] def main(): donald = Duck() donald.color = 'blue' print(donald.color) if __name__ == "__main__": main() #main() #________________________________________________________________________________________________# |