├── Internet
└── locdraw
│ ├── __init__.py
│ ├── port.py
│ ├── client.py
│ └── server.py
├── simple
├── sum.py
├── scores.txt
├── compound.py
├── verysimpleif.py
├── if.py
├── questions.txt
├── todo.py
├── add_robot.py
├── input-score.py
├── input.py
├── loops.py
├── cointoss.py
├── challenges
│ ├── challenges1.html
│ └── challenges2.html
├── functions2.py
├── dice_graph.py
├── validatedinput.py
├── inputnum.py
├── cats-dict.py
├── functions3.py
├── lists.py
├── i-o.py
├── count_enters.py
├── dicethrowcount.py
├── higher-order-functions.py
├── compound-output.py
├── greet-dict.py
├── dieguess.py
├── high-low-game.py
├── robots.py
├── calculator.py
├── functions1.py
├── cypher.py
├── turkeycalc.py
├── questions3.py
├── advent_library.py
├── questions.py
├── mathquiz.py
└── advent.py
├── Course-2004
├── Lesson 7
│ ├── problem1.xml
│ ├── problem2.xml
│ ├── problem2.py
│ ├── problem1.py
│ └── LessonPlan.txt
├── Misc
│ ├── ball
│ │ ├── ball.bmp
│ │ └── ball.py
│ ├── secret.py
│ ├── test.py
│ ├── guess.py
│ └── game1.py
├── Lesson 2
│ ├── fn2.py
│ ├── shuffle.py
│ ├── simple-fn.py
│ ├── except1.py
│ ├── randpick.py
│ ├── class1.py
│ ├── hw3b.py
│ ├── homework
│ │ ├── 2.py
│ │ ├── 3.py
│ │ ├── 5.py
│ │ ├── Answers.txt
│ │ └── Homework.txt
│ ├── hw3.py
│ ├── calc.py
│ ├── fn.py
│ ├── TKinter
│ │ ├── very-simple-gui.py
│ │ ├── simple-gui.py
│ │ └── gui.py
│ ├── randpick2.py
│ └── LessonPlan.txt
├── README
├── Lesson 8
│ ├── LessonPlan.txt
│ └── homework.txt
├── Lesson 9
│ └── LessonPlan.txt
├── Lesson 4
│ ├── dict.py
│ ├── picksim.py
│ ├── homework
│ │ ├── 1.py
│ │ └── homework.txt
│ ├── dicesim.py
│ └── LessonPlan.txt
├── Lesson 3
│ ├── list.py
│ ├── Homework
│ │ ├── 1.py
│ │ ├── 2.py
│ │ └── homework.txt
│ └── LessonPlan.txt
├── Lesson 6
│ ├── LessonPlan.txt
│ ├── adventure3
│ │ ├── commandline.py
│ │ ├── game.xml
│ │ ├── place.py
│ │ ├── placexml.py
│ │ └── adventure3.py
│ └── adventure4
│ │ ├── commandline.py
│ │ ├── gameserver.py
│ │ ├── game.xml
│ │ ├── place.py
│ │ └── gamexml.py
├── Lesson 1
│ ├── drt.py
│ ├── cost.py
│ ├── bikemove.py
│ └── LessonPlan.txt
└── Lesson 5
│ ├── 1.py
│ └── 2.py
├── Input-Output
├── scores.csv
├── in.txt
├── filterio.py
├── score_reader.py
└── word-counts
│ ├── word_counts.py
│ └── stopwords.txt
├── Web
├── name-picker
│ ├── README.md
│ ├── templates
│ │ ├── names.html
│ │ └── layout.html
│ └── name_picker.py
├── weatheruser.py
├── flaskclient.py
├── flask
│ ├── simple.py
│ ├── templates
│ │ └── simple2.html
│ ├── simple2.py
│ ├── gmap
│ │ ├── templates
│ │ │ ├── index.html
│ │ │ └── map.html
│ │ └── gmap.py
│ ├── morse
│ │ ├── morseclient.py
│ │ ├── codes.py
│ │ ├── README.md
│ │ └── morseserver.py
│ └── joke_quote_whoop.py
├── Screen-Scraping
│ ├── ss1.py
│ ├── air_quality.py
│ └── web_crawler.py
├── search.py
├── showip.py
├── weather.py
├── Treasure-Hunt
│ ├── thclient.py
│ ├── thserver.py
│ ├── thclient2.py
│ └── thserver2.py
├── multi-joke-client.py
├── chat
│ └── chatserver.py
├── Old-Style
│ ├── gameserver.py
│ ├── webserver2.py
│ └── webserver.py
└── dumpmeetup.py
├── Adventure
└── readme.txt
├── Pygame
├── Sprite1
│ ├── bee1.png
│ ├── bee.py
│ └── Sprite1.py
├── jump
│ ├── red-man.png
│ └── platform.py
├── Planet
│ ├── planet.png
│ ├── attributions.txt
│ ├── stars.py
│ └── planet.py
├── Bees
│ ├── media
│ │ ├── bee1.png
│ │ ├── bee2.png
│ │ ├── bee3.png
│ │ ├── flower.jpg
│ │ ├── flower.png
│ │ ├── grass.jpg
│ │ ├── grass.png
│ │ └── clover-large.JPG
│ ├── util.py
│ ├── flower.py
│ ├── score.py
│ ├── bee.py
│ └── bees.py
├── SimplePygame
│ ├── bee1.png
│ ├── bird.png
│ ├── groovy.wav
│ ├── powerup.wav
│ ├── PlaySound.py
│ ├── text.py
│ ├── Challenges.html
│ ├── shapes.py
│ ├── simple_color_grid.py
│ ├── SimplePygame.py
│ ├── FadeOutBackground.py
│ ├── draw_shapes_solution.py
│ ├── SimplePygameSolutions1-3.py
│ ├── draw_shapes_problem.py
│ ├── showcolors.py
│ ├── gradients.py
│ ├── Collide.py
│ └── random_color_grid.py
├── One Bee
│ ├── media
│ │ ├── bee1.png
│ │ ├── bee2.png
│ │ └── bee3.png
│ ├── util.py
│ ├── bee.py
│ └── bees.py
├── Two Bees
│ ├── media
│ │ ├── bee1.png
│ │ ├── bee2.png
│ │ └── bee3.png
│ ├── util.py
│ ├── bee.py
│ └── bees.py
├── Chessboard
│ ├── blackpawn.png
│ ├── whitepawn.png
│ └── tiledraw.py
├── Bee Invaders
│ ├── media
│ │ ├── bee1.png
│ │ ├── bee2.png
│ │ ├── bee3.png
│ │ ├── monster.png
│ │ ├── projectile.png
│ │ └── monster-dropping.png
│ ├── util.py
│ ├── projectile.py
│ ├── monster_dropping.py
│ ├── bee.py
│ ├── monster.py
│ └── bees.py
└── InvisibleMaze
│ ├── media
│ └── player.png
│ ├── imageutil.py
│ └── invisiblemaze.py
├── doc
├── browser-result.png
└── Simple Text Adventure Game
│ └── adventure-transitions.png
├── Harder
├── fibonacci.py
├── nested-loops.py
├── factorial.py
├── fibonacci_gen.py
├── spellcheck.py
├── commonwords.py
├── picker.py
├── sieve.py
├── wordgame.py
├── if.py
├── Hash-Attack
│ ├── hashbreak.py
│ └── permuter.py
├── list_comprehensions.py
├── pascal_triangle.py
├── MrTGuessTheFood.py
├── caesar-cipher.py
├── magic-squares.py
├── patternquiz.py
├── cardorder.py
├── roshambo.py
├── memorygame.py
├── hangman.py
├── auto-high-low.py
└── runways.py
├── triple-loop.py
├── Turtle
├── star.py
├── multi.py
├── multi_polygons.py
├── random_lines.py
├── spirals.py
└── centered_triangle.py
├── Plotting
├── sine_scatter.py
├── scatter.py
├── citytemps.py
├── diceplot.py
├── heightage.py
└── plottedtemps.py
├── Object-Oriented
├── cat.py
├── paddle.py
└── robots.py
├── .gitignore
├── Multithreading
├── simplethread.py
└── simplethread-timed.py
├── Jython
├── Life2
│ ├── setup.py
│ ├── GridMutator.py
│ └── LifeGame.py
└── Life
│ ├── GridMutator.py
│ └── life1.py
├── images
└── graphpaper.py
├── LICENSE
├── Physical-Computing
├── tilt_to_wheel_power.py
├── tilt_microbit_makecode.py
└── tilt_microbit_micropython.py
└── Generic-Duel
└── duel.py
/Internet/locdraw/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Internet/locdraw/port.py:
--------------------------------------------------------------------------------
1 | PORT = 5000
2 |
--------------------------------------------------------------------------------
/simple/sum.py:
--------------------------------------------------------------------------------
1 | print(sum(range(1, 101)))
2 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 7/problem1.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/simple/scores.txt:
--------------------------------------------------------------------------------
1 | Mary,9
2 | Joe,10
3 | Frank,11
4 |
--------------------------------------------------------------------------------
/Input-Output/scores.csv:
--------------------------------------------------------------------------------
1 | Fred,99
2 | Sue,100
3 | Bill,25
4 | Mary,67
5 |
--------------------------------------------------------------------------------
/Web/name-picker/README.md:
--------------------------------------------------------------------------------
1 | # Name Picker
2 | A name picker, written in Python with Flask
3 |
--------------------------------------------------------------------------------
/Adventure/readme.txt:
--------------------------------------------------------------------------------
1 | This project was moved to https://github.com/dcbriccetti/python-text-adventure
2 |
--------------------------------------------------------------------------------
/Web/weatheruser.py:
--------------------------------------------------------------------------------
1 | from .weather import temp_at_location
2 |
3 | print(temp_at_location('94549'))
4 |
--------------------------------------------------------------------------------
/Pygame/Sprite1/bee1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Sprite1/bee1.png
--------------------------------------------------------------------------------
/Pygame/jump/red-man.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/jump/red-man.png
--------------------------------------------------------------------------------
/doc/browser-result.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/doc/browser-result.png
--------------------------------------------------------------------------------
/Pygame/Planet/planet.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Planet/planet.png
--------------------------------------------------------------------------------
/Pygame/Bees/media/bee1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Bees/media/bee1.png
--------------------------------------------------------------------------------
/Pygame/Bees/media/bee2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Bees/media/bee2.png
--------------------------------------------------------------------------------
/Pygame/Bees/media/bee3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Bees/media/bee3.png
--------------------------------------------------------------------------------
/Pygame/Bees/media/flower.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Bees/media/flower.jpg
--------------------------------------------------------------------------------
/Pygame/Bees/media/flower.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Bees/media/flower.png
--------------------------------------------------------------------------------
/Pygame/Bees/media/grass.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Bees/media/grass.jpg
--------------------------------------------------------------------------------
/Pygame/Bees/media/grass.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Bees/media/grass.png
--------------------------------------------------------------------------------
/Pygame/Planet/attributions.txt:
--------------------------------------------------------------------------------
1 | Planet art by GM_Shaber
2 | http://opengameart.org/content/27-planets-in-hi-res
3 |
--------------------------------------------------------------------------------
/Pygame/SimplePygame/bee1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/SimplePygame/bee1.png
--------------------------------------------------------------------------------
/Pygame/SimplePygame/bird.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/SimplePygame/bird.png
--------------------------------------------------------------------------------
/Course-2004/Misc/ball/ball.bmp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Course-2004/Misc/ball/ball.bmp
--------------------------------------------------------------------------------
/Pygame/One Bee/media/bee1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/One Bee/media/bee1.png
--------------------------------------------------------------------------------
/Pygame/One Bee/media/bee2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/One Bee/media/bee2.png
--------------------------------------------------------------------------------
/Pygame/One Bee/media/bee3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/One Bee/media/bee3.png
--------------------------------------------------------------------------------
/Pygame/SimplePygame/groovy.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/SimplePygame/groovy.wav
--------------------------------------------------------------------------------
/Pygame/Two Bees/media/bee1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Two Bees/media/bee1.png
--------------------------------------------------------------------------------
/Pygame/Two Bees/media/bee2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Two Bees/media/bee2.png
--------------------------------------------------------------------------------
/Pygame/Two Bees/media/bee3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Two Bees/media/bee3.png
--------------------------------------------------------------------------------
/Pygame/Chessboard/blackpawn.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Chessboard/blackpawn.png
--------------------------------------------------------------------------------
/Pygame/Chessboard/whitepawn.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Chessboard/whitepawn.png
--------------------------------------------------------------------------------
/Pygame/SimplePygame/powerup.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/SimplePygame/powerup.wav
--------------------------------------------------------------------------------
/Course-2004/Lesson 2/fn2.py:
--------------------------------------------------------------------------------
1 | def addNumbers(num1, num2):
2 | return num1 + num2
3 |
4 | sum = addNumbers(3,4)
5 | print(sum)
6 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 2/shuffle.py:
--------------------------------------------------------------------------------
1 | import random
2 | names = ['Ethan', 'Kurt', 'Eric']
3 | random.shuffle(names)
4 | print(names)
5 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 2/simple-fn.py:
--------------------------------------------------------------------------------
1 | def showIntro():
2 | print("This is the exciting introduction ...")
3 |
4 | showIntro()
5 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 7/problem2.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/Pygame/Bee Invaders/media/bee1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Bee Invaders/media/bee1.png
--------------------------------------------------------------------------------
/Pygame/Bee Invaders/media/bee2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Bee Invaders/media/bee2.png
--------------------------------------------------------------------------------
/Pygame/Bee Invaders/media/bee3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Bee Invaders/media/bee3.png
--------------------------------------------------------------------------------
/Pygame/Bees/media/clover-large.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Bees/media/clover-large.JPG
--------------------------------------------------------------------------------
/simple/compound.py:
--------------------------------------------------------------------------------
1 | backpack = False
2 | dollars = .50
3 |
4 | if backpack and dollars >= 1.0:
5 | print('Ride the bus!')
6 |
--------------------------------------------------------------------------------
/Pygame/Bee Invaders/media/monster.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Bee Invaders/media/monster.png
--------------------------------------------------------------------------------
/Pygame/InvisibleMaze/media/player.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/InvisibleMaze/media/player.png
--------------------------------------------------------------------------------
/Harder/fibonacci.py:
--------------------------------------------------------------------------------
1 | num, next_num = 0, 1
2 |
3 | for n in range(10):
4 | print(num)
5 | num, next_num = next_num, num + next_num
6 |
--------------------------------------------------------------------------------
/Pygame/Bee Invaders/media/projectile.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Bee Invaders/media/projectile.png
--------------------------------------------------------------------------------
/Course-2004/Lesson 2/except1.py:
--------------------------------------------------------------------------------
1 | try:
2 | num = float(eval(input('Give us a number: ')))
3 | except ValueError:
4 | print('Bad number')
5 |
--------------------------------------------------------------------------------
/Course-2004/README:
--------------------------------------------------------------------------------
1 | Here are files from a Python class I taught in 2004, and converted to Python 3 in 2015.
2 | They should still be very helpful.
3 |
--------------------------------------------------------------------------------
/Harder/nested-loops.py:
--------------------------------------------------------------------------------
1 | one_to_ten = range(1, 11)
2 |
3 | for i in one_to_ten:
4 | for j in one_to_ten:
5 | print(f'{i} * {j} = {i * j}')
6 |
--------------------------------------------------------------------------------
/Web/flaskclient.py:
--------------------------------------------------------------------------------
1 | import requests
2 |
3 | resp = requests.get('http://localhost:5000/')
4 | status = resp.status_code
5 |
6 | print(resp.text)
7 |
--------------------------------------------------------------------------------
/simple/verysimpleif.py:
--------------------------------------------------------------------------------
1 | health = 100
2 |
3 | if health < 50:
4 | print('You are not doing too well!')
5 | else:
6 | print('You are fine')
7 |
--------------------------------------------------------------------------------
/triple-loop.py:
--------------------------------------------------------------------------------
1 | charset = range(10)
2 | for c1 in charset:
3 | for c2 in charset:
4 | for c3 in charset:
5 | print(c1, c2, c3)
6 |
--------------------------------------------------------------------------------
/Pygame/Bee Invaders/media/monster-dropping.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/Pygame/Bee Invaders/media/monster-dropping.png
--------------------------------------------------------------------------------
/Harder/factorial.py:
--------------------------------------------------------------------------------
1 | def factorial(n):
2 | return n if n == 1 else n * factorial(n - 1)
3 |
4 | assert(factorial(3) == 6)
5 | assert(factorial(4) == 24)
6 |
--------------------------------------------------------------------------------
/Turtle/star.py:
--------------------------------------------------------------------------------
1 | import turtle as t
2 | from time import sleep
3 |
4 | for n in range(4):
5 | t.fd(200)
6 | t.rt(170)
7 |
8 | sleep(2)
9 |
10 |
--------------------------------------------------------------------------------
/Input-Output/in.txt:
--------------------------------------------------------------------------------
1 | Here are some words. Some contain the letter e. And some don't.
2 | The program will copy only those words that don't contain e to the
3 | output file.
--------------------------------------------------------------------------------
/doc/Simple Text Adventure Game/adventure-transitions.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dcbriccetti/python-lessons/HEAD/doc/Simple Text Adventure Game/adventure-transitions.png
--------------------------------------------------------------------------------
/simple/if.py:
--------------------------------------------------------------------------------
1 | cond = input('How are you feeling? ')
2 | happy_words = ('fine', 'good', 'great', 'super')
3 | if cond.lower() in happy_words:
4 | print("That's great!")
5 |
--------------------------------------------------------------------------------
/simple/questions.txt:
--------------------------------------------------------------------------------
1 | How many beats are there per measure in 2/4 time? 2
2 | In what family of instruments is the piano? percussion
3 | How many strings does a violin have? 4
4 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 2/randpick.py:
--------------------------------------------------------------------------------
1 | from random import shuffle
2 | names = ['Eric', 'Sam', 'Ethan', 'Chris', 'Kurt']
3 | shuffle(names)
4 | for name in names:
5 | print(name)
6 |
--------------------------------------------------------------------------------
/simple/todo.py:
--------------------------------------------------------------------------------
1 | items = []
2 |
3 | while True:
4 | item = input('Item? ')
5 | if item:
6 | items.append(item)
7 | else:
8 | break
9 | print(items)
10 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 8/LessonPlan.txt:
--------------------------------------------------------------------------------
1 | Computer Programming with Dave Briccetti
2 | Wed, May 19, 2004, Introduction to Python, Concise Notes
3 |
4 | Outline
5 |
6 | 1) CGI with Python
7 |
8 |
--------------------------------------------------------------------------------
/Course-2004/Misc/secret.py:
--------------------------------------------------------------------------------
1 | word = input("Enter your message: ")
2 | print('Here is your message, in "secret" code:')
3 |
4 | for n in word:
5 | print(ord(n), end=' ')
6 |
7 |
8 |
--------------------------------------------------------------------------------
/simple/add_robot.py:
--------------------------------------------------------------------------------
1 | robot_names = ['robbie', 'data']
2 | new_name = input('What is the new robot name? ')
3 | robot_names.append(new_name)
4 | robot_names.sort()
5 |
6 | print(robot_names)
7 |
--------------------------------------------------------------------------------
/Web/flask/simple.py:
--------------------------------------------------------------------------------
1 | from flask import Flask
2 | app = Flask(__name__)
3 |
4 | @app.route("/")
5 | def index():
6 | return "Hi from a webapp!"
7 |
8 | app.run(host='0.0.0.0', debug=True)
9 |
--------------------------------------------------------------------------------
/simple/input-score.py:
--------------------------------------------------------------------------------
1 | score = int(input('What is your score? '))
2 | if score > 90:
3 | print('Great score!')
4 | elif score > 80:
5 | print('Not bad')
6 | else:
7 | print('You need more work')
8 |
--------------------------------------------------------------------------------
/Pygame/SimplePygame/PlaySound.py:
--------------------------------------------------------------------------------
1 | import pygame, time
2 |
3 | pygame.init()
4 | sound = pygame.mixer.Sound('powerup.wav')
5 | sound.play(loops=2)
6 | time.sleep(3) # Run long enough to hear the sound
7 | pygame.quit()
8 |
--------------------------------------------------------------------------------
/Plotting/sine_scatter.py:
--------------------------------------------------------------------------------
1 | from math import sin, pi
2 | import matplotlib.pyplot as plt
3 |
4 | domain = range(0, 360, 6)
5 | sines = [sin(angle / 360 * 2 * pi) for angle in domain]
6 | plt.scatter(domain, sines)
7 | plt.show()
8 |
--------------------------------------------------------------------------------
/simple/input.py:
--------------------------------------------------------------------------------
1 | ''' Shows examples of the input function '''
2 |
3 | name = input('What is your name? ')
4 | print('Hello, ' + name)
5 |
6 | age = int(input('What is your age, in years? '))
7 | print('Twice your age is', age * 2)
8 |
--------------------------------------------------------------------------------
/Web/Screen-Scraping/ss1.py:
--------------------------------------------------------------------------------
1 | import requests
2 | from bs4 import BeautifulSoup
3 |
4 | html_doc = requests.get('https://www.google.com/search?q=mlb').text
5 |
6 | soup = BeautifulSoup(html_doc, 'html.parser')
7 | print(soup.prettify())
8 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 9/LessonPlan.txt:
--------------------------------------------------------------------------------
1 | Computer Programming with Dave Briccetti
2 | Wed, June 2, 2004, Introduction to Python, Concise Notes
3 |
4 | Outline
5 |
6 | 1) Installing and using Apache Server
7 | 2) Pygame self-study
8 | 3)
9 |
10 |
--------------------------------------------------------------------------------
/simple/loops.py:
--------------------------------------------------------------------------------
1 | nums = (5, 7, 8)
2 | total = 0
3 |
4 | for num in nums:
5 | print('A number: ',num)
6 | total += num
7 |
8 | print('The total is',total)
9 |
10 | # You could replace all the above with
11 | # print(sum(nums))
12 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 4/dict.py:
--------------------------------------------------------------------------------
1 | wc = dict()
2 | while 1:
3 | word = eval(input("Enter a word: "))
4 | if word == "":
5 | break
6 | if word in wc:
7 | wc[word] += 1
8 | else:
9 | wc[word] = 1
10 |
11 | print(wc)
12 |
--------------------------------------------------------------------------------
/Course-2004/Misc/test.py:
--------------------------------------------------------------------------------
1 | import math
2 | diameter = float(input('Diameter of bike wheel in inches?'))
3 | rotate = int(input('How many rotations did the bike turn?'))
4 | dist = diameter * math.pi * rotate
5 | print('The bike travelled %.0f inches' % dist)
6 |
--------------------------------------------------------------------------------
/Web/search.py:
--------------------------------------------------------------------------------
1 | import requests
2 |
3 | search_arg = 'Guido von Rossum'
4 | response = requests.get('https://api.duckduckgo.com/?q=%s&format=json&pretty=1' % search_arg).json()
5 | print('From {}: {}'.format(response['AbstractSource'], response['Abstract']))
6 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 3/list.py:
--------------------------------------------------------------------------------
1 | l = list()
2 | while 1:
3 | word = eval(input("Enter a word: "))
4 | if word == "":
5 | break
6 | if word in l:
7 | print('already in')
8 | else:
9 | l.append(word)
10 |
11 | print(l)
12 |
--------------------------------------------------------------------------------
/Web/flask/templates/simple2.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Simple 2
6 |
7 |
8 | Fortune Teller
9 | Here is your fortune: {{fortune}}
10 |
11 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 6/LessonPlan.txt:
--------------------------------------------------------------------------------
1 | Computer Programming with Dave Briccetti
2 | Wed, Apr 21, 2004, Introduction to Python, Concise Notes
3 |
4 | Outline
5 |
6 | 1) Presentation of homework/show and tell
7 | 2) XML
8 | 3) TKinter
9 | 4) TCP sockets
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Harder/fibonacci_gen.py:
--------------------------------------------------------------------------------
1 | def fibs(highest):
2 | current = 1
3 | next = 2
4 | while current <= highest:
5 | yield current
6 | current, next = next, current + next
7 |
8 |
9 | g = fibs(13)
10 | print(list(g))
11 |
12 | # Produces 1 2 3 5 8 13
--------------------------------------------------------------------------------
/Course-2004/Lesson 2/class1.py:
--------------------------------------------------------------------------------
1 | class Robot:
2 | def workOn(self, task):
3 | print(('I am working on', task))
4 | def giveStatus(self):
5 | print('Everything is fine')
6 |
7 | robot1 = Robot()
8 | robot1.workOn('welding')
9 | robot1.giveStatus()
10 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 2/hw3b.py:
--------------------------------------------------------------------------------
1 | def getNum():
2 | num = float(eval(input('Please enter a number: ')))
3 | if num < 0:
4 | num *= 2
5 | else:
6 | num *= 3
7 | return num
8 |
9 | result = getNum() + getNum()
10 | print(('The result is', result))
11 |
--------------------------------------------------------------------------------
/Turtle/multi.py:
--------------------------------------------------------------------------------
1 | from turtle import speed, Turtle
2 | from random import randint
3 | speed('fast')
4 |
5 | turtles = [Turtle() for n in range(5)]
6 |
7 | for n in range(10):
8 | for t in turtles:
9 | t.forward(randint(50, 100))
10 | t.right(randint(85, 95))
11 |
--------------------------------------------------------------------------------
/Pygame/Bees/util.py:
--------------------------------------------------------------------------------
1 | import os
2 | import pygame
3 |
4 | def loadImage(file):
5 | file = os.path.join('media', file)
6 | surface = pygame.image.load(file)
7 | return surface.convert_alpha()
8 |
9 | def loadImages(*files):
10 | return [loadImage(file) for file in files]
11 |
--------------------------------------------------------------------------------
/Pygame/One Bee/util.py:
--------------------------------------------------------------------------------
1 | import os
2 | import pygame
3 |
4 | def loadImage(file):
5 | file = os.path.join('media', file)
6 | surface = pygame.image.load(file)
7 | return surface.convert_alpha()
8 |
9 | def loadImages(*files):
10 | return [loadImage(file) for file in files]
11 |
--------------------------------------------------------------------------------
/Harder/spellcheck.py:
--------------------------------------------------------------------------------
1 | with open('words.txt') as file:
2 | words = {line.strip() for line in file}
3 |
4 | sentence = input('Enter a sentence and I will spell check every word => ')
5 |
6 | set_words = set(sentence.split(' '))
7 | print('Misspelled words: ' + ', '.join(set_words.difference(words)))
8 |
--------------------------------------------------------------------------------
/Pygame/Bee Invaders/util.py:
--------------------------------------------------------------------------------
1 | import os
2 | import pygame
3 |
4 | def loadImage(file):
5 | file = os.path.join('media', file)
6 | surface = pygame.image.load(file)
7 | return surface.convert_alpha()
8 |
9 | def loadImages(*files):
10 | return [loadImage(file) for file in files]
11 |
--------------------------------------------------------------------------------
/Pygame/Two Bees/util.py:
--------------------------------------------------------------------------------
1 | import os
2 | import pygame
3 |
4 | def loadImage(file):
5 | file = os.path.join('media', file)
6 | surface = pygame.image.load(file)
7 | return surface.convert_alpha()
8 |
9 | def loadImages(*files):
10 | return [loadImage(file) for file in files]
11 |
--------------------------------------------------------------------------------
/simple/cointoss.py:
--------------------------------------------------------------------------------
1 | from random import randint
2 |
3 | numHeads = 0
4 | numTails = 0
5 |
6 | for t in range(100):
7 | if randint(1, 2) == 1:
8 | numHeads += 1
9 | else:
10 | numTails += 1
11 |
12 | print(f'There were {numHeads} heads and {numTails} tails')
13 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 2/homework/2.py:
--------------------------------------------------------------------------------
1 | def getNum():
2 | num = float(eval(input('Please enter a number: ')))
3 | if num < 0:
4 | num *= 2
5 | else:
6 | num *= 3
7 | return num
8 |
9 | num1 = getNum()
10 | num2 = getNum()
11 |
12 | print(('The result is', num1 + num2))
13 |
--------------------------------------------------------------------------------
/Input-Output/filterio.py:
--------------------------------------------------------------------------------
1 | with open('in.txt') as in_file:
2 | with open('out.txt', 'w') as out_file:
3 | for line in in_file:
4 | words = line.strip().split(' ')
5 | for word in words:
6 | if 'e' not in word:
7 | out_file.write(word + ' ')
8 |
--------------------------------------------------------------------------------
/Object-Oriented/cat.py:
--------------------------------------------------------------------------------
1 | '''Simple example defining a Cat class, and instantiating a cat from it'''
2 |
3 | class Cat(object):
4 | def meow(self):
5 | print("Meow!")
6 |
7 | def eat(self):
8 | print("Glub glub glub")
9 |
10 | cat = Cat()
11 | cat.meow()
12 | cat.eat()
13 |
--------------------------------------------------------------------------------
/Turtle/multi_polygons.py:
--------------------------------------------------------------------------------
1 | import turtle as t
2 |
3 | t.speed('fastest')
4 |
5 | sides = int(input('Num sides in the largest polygon? '))
6 | for sides in range(3, sides + 1):
7 | for side in range(sides):
8 | t.fd(100)
9 | t.right(360 / sides)
10 |
11 | input('Press enter to continue')
12 |
--------------------------------------------------------------------------------
/simple/challenges/challenges1.html:
--------------------------------------------------------------------------------
1 |
2 | Problems
3 |
4 | - Write a program that displays hello
5 |
- Prompts for someone's name and stores it into a variable called name
6 |
- Write a program that recognizes people's names and gives individualized greetings (see if.py)
7 |
8 |
9 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 3/Homework/1.py:
--------------------------------------------------------------------------------
1 | import random
2 | strings = []
3 |
4 | while 1:
5 | s = eval(input("Give us a string, gov. "))
6 | if s == "":
7 | break
8 | strings.append(s);
9 |
10 | random.shuffle(strings)
11 | print(("Here are your strings, all nice and shuffled: ", strings))
12 |
13 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 2/hw3.py:
--------------------------------------------------------------------------------
1 | num1 = float(eval(input('Please enter a number: ')))
2 | if num1 < 0:
3 | num1 *= 2
4 | else:
5 | num1 *= 3
6 |
7 | num2 = float(eval(input('Please enter a number: ')))
8 | if num2 < 0:
9 | num2 *= 2
10 | else:
11 | num2 *= 3
12 |
13 | print(('The result is', num1 + num2))
14 |
--------------------------------------------------------------------------------
/simple/functions2.py:
--------------------------------------------------------------------------------
1 | def celsius_to_fahrenheit(celsius_temp: float) -> float:
2 | return celsius_temp * 1.8 + 32
3 |
4 | celsius_temp = float(input('What is the temperature in Celsius? '))
5 | fahrenheit_temp = celsius_to_fahrenheit(celsius_temp)
6 | print(f'In old fashioned Fahrenheit degrees, that is {fahrenheit_temp}')
7 |
--------------------------------------------------------------------------------
/simple/dice_graph.py:
--------------------------------------------------------------------------------
1 | from random import randint
2 |
3 | outcomes = [0] * 13
4 |
5 | for _ in range(1_000):
6 | outcome = randint(1, 6) + randint(1, 6)
7 | outcomes[outcome] += 1
8 |
9 | for outcome_index, outcome in enumerate(outcomes[2:], 2):
10 | print(f'{outcome_index:2}: {"*" * outcome} {outcome}')
11 |
12 |
--------------------------------------------------------------------------------
/simple/validatedinput.py:
--------------------------------------------------------------------------------
1 | while True: # Continue while input is invalid
2 | try:
3 | num = int(input('Integer between 1 and 10? '))
4 | if num > 0 and num < 11:
5 | break
6 | except ValueError:
7 | print("That wasn't even an integer.")
8 |
9 | print('Your number is %d' % num)
10 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 2/calc.py:
--------------------------------------------------------------------------------
1 | class Calculator:
2 | def add(self, num1, num2):
3 | return num1 + num2
4 | def divide(self, num1, num2):
5 | return num1 / num2
6 |
7 | calc = Calculator()
8 | print((calc.add(2.5, 5)))
9 | try:
10 | print((calc.divide(3,1)))
11 | except ZeroDivisionError:
12 | print('Oops')
13 |
--------------------------------------------------------------------------------
/simple/inputnum.py:
--------------------------------------------------------------------------------
1 | def getNumeric(prompt):
2 | while True:
3 | response = input(prompt)
4 | try:
5 | return int(response)
6 | except ValueError:
7 | print("Please enter a number.")
8 |
9 | if __name__ == '__main__':
10 | age = getNumeric('What is your age? ')
11 | print(age)
12 |
--------------------------------------------------------------------------------
/simple/cats-dict.py:
--------------------------------------------------------------------------------
1 |
2 | cats = {}
3 | cats['tabby'] = 'The tabby cat...'
4 | cats['persian'] = 'This cat...'
5 | cats['hairless'] = 'This type of cat, which horrifies most people, ...'
6 |
7 | catType = input('What type of cat? ')
8 |
9 | if catType not in cats:
10 | print('Does not compute!')
11 | else:
12 | print(cats[catType])
13 |
--------------------------------------------------------------------------------
/Plotting/scatter.py:
--------------------------------------------------------------------------------
1 | # An example from matplotlib
2 |
3 | import numpy as np
4 | import matplotlib.pyplot as plt
5 |
6 | N = 50
7 | x = np.random.rand(N)
8 | y = np.random.rand(N)
9 | colors = np.random.rand(N)
10 | radius = 15 * np.random.rand(N)
11 | area = np.pi * radius ** 2
12 |
13 | plt.scatter(x, y, s=area, c=colors, alpha=0.5)
14 | plt.show()
--------------------------------------------------------------------------------
/Course-2004/Lesson 2/fn.py:
--------------------------------------------------------------------------------
1 | def getNum(prompt = 'Positive real number, please: '):
2 | while 1:
3 | try:
4 | num = float(eval(input(prompt)))
5 | if num >= 0:
6 | return num
7 | except ValueError:
8 | print('Bad number')
9 |
10 | num = getNum(prompt = 'Give it! ')
11 | print(num)
12 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 1/drt.py:
--------------------------------------------------------------------------------
1 | rateKph = float(eval(input('Rate (kilometers per hour)? ')))
2 | rateKpm = rateKph / 60.0
3 |
4 | print(('%f km per hour (%f km per minute)' % (rateKph, rateKpm)))
5 | print('Time\tDistance')
6 | print('(Mins)\t(km)')
7 |
8 | for mins in range(16):
9 | dist = rateKpm * mins
10 | print(('%.2f \t %.2f' % (mins, dist)))
11 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 6/adventure3/commandline.py:
--------------------------------------------------------------------------------
1 | class CommandLine:
2 | def set(self, line):
3 | self.line = line
4 | spaceIndex = line.find(' ')
5 | if spaceIndex > 0:
6 | self.cmd = line[0:spaceIndex]
7 | self.args = line[spaceIndex + 1:]
8 | else:
9 | self.cmd = line
10 | self.args = ""
11 |
12 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 6/adventure4/commandline.py:
--------------------------------------------------------------------------------
1 | class CommandLine:
2 | def set(self, line):
3 | self.line = line
4 | spaceIndex = line.find(' ')
5 | if spaceIndex > 0:
6 | self.cmd = line[0:spaceIndex]
7 | self.args = line[spaceIndex + 1:]
8 | else:
9 | self.cmd = line
10 | self.args = ""
11 |
12 |
--------------------------------------------------------------------------------
/Input-Output/score_reader.py:
--------------------------------------------------------------------------------
1 | hs_name = ''
2 | hs_score = 0
3 |
4 | with open('scores.csv') as file:
5 | for line in file:
6 | name, score_str = line.strip().split(',')
7 | score = int(score_str)
8 | if score > hs_score:
9 | hs_name = name
10 | hs_score = score
11 |
12 | print('%s has the highest score, %d' % (hs_name, hs_score))
13 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /Adventure/nbproject/private/
2 | *.pyc
3 | /simple/nbproject/private/
4 | /IfExample/nbproject/private/
5 | /SimplePygame/nbproject/
6 | /Bees/nbproject/private/
7 | /Sprite1/nbproject/private/
8 | /TileDraw/nbproject/private/
9 | /NewPythonProject/nbproject/private
10 | /nbproject/private/
11 | Web/name-picker/.idea
12 | .idea
13 | doc/.ipynb_checkpoints
14 | .ipynb_checkpoints
15 |
--------------------------------------------------------------------------------
/Harder/commonwords.py:
--------------------------------------------------------------------------------
1 | with open('common-words.txt') as file:
2 | common_words = {line.strip().lower() for line in file if not line.startswith('#')}
3 |
4 | while True:
5 | sentence = input('-> ')
6 | if not sentence:
7 | break
8 | for word in sentence.split(' '):
9 | print(word if word.lower() in common_words else '*' * len(word), end=' ')
10 | print()
11 |
--------------------------------------------------------------------------------
/Harder/picker.py:
--------------------------------------------------------------------------------
1 | # This program pops names off a list in random sequence
2 |
3 | from random import randint
4 | from time import sleep
5 |
6 | remaining_names = 'sue mary hari fred eric menlo'.split()
7 |
8 | while remaining_names:
9 | pop_index = randint(0, len(remaining_names) - 1)
10 | popped_name = remaining_names.pop(pop_index)
11 | print(popped_name)
12 | sleep(1)
13 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 8/homework.txt:
--------------------------------------------------------------------------------
1 | Homework 8
2 | Due June 1, 2004, 5 PM
3 |
4 | Do 0 or more of the following:
5 |
6 | 1) Install Apache Web Server (www.apache.org) and get the Lesson 8 sample running
7 |
8 | 2) Read about CGI with Python: http://python.org/doc/lib/module-cgi.html
9 |
10 | 3) Get more experience with XML and Python
11 |
12 | 4) Review all the class notes on TKinter
13 |
14 |
--------------------------------------------------------------------------------
/Web/flask/simple2.py:
--------------------------------------------------------------------------------
1 | from random import choice
2 | from flask import Flask, render_template
3 |
4 | app = Flask(__name__)
5 |
6 | @app.route("/")
7 | def index():
8 | fortune = choice(
9 | 'You will have good health',
10 | 'You will not have good health'
11 | )
12 | return render_template('simple2.html', fortune=fortune)
13 |
14 | app.run(host='127.0.0.1', debug=True)
15 |
--------------------------------------------------------------------------------
/Pygame/SimplePygame/text.py:
--------------------------------------------------------------------------------
1 | from time import sleep
2 | import pygame
3 | from pygame.locals import Color
4 |
5 | pygame.init()
6 | screen = pygame.display.set_mode((620, 115), 0)
7 | font = pygame.font.Font(None, 150)
8 | message = font.render('Hello, world', True, Color('green'))
9 | screen.fill(Color('black'))
10 | screen.blit(message, (8, 8))
11 | pygame.display.flip()
12 | sleep(3)
13 | pygame.quit()
14 |
--------------------------------------------------------------------------------
/simple/functions3.py:
--------------------------------------------------------------------------------
1 | from random import randint
2 |
3 | def tossCoins():
4 | for n in range(3):
5 | if randint(1, 2) == 1:
6 | print('heads')
7 | else:
8 | print('tails')
9 |
10 | print('Hello, and welcome to the simulation')
11 | tossCoins()
12 | print('Now for intermission')
13 | print("Let's flip some more coins")
14 | tossCoins()
15 | print('We are done')
16 |
--------------------------------------------------------------------------------
/simple/lists.py:
--------------------------------------------------------------------------------
1 | foods = ['soup', 'oranges']
2 | print('foods is', foods)
3 |
4 | foods.append('milk')
5 | print ('After appending milk, foods is', foods)
6 |
7 | print('foods[0] is', foods[0])
8 | print('foods[1] is', foods[1])
9 |
10 | foods.append(input('Enter a food: '))
11 | print ('foods is now', foods)
12 |
13 | print('Looping through foods: ')
14 | for food in foods:
15 | print('A food:', food)
16 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 2/homework/3.py:
--------------------------------------------------------------------------------
1 | def getSpecialNum():
2 | while 1:
3 | try:
4 | num = float(eval(input('Enter a number > 10: ')))
5 | if num > 10:
6 | break
7 |
8 | print('That is not > 10')
9 |
10 | except (ValueError):
11 | print('That is not a number')
12 |
13 | print('Thank you')
14 |
15 | getSpecialNum()
16 |
--------------------------------------------------------------------------------
/simple/i-o.py:
--------------------------------------------------------------------------------
1 | with open('scores.txt') as files:
2 | lines = files.readlines()
3 |
4 | scores = []
5 |
6 | for line in lines:
7 | line_strip = line.strip()
8 | name, score_str = line_strip.split(',')
9 | score = int(score_str)
10 | scores.append(score)
11 | print('The score of %s is %d' % (name, score))
12 |
13 | print('Min: %d, avg: %d, max: %d' % (min(scores), sum(scores) / len(scores) ,max(scores)))
14 |
--------------------------------------------------------------------------------
/Turtle/random_lines.py:
--------------------------------------------------------------------------------
1 | from sys import exit
2 | import turtle as t
3 | from random import randint, choice
4 |
5 | colors = ('blue', 'red', 'green', 'yellow')
6 | t.speed('fastest')
7 | t.pensize(20)
8 | while True:
9 | t.color(choice(colors))
10 | t.fd(randint(20, 200))
11 | t.rt(randint(-45, 45))
12 | if abs(t.pos()[0]) > 500 or abs(t.pos()[1]) > 500:
13 | t.setpos((randint(-100, 100), (randint(-100, 100))))
14 |
--------------------------------------------------------------------------------
/simple/count_enters.py:
--------------------------------------------------------------------------------
1 | from time import time, sleep
2 |
3 | messages = ['How many times can you press enter in ten seconds?', 'Get ready', 3, 2, 1, 'Go!']
4 |
5 | for message in messages:
6 | sleep(1)
7 | print(message)
8 |
9 | start_time = time()
10 | end_time = start_time + 10
11 | presses = 0
12 |
13 | while time() < end_time:
14 | input()
15 | presses += 1
16 |
17 | print(f'You pressed enter {presses} times.')
18 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 2/TKinter/very-simple-gui.py:
--------------------------------------------------------------------------------
1 | from tkinter import *
2 |
3 | class Application(Frame):
4 | def createWidgets(self):
5 | self.quitButton = Button(self, text = 'Quit', command = self.quit)
6 | self.quitButton.pack()
7 | def __init__(self, master=None):
8 | Frame.__init__(self, master)
9 | self.pack()
10 | self.createWidgets()
11 |
12 | app = Application()
13 | app.mainloop()
14 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 4/picksim.py:
--------------------------------------------------------------------------------
1 | import random
2 |
3 | def getPick():
4 | return random.choice(("bananas", "turnips", "radishes", "papayas"))
5 |
6 | picks = {}
7 | numPicks = 100
8 |
9 | for t in range(numPicks):
10 | pick = getPick()
11 | if pick in picks:
12 | picks[pick] += 1
13 | else:
14 | picks[pick] = 1
15 |
16 | for n in list(picks.keys()):
17 | print(("%10s" % n, 'X' * picks[n]))
18 |
19 |
--------------------------------------------------------------------------------
/Web/name-picker/templates/names.html:
--------------------------------------------------------------------------------
1 | {% extends "layout.html" %}
2 | {% block content %}
3 |
4 |
5 |
{{ name }}
6 |
7 |
8 | {% if remaining %}
9 | Names remaining: {{ remaining }}.
10 | {% else %}
11 | There are no more names
12 | Reset
13 | {% endif %}
14 | {% endblock %}
15 |
--------------------------------------------------------------------------------
/Course-2004/Misc/guess.py:
--------------------------------------------------------------------------------
1 | import random
2 | num = random.randint(1,100)
3 | guess = 0
4 |
5 | print("I am thinking of a number between 1 and 100. See if you can guess it.")
6 |
7 | while (guess != num):
8 |
9 | guess = int(input("Your guess: "))
10 |
11 | if guess == num:
12 | print("That's right!")
13 | elif guess < num:
14 | print(guess, "is too low")
15 | else:
16 | print(guess, "is too high")
17 |
18 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 7/problem2.py:
--------------------------------------------------------------------------------
1 | from xml.dom.ext.reader.Sax import FromXmlFile
2 | from xml.dom.NodeFilter import NodeFilter
3 |
4 | root = FromXmlFile('problem2.xml')
5 | walker = root.createTreeWalker(root.documentElement,
6 | NodeFilter.SHOW_ELEMENT, None, 0)
7 |
8 | while 1:
9 | print(walker.currentNode)
10 | print(walker.currentNode.attributes)
11 | next = walker.nextNode()
12 | if next is None: break
13 |
--------------------------------------------------------------------------------
/Plotting/citytemps.py:
--------------------------------------------------------------------------------
1 | # Inspired by an example from matplotlib
2 |
3 | import matplotlib.pyplot as plt
4 | import numpy as np
5 |
6 | cities = ['Walnut Creek', 'Lafayette', 'Moraga']
7 | y_pos = np.arange(len(cities))
8 | temperature = 10 + 10 * np.random.rand(len(cities))
9 |
10 | plt.barh(y_pos, temperature, align='center', alpha=0.4)
11 | plt.yticks(y_pos, cities)
12 | plt.xlabel('Temperature')
13 | plt.title('Current Temperatures')
14 | plt.show()
15 |
--------------------------------------------------------------------------------
/Turtle/spirals.py:
--------------------------------------------------------------------------------
1 | import turtle as t
2 | from random import choice
3 | from time import sleep
4 |
5 | colors = ('red', 'green', 'blue', 'yellow', 'black')
6 | t.speed('fastest')
7 | t.pu()
8 | t.goto(400, -100)
9 | t.setheading(90)
10 | t.pd()
11 | t.pensize(10)
12 | turn = 10
13 | length = 100
14 | while length > 20:
15 | t.color(choice(colors))
16 | t.fd(length)
17 | t.left(turn)
18 | turn += 0.1
19 | length *= 0.99
20 |
21 | sleep(1000)
--------------------------------------------------------------------------------
/Web/showip.py:
--------------------------------------------------------------------------------
1 | # Uses https://pypi.python.org/pypi/netifaces
2 |
3 | import netifaces
4 | for interface_name in netifaces.interfaces():
5 | addrs_for_iface = netifaces.ifaddresses(interface_name)
6 | inet_addrs = addrs_for_iface.get(netifaces.AF_INET)
7 | if inet_addrs:
8 | for addr in inet_addrs:
9 | ip_address = addr['addr']
10 | if ip_address != '127.0.0.1':
11 | print(interface_name, ip_address)
12 |
--------------------------------------------------------------------------------
/simple/dicethrowcount.py:
--------------------------------------------------------------------------------
1 | from random import randint
2 |
3 | num_dice = 2
4 | num_sides = 6
5 | num_throws = 10000
6 | list_len = num_dice * num_sides + 1
7 |
8 | counts = [0 for n in range(list_len)]
9 |
10 | for i in range(num_throws):
11 | outcome = sum([randint(1, num_sides) for j in range(num_dice)])
12 | counts[outcome] += 1
13 |
14 | for outcome, count in enumerate(counts[num_dice: list_len]):
15 | print(f'{outcome + num_dice:3,}\t{count:6,}')
16 |
--------------------------------------------------------------------------------
/simple/higher-order-functions.py:
--------------------------------------------------------------------------------
1 | def map(nums_list, operation):
2 | ''' Return a sequence of values obtained by applying the operation
3 | function to each number in nums_list. '''
4 | return [operation(num) for num in nums_list]
5 |
6 | def double(num):
7 | return num * 2
8 |
9 | def triple(num):
10 | return num * 3
11 |
12 | nums_list = (1, 3, -10)
13 |
14 | for operation in (double, triple):
15 | print(map(nums_list, operation))
16 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 4/homework/1.py:
--------------------------------------------------------------------------------
1 | gameChars = {}
2 |
3 | while 1:
4 | name = eval(input("Player name? "))
5 | if name == "":
6 | break
7 | magic = int(eval(input("Magic power value? ")))
8 | gameChars[name] = magic
9 |
10 | print("These characters have magic power values over 80:")
11 |
12 | for key in gameChars:
13 | if gameChars[key] > 80:
14 | print(key)
15 |
16 | print([key for key in gameChars if gameChars[key] > 80])
17 |
--------------------------------------------------------------------------------
/Harder/sieve.py:
--------------------------------------------------------------------------------
1 | import math
2 | from time import time
3 | start_time = time()
4 | HIGHEST = 100
5 | sieve = [True] * (HIGHEST + 1)
6 |
7 | for prime in range(2, int(math.sqrt(HIGHEST + 1))):
8 | for n in range(prime * 2, HIGHEST + 1, prime):
9 | sieve[n] = False
10 |
11 | elapsed_time = time() - start_time
12 |
13 | print()
14 | print(elapsed_time)
15 |
16 | for n in range(1, HIGHEST + 1):
17 | if sieve[n]:
18 | print(n, end=' ')
19 |
20 |
--------------------------------------------------------------------------------
/Web/weather.py:
--------------------------------------------------------------------------------
1 | import requests
2 |
3 | with open('openweathermap.txt') as file:
4 | key = file.read().strip() # Put your API key in this file
5 |
6 |
7 | def temp_at_location(location):
8 | url = f'http://api.openweathermap.org/data/2.5/weather?q={location}&mode=json&units=metric&APPID={key}'
9 | json = requests.get(url).json()
10 | return json['main']['temp']
11 |
12 | if __name__ == '__main__':
13 | print(f'{temp_at_location("94549"):.1f}')
14 |
--------------------------------------------------------------------------------
/simple/compound-output.py:
--------------------------------------------------------------------------------
1 | name = "Sue"
2 | age = 12
3 | score = 95
4 |
5 | print(name, age, score)
6 | print(name + str(age) + str(score))
7 | print(name + " " + str(age) + " " + str(score))
8 | print(name + ", " + str(age) + ", " + str(score))
9 |
10 | print(name + ", age", str(age) + ", scored", score)
11 | print(name + ", age", str(age) + ", scored " + str(score))
12 | print("%s, age %d, scored %x" % (name, age, score))
13 | print(f"{name}, age {age}, scored {score}")
14 |
--------------------------------------------------------------------------------
/simple/greet-dict.py:
--------------------------------------------------------------------------------
1 | messages = {
2 | 'sam': 'Hey, little brother!',
3 | 'fred': 'Congrats on the new lawn-mowing job.',
4 | 'betty': "Where's that five dollars you owe me?",
5 | }
6 |
7 | names = list(messages.keys())
8 | names.sort()
9 | print(', '.join(names))
10 |
11 | name = input('What is your name? ')
12 | nameLower = name.lower()
13 |
14 | if nameLower in messages:
15 | print(messages[nameLower])
16 | else:
17 | print("I don't know any " + name)
18 |
--------------------------------------------------------------------------------
/Web/Treasure-Hunt/thclient.py:
--------------------------------------------------------------------------------
1 | import requests
2 |
3 | treasure_found = False
4 | URL_START = 'http://localhost:5000'
5 | clue_loc = '/'
6 |
7 | while not treasure_found:
8 | print('Going to', clue_loc)
9 | resp = requests.get(URL_START + clue_loc)
10 | if resp.text == 'You have reached the treasure!':
11 | treasure_found = True
12 | print(resp.text)
13 | else:
14 | print('Clue from %s: %s' % (clue_loc, resp.text))
15 | clue_loc = resp.text
16 |
--------------------------------------------------------------------------------
/Pygame/SimplePygame/Challenges.html:
--------------------------------------------------------------------------------
1 |
2 | Challenges
3 |
4 | - Change the background color to one you prefer
5 |
- Replace the sprite with one of your own
6 |
- Make the sprite move left, up, and down
7 |
- Add a second sprite and control it with different keys
8 |
- Add one or more computer-controlled characters that move around in various ways
9 |
10 |
11 |
--------------------------------------------------------------------------------
/Harder/wordgame.py:
--------------------------------------------------------------------------------
1 | from random import choice
2 |
3 | with open('common-words.txt') as file:
4 | all_words = [line.strip().lower() for line in file if not line.startswith('#')]
5 |
6 | words = [choice(all_words) for n in range(10)]
7 |
8 | while True:
9 | letters = input('Letters? ')
10 | for word in words:
11 | if letters == word:
12 | print('You got ' + word)
13 | for letter in word:
14 | print(letter if letter in letters else '_', end='')
15 | print()
16 |
--------------------------------------------------------------------------------
/Object-Oriented/paddle.py:
--------------------------------------------------------------------------------
1 | class Paddle():
2 | def __init__(self, x, y):
3 | self.x = x
4 | self.y = y
5 | self.width = 20
6 | self.height = 80
7 |
8 | def draw(self):
9 | print('Drawing at %d, %d' % (self.x, self.y))
10 |
11 | def move(self, amount):
12 | self.y += amount
13 |
14 | left_paddle = Paddle(10, 10)
15 | left_paddle.draw()
16 | right_paddle = Paddle(400, 10)
17 | right_paddle.draw()
18 |
19 | left_paddle.move(1)
20 | left_paddle.draw()
21 |
22 |
--------------------------------------------------------------------------------
/simple/dieguess.py:
--------------------------------------------------------------------------------
1 | from random import randint
2 | print('Welcome to the die-guessing game')
3 | balance = 50
4 |
5 | while True:
6 | print('Your balance is %d' % balance)
7 | bet = int(input('How much do you bet? (0 to quit)'))
8 | if bet == 0:
9 | break
10 | throw = randint(1, 6)
11 | guess = int(input('What do you guess we rolled? '))
12 | if guess == throw:
13 | print('Right!')
14 | balance += 6 * bet
15 | else:
16 | print('Too bad')
17 | balance -= bet
18 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 1/cost.py:
--------------------------------------------------------------------------------
1 | costPerHour = int(eval(input('How much per hour? ')))
2 | numStudents = int(eval(input('How many students? ')))
3 | numHours = float(eval(input('How many hours? ')))
4 |
5 | costPerStudentPerHour = costPerHour / numStudents
6 | costPerStudent = costPerStudentPerHour * numHours
7 | totalCost = costPerHour * numHours
8 |
9 | print(('Total cost: $%.2f' % totalCost))
10 | print(('Cost per student per hour: $%.2f' % costPerStudentPerHour))
11 | print(('Total cost per student: $%.2f' % costPerStudent))
12 |
--------------------------------------------------------------------------------
/simple/high-low-game.py:
--------------------------------------------------------------------------------
1 | from random import randint
2 | print('''
3 | Welcome to the high-low guessing game.
4 | I am thinking of an integer between 1 and 100.
5 | ''')
6 |
7 | guess = None
8 | guesses = 0
9 | number = randint(1, 100)
10 |
11 | while guess != number:
12 | guesses += 1
13 | guess = int(input('What is your guess? '))
14 |
15 | if guess > number:
16 | print('Too high')
17 | elif guess < number:
18 | print('Too low')
19 |
20 | print('You found the number in', guesses, 'guesses')
21 |
--------------------------------------------------------------------------------
/simple/robots.py:
--------------------------------------------------------------------------------
1 | class Robot(object):
2 | def __init__(self, name):
3 | self.name = name
4 |
5 | def greet(self):
6 | print('Hi. I am %s.' % self.name)
7 |
8 | class EvilRobot(Robot):
9 | def __init__(self, name):
10 | super().__init__(name)
11 |
12 | def greet(self):
13 | print('I am %s, and I am not pleased to see you humans here!' % self.name)
14 |
15 | robots = (Robot("Robbie"), Robot("Data"), EvilRobot("Lor"))
16 |
17 | for robot in robots:
18 | robot.greet()
19 |
20 |
--------------------------------------------------------------------------------
/Harder/if.py:
--------------------------------------------------------------------------------
1 | '''Shows how to use if.'''
2 |
3 | print('''
4 | Welcome to my exciting game!
5 | Here are the instructions.
6 | Blah, blah.
7 | ''')
8 |
9 | player = input('What is your name? ')
10 | pl = player.lower()
11 | if pl in ('mom', 'dad'):
12 | print('Sorry, this game is just for kids')
13 | elif pl == 'sam':
14 | print('Hello little brother.')
15 | elif pl == 'jean':
16 | print('Hello little sister.')
17 | elif pl == 'pete':
18 | print('Hello uncle.')
19 | else:
20 | print('Nice to meet you,', player)
21 |
--------------------------------------------------------------------------------
/Pygame/InvisibleMaze/imageutil.py:
--------------------------------------------------------------------------------
1 | import os
2 | import pygame
3 |
4 | def loadImage(file, alpha=True):
5 | file = os.path.join('media', file)
6 | try:
7 | surface = pygame.image.load(file)
8 | except pygame.error:
9 | raise SystemExit, 'Could not load image "%s" %s'%(file, pygame.get_error())
10 | return surface.convert_alpha() if alpha else surface
11 |
12 | def loadImages(*files):
13 | imgs = []
14 | for file in files:
15 | imgs.append(loadImage(file))
16 | return imgs
17 |
18 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 7/problem1.py:
--------------------------------------------------------------------------------
1 | from xml.dom.ext.reader.Sax import FromXmlFile
2 | from xml.dom.NodeFilter import NodeFilter
3 |
4 | root = FromXmlFile('problem1.xml')
5 |
6 | walker = root.createTreeWalker(root.documentElement,
7 | NodeFilter.SHOW_ELEMENT, None, 0)
8 |
9 | while 1:
10 | nodeName = walker.currentNode.nodeName
11 |
12 | if nodeName == 'game':
13 | print("Hey, I found the game tag!")
14 |
15 | next = walker.nextNode()
16 |
17 | if next is None: break
18 |
--------------------------------------------------------------------------------
/Object-Oriented/robots.py:
--------------------------------------------------------------------------------
1 | class Robot(object):
2 | def __init__(self, name):
3 | self.name = name
4 |
5 | def greet(self):
6 | print('Hi, I am ' + self.name)
7 |
8 | class SuperRobot(Robot):
9 | def __init__(self, name):
10 | super().__init__(name)
11 |
12 | def greet(self):
13 | print('Watch out, human! I am %s and I am dangerous!' % self.name)
14 |
15 | robots = (SuperRobot("Robbie"), Robot("Marvin"), Robot("Rosie"), Robot('Data'))
16 |
17 | for robot in robots:
18 | robot.greet()
19 |
--------------------------------------------------------------------------------
/Pygame/SimplePygame/shapes.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from pygame.locals import *
3 |
4 | pygame.init()
5 | screen = pygame.display.set_mode((400, 300), 0)
6 | screen.fill(Color('black'))
7 | pygame.draw.rect(screen, Color('red'), Rect(10, 10, 100, 100))
8 | pygame.draw.circle(screen, Color('blue'), (200, 110), 50)
9 | pygame.display.flip()
10 |
11 | loop = True
12 | while loop:
13 | event = pygame.event.wait()
14 | if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
15 | loop = False
16 |
17 | pygame.quit()
18 |
--------------------------------------------------------------------------------
/Pygame/Bees/flower.py:
--------------------------------------------------------------------------------
1 | import random, pygame
2 | from util import loadImage
3 |
4 | class Flower(pygame.sprite.Sprite):
5 |
6 | @staticmethod
7 | def loadImages():
8 | Flower.image = loadImage('flower.png')
9 |
10 | def __init__(self, screenRect):
11 | pygame.sprite.Sprite.__init__(self)
12 | self.image = Flower.image
13 | imgRect = self.image.get_rect()
14 | self.rect = imgRect.move(random.randint(0, screenRect.width),
15 | random.randint(0, screenRect.height)).clamp(screenRect)
16 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 2/homework/5.py:
--------------------------------------------------------------------------------
1 | class InputCollector:
2 | def getSpecialNum(self):
3 | while 1:
4 | try:
5 | num = float(eval(input('Enter a number > 10: ')))
6 | if num > 10:
7 | break
8 |
9 | print('That is not > 10')
10 |
11 | except (ValueError):
12 | print('That is not a number')
13 |
14 | print('Thank you')
15 |
16 | inputCollector = InputCollector()
17 | inputCollector.getSpecialNum()
18 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 2/randpick2.py:
--------------------------------------------------------------------------------
1 | import random
2 |
3 | # names is a list of names, initally empty
4 | names = []
5 |
6 | # Keep looping until no name is entered
7 | while 1:
8 | name = eval(input('Name: '))
9 |
10 | # If no name given, exit loop with break
11 | if name == "":
12 | break
13 |
14 | # Add this name to the list of names
15 | names.append(name)
16 |
17 | # Mix up the list of names with shuffle
18 | random.shuffle(names)
19 |
20 | # Display all the shuffled names, one per line
21 | for name in names:
22 | print(name)
23 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 4/dicesim.py:
--------------------------------------------------------------------------------
1 | from random import randint
2 |
3 | def getThrow(maxValue):
4 | return randint(1, maxValue)
5 |
6 | throws = {}
7 | diceSides = 6
8 | numDice = 5
9 | numThrows = 100
10 | maxDiceSum = diceSides * numDice
11 |
12 | for n in range(1, maxDiceSum + 1):
13 | throws[n] = 0
14 |
15 | for t in range(numThrows):
16 | throwSum = 0
17 | for s in range(numDice):
18 | throwSum += getThrow(diceSides)
19 | throws[throwSum] += 1
20 |
21 | for n in range(numDice, maxDiceSum + 1):
22 | print(("%2d" % n, 'X' * throws[n]))
23 |
--------------------------------------------------------------------------------
/Pygame/Bee Invaders/projectile.py:
--------------------------------------------------------------------------------
1 | from pygame.sprite import Sprite
2 | from util import loadImage
3 |
4 | class Projectile(Sprite):
5 |
6 | def __init__(self, x, y):
7 | super().__init__()
8 | self.image = loadImage('projectile.png')
9 | self.rect = self.image.get_rect()
10 | self.x = x
11 | self.y = y
12 |
13 | def update(self):
14 | imgRect = self.image.get_rect()
15 | self.y -= 5
16 | if self.y < -imgRect.height / 2:
17 | self.kill()
18 | self.rect = imgRect.move(self.x, self.y)
19 |
--------------------------------------------------------------------------------
/Web/Treasure-Hunt/thserver.py:
--------------------------------------------------------------------------------
1 | '''
2 | A simple treasure hunt server.
3 | / -> /garden -> /shed -> /attic
4 | '''
5 | from flask import Flask
6 | app = Flask(__name__)
7 |
8 |
9 | @app.route('/')
10 | def start():
11 | return '/garden'
12 |
13 |
14 | @app.route('/garden')
15 | def garden():
16 | return '/shed'
17 |
18 |
19 | @app.route('/shed')
20 | def shed():
21 | return '/attic'
22 |
23 |
24 | @app.route('/attic')
25 | def attic():
26 | return "You have reached the treasure!"
27 |
28 |
29 | if __name__ == "__main__":
30 | app.run(host='0.0.0.0', debug=True)
--------------------------------------------------------------------------------
/Web/Screen-Scraping/air_quality.py:
--------------------------------------------------------------------------------
1 | import requests
2 | from bs4 import BeautifulSoup
3 | state = input('What state? (California) ').lower().replace(' ', '-') or "california"
4 | city = input('What city? ') .lower().replace(' ', '-')
5 | response = requests.get(f'https://www.iqair.com/us/usa/{state}/{city}')
6 | soup = BeautifulSoup(response.text, 'html.parser')
7 | aqi_elem = soup.find('p', class_='aqi-value__value')
8 | if aqi_elem:
9 | aqi_text = aqi_elem.text
10 | aqi_value = int(aqi_text)
11 | print(f'Air quality index: {aqi_value}')
12 | else:
13 | print('Not found')
14 |
--------------------------------------------------------------------------------
/Web/multi-joke-client.py:
--------------------------------------------------------------------------------
1 | import requests
2 |
3 | targets = (
4 | ('Ryan', 'http://192.168.1.128:8080/joke'),
5 | ('Nathan', 'http://192.168.1.221:5000/joke'),
6 | ('Alex', 'http://192.168.1.53:5000/joke'),
7 | ('Hari', 'http://192.168.1.102:5000/joke')
8 | )
9 |
10 | while True:
11 | for target_name, target_url in targets:
12 | try:
13 | resp = requests.get(target_url)
14 | print(target_name + ': ' + resp.text)
15 | except requests.exceptions.ConnectionError:
16 | print(target_name + ' refused connection')
17 |
--------------------------------------------------------------------------------
/simple/calculator.py:
--------------------------------------------------------------------------------
1 | '''A simple calculator using a dictionary to look up functions for operators'''
2 |
3 | def add(n1, n2): return n1 + n2
4 | def mult(n1, n2): return n1 * n2
5 |
6 | opers = {
7 | '+': add,
8 | '*': mult
9 | }
10 |
11 | print("Enter expressions like 23 * 10 or 2 - 5")
12 |
13 | while True:
14 | expr = input('> ')
15 | if expr:
16 | try:
17 | (op1, op, op2) = expr.split(' ')
18 | print(opers[op](int(op1), int(op2)))
19 | except Exception:
20 | print("Sorry, I couldn't make sense of that")
21 | else:
22 | break
23 |
--------------------------------------------------------------------------------
/Multithreading/simplethread.py:
--------------------------------------------------------------------------------
1 | from threading import Thread
2 | from time import sleep
3 | from random import random
4 |
5 | NUM_COUNTERS = 3
6 | COUNT_TO = 5
7 |
8 |
9 | def count_and_sleep():
10 | for n in range(COUNT_TO):
11 | seconds = random() / 2
12 | print('%2d. Waiting %.2f seconds.' % (n + 1, seconds))
13 | sleep(seconds)
14 |
15 |
16 | print('All in the main thread')
17 | for n in range(NUM_COUNTERS):
18 | count_and_sleep()
19 |
20 | print('')
21 | print('With multiple threads')
22 | for n in range(NUM_COUNTERS):
23 | thread = Thread(target=count_and_sleep)
24 | thread.start()
25 |
--------------------------------------------------------------------------------
/Pygame/SimplePygame/simple_color_grid.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from random import randint
3 | from pygame.locals import *
4 |
5 | pygame.init()
6 | screen = pygame.display.set_mode((96, 96), 0)
7 | bg_color = Color('black')
8 | colors = ('red', 'green', 'blue')
9 |
10 | screen.fill(bg_color)
11 |
12 | for x in range(3):
13 | for y in range(3):
14 | pygame.draw.rect(screen, Color(colors[y]), Rect(x * 32 + 1, y * 32 + 1, 30, 30))
15 |
16 | pygame.display.flip()
17 |
18 | while True:
19 | event = pygame.event.poll()
20 | if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
21 | break
22 |
23 | pygame.quit()
24 |
--------------------------------------------------------------------------------
/simple/functions1.py:
--------------------------------------------------------------------------------
1 | def letter_grade(score):
2 | if score < 60:
3 | grade = 'F'
4 | elif score < 70:
5 | grade = 'D'
6 | elif score < 80:
7 | grade = 'C'
8 | elif score < 90:
9 | grade = 'B'
10 | else:
11 | grade = 'A'
12 | return grade
13 |
14 | def shorter_letter_grade(score):
15 | for index, min in enumerate((90, 80, 70, 60, 0)):
16 | if score >= min:
17 | return 'ABCDF'[index]
18 |
19 | for score in range(55, 101):
20 | grade1 = letter_grade(score)
21 | grade2 = shorter_letter_grade(score)
22 | assert(grade1 == grade2)
23 | print(score, grade1)
24 |
--------------------------------------------------------------------------------
/Harder/Hash-Attack/hashbreak.py:
--------------------------------------------------------------------------------
1 | from hashlib import md5
2 | from permuter import chars_range, Permuter
3 |
4 |
5 | def hash_with_md5(string):
6 | return md5(bytes(string, 'utf-8')).hexdigest()
7 |
8 | plaintext = 'zoom'
9 | hashed_secret = hash_with_md5(plaintext)
10 |
11 | MAX_STRING_LENGTH = len(plaintext)
12 | CHARS = chars_range('a', 'z') + ' .'
13 | print(CHARS)
14 |
15 | permuter = Permuter(CHARS, MAX_STRING_LENGTH)
16 |
17 | for guess in permuter.next():
18 | hashed_guess = hash_with_md5(guess)
19 | if hashed_guess == hashed_secret:
20 | print('Found {:s} in {:,d} tries.'.format(guess, permuter.generated))
21 | break
22 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 3/Homework/2.py:
--------------------------------------------------------------------------------
1 | def getRoster():
2 | roster = []
3 | print('Enter names, one per line. Give an empty name when done.')
4 | while 1:
5 | name = eval(input('==> '))
6 | if name == "":
7 | break
8 | roster.append(name)
9 | return roster
10 |
11 | print('Math class')
12 | mathRoster = getRoster()
13 | print('English class')
14 | englishRoster = getRoster()
15 |
16 | print(('Math class:', mathRoster))
17 | print(('English class:', englishRoster))
18 |
19 | print('In both classes:')
20 |
21 | for name in mathRoster:
22 | if name in englishRoster:
23 | print(name)
24 |
25 |
26 |
--------------------------------------------------------------------------------
/Harder/list_comprehensions.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 | words: List[str] = 'a very fine cat goes to the dentist'.split()
4 |
5 | # Just keep the longer words
6 | # Naïve approach
7 |
8 | long_words = []
9 | for word in words:
10 | if len(word) > 3:
11 | long_words.append(word)
12 |
13 | print(long_words)
14 |
15 | # Make a list comprehension from the code of the naïve approach:
16 | # 1: start with []
17 | # 2: copy and paste what the list comprehension should produce
18 | # 3: copy and paste the for loop
19 | # 4: copy and paste the `if`
20 |
21 | long_words = [len(word) for word in words if len(word) > 3]
22 |
23 |
24 | print(long_words)
25 |
--------------------------------------------------------------------------------
/Pygame/Bees/score.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from pygame.locals import Color
3 |
4 | class Score(pygame.sprite.Sprite):
5 | def __init__(self):
6 | pygame.sprite.Sprite.__init__(self)
7 | self.font = pygame.font.Font(None, 20)
8 | self.color = Color('white')
9 | self.lastscore = -1
10 | self.score = 0
11 | self.update()
12 | self.rect = self.image.get_rect().move(10, 20)
13 |
14 | def update(self):
15 | if self.score != self.lastscore:
16 | self.lastscore = self.score
17 | msg = "Score: %d" % self.score
18 | self.image = self.font.render(msg, 0, self.color)
19 |
20 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 1/bikemove.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | print("""
4 | This program calculates how far your bike moved,
5 | given the wheel size and number of turns of the
6 | wheel.
7 | """)
8 |
9 | diam = float(eval(input("What is the diameter of your front wheel (in meters)? ")))
10 |
11 | # To calculate the circumference from the diameter, multiply by pi
12 | circ = diam * math.pi
13 |
14 | turns = float(eval(input("How many times did it turn? ")))
15 |
16 | # Each turn the bike moves forward by the circumference
17 | dist = circ * turns
18 |
19 | print(('The circumference of your wheel is %.2f meters.' % (circ)))
20 | print(('The bike travelled %.2f meters.' % dist))
21 |
--------------------------------------------------------------------------------
/Web/chat/chatserver.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from time import time
3 | from flask import Flask, request
4 |
5 | PLAIN_HEADER = {'Content-Type': 'text/plain; charset=utf-8'}
6 | logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(threadName)s %(message)s')
7 | log = logging.getLogger('chatserver')
8 | app = Flask(__name__)
9 | messages = []
10 |
11 |
12 | @app.route('/post//')
13 | def post_message(who, message):
14 | messages.append((time(), request.remote_addr, who, message))
15 | print(messages)
16 | return "Message saved.\n" + str(messages), 200, PLAIN_HEADER
17 |
18 | app.run(host='localhost', debug=True, threaded=True)
19 |
--------------------------------------------------------------------------------
/simple/challenges/challenges2.html:
--------------------------------------------------------------------------------
1 |
2 | Problems
3 |
4 | - Produce one or more random integers in the range -5,5
5 |
- Randomly choose from a sequence like ('Sam', 'Sue', 'Bill')
6 |
- Randomly choose a number between 1 and 3. Ask the user for
7 | a guess. Tell the user if the guess is right.
8 |
- Display the result of rolling two six-sided dice
9 |
- Use randint or choice to add an element of randomness to
10 | a program of your own design
11 |
12 | Answers
13 | Quicktime Movie
14 | YouTube
15 |
--------------------------------------------------------------------------------
/Harder/pascal_triangle.py:
--------------------------------------------------------------------------------
1 | 'Pascal’s Triangle Maker: https://youtu.be/vbr-XaMVTsc'
2 |
3 | from itertools import pairwise
4 |
5 | def make_triangle(num_rows=10):
6 | def make_next_row(row: list[int]) -> list[int]:
7 | return [1] + [left + right for left, right in pairwise(row)] + [1]
8 |
9 | def format_row(row_numbers: list[int]):
10 | centered_padded_nums: list[str] = [f'{num: ^3}' for num in row_numbers]
11 | return f"{' '.join(centered_padded_nums): ^40}"
12 |
13 | row = [1]
14 | for _ in range(num_rows):
15 | print(format_row(row))
16 | row = make_next_row(row)
17 |
18 | if __name__ == '__main__':
19 | make_triangle()
20 |
--------------------------------------------------------------------------------
/Input-Output/word-counts/word_counts.py:
--------------------------------------------------------------------------------
1 | from string import punctuation
2 | from pathlib import Path
3 |
4 | NUM_RESULTS = 20
5 | word_counts: dict[str, int] = {}
6 | stopwords: set[str] = {line.strip() for line in Path('stopwords.txt').read_text().splitlines()}
7 |
8 | for line in Path('play.txt').read_text().lower().splitlines():
9 | for word in line.split():
10 | if (cleaned := word.strip(punctuation)) not in stopwords:
11 | word_counts[cleaned] = word_counts.get(cleaned, 0) + 1
12 |
13 | sorted_counts: list[tuple[str, int]] = sorted(word_counts.items(), key=lambda t: t[1], reverse=True)
14 |
15 | for word, count in sorted_counts[:NUM_RESULTS]:
16 | print(f'{word}\t{count}')
17 |
--------------------------------------------------------------------------------
/Pygame/Bee Invaders/monster_dropping.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from util import loadImage
3 |
4 | class MonsterDropping(pygame.sprite.Sprite):
5 |
6 | def __init__(self, x, y, pixels_per_movement):
7 | pygame.sprite.Sprite.__init__(self)
8 | self.pixels_per_movement = pixels_per_movement
9 | self.image = loadImage('monster-dropping.png')
10 | self.rect = self.image.get_rect()
11 | self.x = x
12 | self.y = y
13 |
14 | def update(self):
15 | imgRect = self.image.get_rect()
16 | self.y += 5
17 | self.x += self.pixels_per_movement
18 | if self.y < 0:
19 | self.kill()
20 | self.rect = imgRect.move(self.x, self.y)
21 |
--------------------------------------------------------------------------------
/Web/flask/gmap/templates/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Local Schools
7 |
10 |
11 |
12 |
13 |
Choose a School
14 | {% for school in schools %}
15 |
{{school.name}}
16 | {% endfor %}
17 |
18 |
19 |
--------------------------------------------------------------------------------
/Jython/Life2/setup.py:
--------------------------------------------------------------------------------
1 | __author__="daveb"
2 | __date__ ="$Aug 28, 2011 9:35:36 AM$"
3 |
4 | from setuptools import setup,find_packages
5 |
6 | setup (
7 | name = 'Game of Life',
8 | version = '0.1',
9 | packages = find_packages(),
10 |
11 | # Declare your packages' dependencies here, for eg:
12 | install_requires=['foo>=3'],
13 |
14 | # Fill in these to make your Egg ready for upload to
15 | # PyPI
16 | author = 'daveb',
17 | author_email = '',
18 |
19 | summary = 'Just another Python package for the cheese shop',
20 | url = '',
21 | license = '',
22 | long_description= 'Long description of the package',
23 |
24 | # could also include long_description, download_url, classifiers, etc.
25 |
26 |
27 | )
--------------------------------------------------------------------------------
/Course-2004/Lesson 6/adventure4/gameserver.py:
--------------------------------------------------------------------------------
1 | import socket
2 | from gamexml import GameXml
3 |
4 | places = {}
5 | gameXml = GameXml("game.xml", places)
6 |
7 | servSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
8 | servSock.bind(('', int(gameXml.serverPort)))
9 | servSock.listen(1)
10 |
11 | while 1:
12 | print('Game server waiting for connection')
13 |
14 | (clientSock, clientAddr) = servSock.accept()
15 | print('How exciting! A connection from', clientAddr)
16 |
17 | while 1:
18 | data = clientSock.recv(100)
19 | if not data:
20 | break
21 | print(clientAddr, data)
22 |
23 | print('Bye bye,', clientAddr)
24 | clientSock.close()
25 |
26 | servSock.close()
27 |
--------------------------------------------------------------------------------
/simple/cypher.py:
--------------------------------------------------------------------------------
1 | 'A somewhat inefficient (because of string.index) cypher'
2 |
3 | plaintext = 'meet me at the usual place'
4 | fromLetters = 'abcdefghijklmnopqrstuv0123456789 '
5 | toLetters = '6n4pde3fs 2c1ivjr05lq8utbgam7hk9o'
6 |
7 | for plaintext_char in plaintext:
8 | from_letters_index: int = fromLetters.index(plaintext_char)
9 | encrypted_letter: str = toLetters[from_letters_index]
10 | print(f'{plaintext_char} -> {encrypted_letter}')
11 |
12 | print()
13 |
14 | cyphertext = '1ddlo1do6lolfdoq5q6cojc64d'
15 | for cyphertext_char in cyphertext:
16 | to_letters_index: int = toLetters.index(cyphertext_char)
17 | decrypted_letter: str = fromLetters[to_letters_index]
18 | print(decrypted_letter, end='')
19 |
--------------------------------------------------------------------------------
/Course-2004/Misc/game1.py:
--------------------------------------------------------------------------------
1 | import os, sys, pygame
2 | from pygame.locals import *
3 |
4 | def main():
5 | pygame.init()
6 | screen = pygame.display.set_mode((500,200))
7 | pygame.display.set_caption('Hello World')
8 | bg = pygame.Surface(screen.get_size())
9 | bg = bg.convert()
10 | bg.fill((255, 255, 200))
11 | clock = pygame.time.Clock()
12 | keepGoing = True
13 | while keepGoing:
14 | clock.tick(60)
15 | for event in pygame.event.get():
16 | if event.type == QUIT or \
17 | event.type == KEYDOWN and event.key == K_ESCAPE:
18 | keepGoing = false
19 | screen.blit(bg, (0, 0))
20 | pygame.display.flip()
21 |
22 | pygame.quit()
23 |
24 | main()
25 |
--------------------------------------------------------------------------------
/Web/flask/morse/morseclient.py:
--------------------------------------------------------------------------------
1 | import requests
2 | from time import sleep
3 | from codes import PASSWORD, morse_codes, words_by_symbol
4 |
5 | URL_BASE = 'http://localhost:5000'
6 | INTER_LETTER_DELAY = 0.2
7 |
8 |
9 | def request_secret():
10 | response = requests.get(URL_BASE + '/secret')
11 | print(response.text)
12 |
13 |
14 | def send_unlock_request(message):
15 | for letter in message:
16 | symbols_for_letter = morse_codes[letter]
17 | for symbol in symbols_for_letter:
18 | response = requests.get(URL_BASE + '/code/' + words_by_symbol[symbol])
19 | print(response.text)
20 | sleep(INTER_LETTER_DELAY)
21 |
22 |
23 | request_secret()
24 | send_unlock_request(PASSWORD)
25 | request_secret()
26 |
--------------------------------------------------------------------------------
/Web/name-picker/templates/layout.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | {% block head %}
5 |
6 |
7 |
8 | Name Picker
9 |
10 |
11 |
12 | {% endblock %}
13 |
14 |
15 | {% block content %}{% endblock %}
16 |
17 |
--------------------------------------------------------------------------------
/simple/turkeycalc.py:
--------------------------------------------------------------------------------
1 | LBS_PER_KG = 2.205
2 | COOK_MINUTES_PER_KG = 31
3 |
4 | si = input('Do you use the International System of Units (Metric System)? (y/n) ') == 'y'
5 | if si:
6 | weight = int(input('How many kilograms is your turkey? '))
7 | else:
8 | print("Oh, I'm sorry. You must be in one of those three backward countries that haven't adopted it.")
9 | weight = int(input('How many backwards-country-pounds is your turkey? ')) / LBS_PER_KG
10 |
11 | stuffed = input('Is your turkey stuffed? (y/n) ') == 'y'
12 |
13 | minutes = weight * COOK_MINUTES_PER_KG
14 | if stuffed:
15 | minutes += 20
16 |
17 | print('Please cook your turkey for', int(minutes), 'minutes.')
18 |
19 | if not si:
20 | print('Enjoy life in your backwards country.')
21 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 6/adventure3/game.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
15 |
16 |
17 |
18 |
19 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/Plotting/diceplot.py:
--------------------------------------------------------------------------------
1 | from random import randint
2 | import matplotlib.pyplot as plt
3 | import numpy as np
4 |
5 | DICE = 2
6 | SIDES = 6
7 | THROWS = 1000
8 |
9 | highest_outcome = SIDES * DICE
10 | outcome_counts = np.zeros(highest_outcome)
11 | ys = np.arange(1, highest_outcome + 1)
12 |
13 | for t in range(THROWS):
14 | throw_sum = sum((randint(1, SIDES) for d in range(DICE)))
15 | outcome_counts[throw_sum - 1] += 1
16 |
17 | plt.barh(ys, outcome_counts, align='center', alpha=0.4)
18 | plt.xlabel('Number of each outcome')
19 | plt.ylabel('Outcome (Sum of Die Values)')
20 | die_or_dice = "Die" if DICE == 1 else "Dice"
21 | plt.title(f'{die_or_dice} Throw Simulation—{DICE} {SIDES}-Sided {die_or_dice}')
22 | plt.ylim((DICE - 1, highest_outcome + 1))
23 | plt.show()
24 |
--------------------------------------------------------------------------------
/Harder/MrTGuessTheFood.py:
--------------------------------------------------------------------------------
1 | from random import choice
2 |
3 | items = ['soup', 'corn', 'milk', 'bread', 'eggs', 'cereal']
4 | item = choice(items)
5 | positiveSayings = ['Stay in school!', "Don't do drugs!"]
6 |
7 | guess = None
8 | guessesLeft = 3
9 | print(f'Mr. T says guess the food item in {guessesLeft} guesses.')
10 | print('Items:', ', '.join(items))
11 |
12 | while guess != item and guessesLeft:
13 | guess = input('Your guess? ')
14 | guessesLeft -= 1
15 | if guess != item and guessesLeft:
16 | singularOrPlural = 'guess' + ('' if guessesLeft == 1 else 'es')
17 | print(f'Wrong. {guessesLeft} {singularOrPlural} left.')
18 |
19 | if guess == item:
20 | print("That's right.", choice(positiveSayings))
21 | else:
22 | print("I pity the fool!")
23 |
--------------------------------------------------------------------------------
/Pygame/SimplePygame/SimplePygame.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from pygame.locals import *
3 |
4 | pygame.init()
5 | screen = pygame.display.set_mode((600, 600), 0)
6 | pygame.display.set_caption('Simple Pygame Game')
7 | bee = pygame.image.load('bee1.png').convert_alpha()
8 | beeX = 0
9 | beeY = 0
10 | clock = pygame.time.Clock()
11 | running = True
12 |
13 | while running:
14 | for event in pygame.event.get():
15 | if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
16 | running = False
17 |
18 | keys = pygame.key.get_pressed()
19 | if keys[K_RIGHT]:
20 | beeX += 5
21 |
22 | screen.fill((0, 120, 0))
23 | screen.blit(bee, (beeX, beeY))
24 | pygame.display.flip()
25 | clock.tick(60)
26 |
27 | pygame.quit()
28 |
--------------------------------------------------------------------------------
/simple/questions3.py:
--------------------------------------------------------------------------------
1 | from random import shuffle
2 | print('Welcome to the wonderful quiz on music!')
3 |
4 | with open("questions.txt") as f:
5 | lines = f.readlines()
6 |
7 | shuffle(lines)
8 | numRight = 0
9 | wrong = []
10 |
11 | numQuestions = int(input("How many questions? "))
12 |
13 | for line in lines[:numQuestions]:
14 | question, rightAnswer = line.strip().split("\t")
15 | answer = input(question + ' ')
16 | if answer.lower() == rightAnswer:
17 | print('Right!')
18 | numRight += 1
19 | else:
20 | print('No, the answer is %s.' % rightAnswer)
21 | wrong.append(question)
22 |
23 | print('You got %d right' % (numRight))
24 | if (wrong):
25 | print('You got these wrong: ')
26 | for q in wrong:
27 | print(q)
--------------------------------------------------------------------------------
/Web/name-picker/name_picker.py:
--------------------------------------------------------------------------------
1 | from flask import Flask, render_template, redirect
2 | from random import randint
3 |
4 | HOW_MANY_OF_EACH_NAME = 4
5 | all_names = ('Graham Meera Rohan Alex'.split(' ')) * HOW_MANY_OF_EACH_NAME
6 | remaining_names = list(all_names)
7 |
8 | app = Flask(__name__)
9 |
10 |
11 | @app.route("/")
12 | def index():
13 | if remaining_names:
14 | name = remaining_names.pop(randint(0, len(remaining_names) - 1))
15 | return render_template("names.html", name=name, remaining=len(remaining_names))
16 | else:
17 | return redirect("/reset")
18 |
19 |
20 | @app.route("/reset")
21 | def reset():
22 | global remaining_names
23 | remaining_names = list(all_names)
24 | return redirect("/")
25 |
26 | app.run(debug=True, port=8181)
27 |
--------------------------------------------------------------------------------
/Course-2004/Misc/ball/ball.py:
--------------------------------------------------------------------------------
1 | import sys, pygame
2 | pygame.init()
3 | size = width, height = 320, 240
4 | speed = [2, 2]
5 | white = 255, 255, 255
6 | screen = pygame.display.set_mode(size)
7 | ball = pygame.image.load("ball.bmp")
8 | ballrect = ball.get_rect()
9 | clock = pygame.time.Clock()
10 |
11 | while True:
12 | clock.tick(60)
13 | for event in pygame.event.get():
14 | if event.type == pygame.QUIT:
15 | sys.exit()
16 |
17 | ballrect = ballrect.move(speed)
18 | if ballrect.left < 0 or ballrect.right > width:
19 | speed[0] = -speed[0]
20 | if ballrect.top < 0 or ballrect.bottom > height:
21 | speed[1] = -speed[1]
22 |
23 | screen.fill(white)
24 | screen.blit(ball, ballrect)
25 | pygame.display.flip()
26 |
27 |
28 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 6/adventure4/game.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
15 |
16 |
17 |
18 |
19 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/Pygame/Sprite1/bee.py:
--------------------------------------------------------------------------------
1 | import pygame, os
2 | from pygame.locals import *
3 |
4 | class Bee(pygame.sprite.Sprite):
5 |
6 | @staticmethod
7 | def loadImage():
8 | surface = pygame.image.load('bee1.png')
9 | Bee.image = surface.convert_alpha()
10 |
11 | def __init__(self, screenRect):
12 | pygame.sprite.Sprite.__init__(self)
13 | self.screenRect = screenRect
14 | self.image = Bee.image
15 | imgRect = self.image.get_rect()
16 | self.rect = imgRect.move(screenRect.centerx - imgRect.centerx,
17 | screenRect.centery - imgRect.centery)
18 |
19 | def update(self):
20 | keystate = pygame.key.get_pressed()
21 | if keystate[K_RIGHT]:
22 | self.rect = self.rect.move((8, 0)).clamp(self.screenRect)
23 |
--------------------------------------------------------------------------------
/images/graphpaper.py:
--------------------------------------------------------------------------------
1 | 'Generates graph paper with multiple coordinate axes'
2 |
3 | from PIL import Image
4 | import numpy as np
5 |
6 | dims = (5000, 3000, 3)
7 | cols_center = dims[1] // 2
8 | grid_spacing = 20
9 | x_axis_spacing = 1000
10 |
11 | pixels = np.full(dims, 255, dtype=np.uint8)
12 |
13 | lc = 200
14 | line_color = (lc, lc, lc)
15 | axis_color = (0, 0, 0)
16 |
17 | for row in range(0, dims[0], grid_spacing):
18 | pixels[row, :] = line_color
19 | for col in range(0, dims[1], grid_spacing):
20 | pixels[:, col] = line_color
21 | pixels[:, cols_center - 1 : cols_center + 1] = axis_color
22 | for x_axis_row in range(x_axis_spacing // 2, dims[0], x_axis_spacing):
23 | pixels[x_axis_row - 1 : x_axis_row + 1] = axis_color
24 |
25 | img = Image.fromarray(pixels)
26 | img.save('graphpaper.png')
27 |
--------------------------------------------------------------------------------
/simple/advent_library.py:
--------------------------------------------------------------------------------
1 | from random import choice
2 |
3 | print('Welcome to Library Adventure')
4 |
5 | transitions = {
6 | 'Main Room': ('Tech Lab', 'Teen Center'),
7 | 'Tech Lab': ('Main Room',),
8 | 'Teen Center': ('Main Room',),
9 | }
10 | places = tuple(transitions.keys())
11 | place = choice(places)
12 | alive = True
13 |
14 | while alive:
15 | print('You are in the', place)
16 | destinations = transitions[place]
17 | print('From here you can go to', ', '.join(destinations))
18 | new_place = input('Where would you like to go? ')
19 | if not new_place:
20 | print('You have left the game')
21 | break
22 | else:
23 | if new_place in destinations:
24 | place = new_place
25 | else:
26 | print("You can't go there.")
27 |
--------------------------------------------------------------------------------
/simple/questions.py:
--------------------------------------------------------------------------------
1 | from random import shuffle
2 | print('Welcome to the wonderful quiz on music!')
3 |
4 | qas = [
5 | ('How many beats are there per measure in 2/4 time?', '2'),
6 | ('In what family of instruments is the piano?', 'percussion'),
7 | ('How many strings does a violin have?', '4')
8 | ]
9 | shuffle(qas)
10 | numRight = 0
11 | wrong = []
12 |
13 | numQuestions = int(input("How many questions? "))
14 |
15 | for question, rightAnswer in qas[:numQuestions]:
16 | answer = input(question + ' ')
17 | if answer.lower() == rightAnswer:
18 | print('Right!')
19 | numRight += 1
20 | else:
21 | print('No, the answer is %s.' % rightAnswer)
22 | wrong.append(question)
23 |
24 | print('You got %d right and the following wrong:' % (numRight))
25 | for q in wrong:
26 | print(q)
--------------------------------------------------------------------------------
/Harder/caesar-cipher.py:
--------------------------------------------------------------------------------
1 | 'Simple Caesar Cipher implementation'
2 |
3 |
4 | def shift(plaintext, num_positions: int) -> str:
5 | return ''.join((_shift_character(ch, num_positions) for ch in plaintext))
6 |
7 |
8 | def _shift_character(ch, shift_by) -> str:
9 | return chr((ord(ch) + shift_by) % 256)
10 |
11 |
12 | if __name__ == '__main__':
13 | # Test with a simple message, and with a string made of all 256 8-bit ASCII characters
14 |
15 | simple_plaintext = 'The eagle flies at dawn.'
16 | all_ascii_chars: str = ''.join((chr(n) for n in range(256)))
17 |
18 | for plaintext in [simple_plaintext, all_ascii_chars]:
19 | cyphertext: str = shift(plaintext, 1)
20 | print(cyphertext)
21 | decoded: str = shift(cyphertext, -1)
22 | print(decoded)
23 | assert plaintext == decoded
24 |
--------------------------------------------------------------------------------
/Plotting/heightage.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import matplotlib.pyplot as plt
3 |
4 | def ym(years, months): return years * 12 + months
5 | def fi(feet, inches): return feet * 12 + inches
6 |
7 | data = (
8 | ('Sue', ym(12, 1), fi(5, 2), 85, 'orange'),
9 | ('Bill', ym(12, 9), fi(5, 4), 130, 'yellow'),
10 | ('Jeff', ym(13, 2), fi(5, 3), 110, 'green'),
11 | ('Jenny', ym(14, 5), fi(5, 5), 120, 'blue'),
12 | ('Peter', ym(13, 2), fi(5, 2), 95, 'indigo')
13 | )
14 |
15 | for name, age, height, weight, color in data:
16 | plt.scatter(age / 12.0, height, s=np.pi * (weight / 15) ** 2, c=color, label=name, alpha=0.5)
17 |
18 | plt.title('Heights and Weights by Age')
19 | plt.legend(loc='upper left')
20 | plt.xlabel('Age')
21 | plt.ylabel('Height')
22 | plt.grid()
23 | plt.show()
24 |
--------------------------------------------------------------------------------
/Pygame/Planet/stars.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from random import gauss, randint
3 |
4 | pg = pygame
5 | pd = pg.display
6 |
7 | def draw_field(star_field):
8 | sr = star_field.get_rect()
9 | star_field.fill((0, 0, 0))
10 |
11 | for n in range(int(gauss(500, 100))):
12 | gray = randint(1, 255)
13 | bluer = redder = greener = 0
14 |
15 | ri = randint(1, 10)
16 | if ri == 1:
17 | bluer = randint(0, 255 - gray)
18 | elif ri == 2:
19 | redder = randint(0, 255 - gray)
20 | elif ri == 3: # Make yellower (red + green)
21 | redder = greener = randint(0, 255 - gray)
22 |
23 | pg.draw.circle(star_field, (gray + redder, gray + greener, gray + bluer),
24 | (randint(0, sr.width), randint(0, sr.height)), max(0, int(gauss(1, 1))))
25 |
--------------------------------------------------------------------------------
/Plotting/plottedtemps.py:
--------------------------------------------------------------------------------
1 | import matplotlib.pyplot as plt
2 | import numpy as np
3 | import requests
4 |
5 | def kelvin_to_celcius(kelvin):
6 | return kelvin - 273.15
7 |
8 | def temp_for_location(location):
9 | resp = requests.get('http://api.openweathermap.org/data/2.5/weather?q=%s&mode=json' % location)
10 | json = resp.json()
11 | main = json['main']
12 | temp = main['temp']
13 | c_temp = kelvin_to_celcius(temp)
14 | return c_temp
15 |
16 | cities = ('Walnut Creek', 'Lafayette', 'San Francisco')
17 | zips = ('94597', '94549', '94108')
18 | temperatures = [temp_for_location(zip) for zip in zips]
19 | y_pos = np.arange(len(cities))
20 |
21 | plt.barh(y_pos, temperatures, align='center', alpha=0.4)
22 | plt.yticks(y_pos, cities)
23 | plt.xlabel('Temperature')
24 | plt.title('Current Temperatures')
25 | plt.show()
26 |
--------------------------------------------------------------------------------
/Pygame/SimplePygame/FadeOutBackground.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from pygame.locals import *
3 |
4 | pygame.init()
5 | screen = pygame.display.set_mode((600, 400), 0)
6 | pygame.display.set_caption('Move Bee Right and Notice the Fadeout')
7 | bee = pygame.image.load('bee1.png').convert_alpha()
8 | beeX = 0
9 | beeY = 0
10 | bgsound = pygame.mixer.Sound('groovy.wav')
11 | bgsound.play(loops=10)
12 |
13 | loop = True
14 | while loop:
15 | for event in pygame.event.get():
16 | if event.type == QUIT \
17 | or (event.type == KEYDOWN and event.key == K_ESCAPE):
18 | loop = False
19 |
20 | if pygame.key.get_pressed()[K_RIGHT]:
21 | bgsound.fadeout(5000)
22 | beeX += 5
23 |
24 | screen.fill((0,180,0))
25 | screen.blit(bee, (beeX, beeY))
26 | pygame.display.flip()
27 |
28 | pygame.quit()
--------------------------------------------------------------------------------
/Pygame/SimplePygame/draw_shapes_solution.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from pygame.locals import *
3 |
4 | def draw_circle(surface, rect):
5 | pygame.draw.circle(surface, (255, 255, 255), rect.center, rect.width / 2)
6 |
7 | def draw_square(surface, rect):
8 | pygame.draw.rect(surface, (255, 255, 255), rect)
9 |
10 | def draw_shapes(surface, draw_fns):
11 | rect = Rect(20, 20, 50, 50)
12 | for fn in draw_fns:
13 | fn(surface, rect)
14 | rect = rect.move(70, 0)
15 |
16 | pygame.init()
17 | screen = pygame.display.set_mode((500, 100), 0)
18 | screen.fill((0, 60, 0))
19 |
20 | draw_shapes(screen, (draw_circle, draw_square))
21 |
22 | pygame.display.flip()
23 |
24 | loop = True
25 | while loop:
26 | event = pygame.event.wait()
27 | if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
28 | loop = False
29 |
30 | pygame.quit()
31 |
--------------------------------------------------------------------------------
/Pygame/SimplePygame/SimplePygameSolutions1-3.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from pygame.locals import *
3 |
4 | pygame.init()
5 | screen = pygame.display.set_mode((600, 400), 0)
6 | pygame.display.set_caption('Simple Pygame Game')
7 | bee = pygame.image.load('bee1.png').convert_alpha()
8 | beeX = 0
9 | beeY = 0
10 |
11 | loop = True
12 | while loop:
13 | for event in pygame.event.get():
14 | if event.type == QUIT \
15 | or (event.type == KEYDOWN and event.key == K_ESCAPE):
16 | loop = False
17 |
18 | keystate = pygame.key.get_pressed()
19 | if keystate[K_RIGHT]:
20 | beeX += 5
21 | if keystate[K_LEFT]:
22 | beeX -= 5
23 | if keystate[K_UP]:
24 | beeY -= 5
25 | if keystate[K_DOWN]:
26 | beeY += 5
27 |
28 | screen.fill((0,180,0))
29 | screen.blit(bee, (beeX, beeY))
30 | pygame.display.flip()
31 |
32 | pygame.quit()
--------------------------------------------------------------------------------
/Pygame/SimplePygame/draw_shapes_problem.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from pygame.locals import *
3 |
4 | def draw_circle(surface, rect):
5 | pygame.draw.circle(surface, (255, 255, 255), rect.center, rect.width / 2)
6 |
7 | def draw_square # you write this function
8 |
9 | def draw_shapes(surface, draw_fns):
10 | rect = Rect(20, 20, 50, 50)
11 | # you write this line: loop over draw_fns
12 | # you write this line: call the function
13 | rect = rect.move(70, 0)
14 |
15 | pygame.init()
16 | screen = pygame.display.set_mode((500, 100), 0)
17 | screen.fill((0, 60, 0))
18 |
19 | # you write a call to draw_shapes, passing it what it needs
20 |
21 | pygame.display.flip()
22 |
23 | loop = True
24 | while loop:
25 | event = pygame.event.wait()
26 | if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
27 | loop = False
28 |
29 | pygame.quit()
30 |
--------------------------------------------------------------------------------
/Web/flask/morse/codes.py:
--------------------------------------------------------------------------------
1 | PASSWORD = 'abracadabra'
2 |
3 | codes = """
4 | 0 -----
5 | 1 .----
6 | 2 ..---
7 | 3 ...--
8 | 4 ....-
9 | 5 .....
10 | 6 -....
11 | 7 --...
12 | 8 ---..
13 | 9 ----.
14 | a .-
15 | b -...
16 | c -.-.
17 | d -..
18 | e .
19 | f ..-.
20 | g --.
21 | h ....
22 | i ..
23 | j .---
24 | k -.-
25 | l .-..
26 | m --
27 | n -.
28 | o ---
29 | p .--.
30 | q --.-
31 | r .-.
32 | s ...
33 | t -
34 | u ..-
35 | v ...-
36 | w .--
37 | x -..-
38 | y -.--
39 | z --..
40 | . .-.-.-
41 | --..--
42 | ? ..--..
43 | ! -.-.--
44 | - -....-
45 | / -..-.
46 | @ .--.-.
47 | ( -.--.
48 | ) -.--.-
49 | """.split("\n")
50 | morse_codes = {el[0]: el[2:] for el in codes if el}
51 |
52 | symbols_and_words = (
53 | ('-', 'dash'),
54 | ('.', 'dot')
55 | )
56 |
57 | words_by_symbol = {symbol: word for symbol, word in symbols_and_words}
58 | symbols_by_word = {word: symbol for symbol, word in symbols_and_words}
59 |
--------------------------------------------------------------------------------
/Pygame/Sprite1/Sprite1.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from pygame.locals import *
3 | from bee import Bee
4 |
5 | pygame.init()
6 | screen = pygame.display.set_mode((600, 600), 0)
7 | bgColor = 0, 120, 0
8 | screen.fill(bgColor)
9 | pygame.display.flip()
10 | pygame.display.set_caption('Sprite Lesson 1')
11 | Bee.loadImage()
12 | bee = Bee(screen.get_rect())
13 | drawingGroup = pygame.sprite.RenderUpdates()
14 | drawingGroup.add(bee)
15 |
16 | def clear_callback(surf, rect):
17 | surf.fill(bgColor, rect)
18 |
19 | loop = True
20 | while loop:
21 | for event in pygame.event.get():
22 | if event.type == QUIT \
23 | or (event.type == KEYDOWN and event.key == K_ESCAPE):
24 | loop = False
25 |
26 | drawingGroup.clear(screen, clear_callback)
27 | drawingGroup.update()
28 | changedRects = drawingGroup.draw(screen)
29 | pygame.display.update(changedRects)
30 |
31 | pygame.quit()
--------------------------------------------------------------------------------
/Web/Old-Style/gameserver.py:
--------------------------------------------------------------------------------
1 | import socket
2 |
3 | serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
4 | serverSocket.bind(('', 5001))
5 | serverSocket.listen(1)
6 |
7 | while True:
8 | print('Game server waiting for connection')
9 |
10 | (clientSocket, clientAddr) = serverSocket.accept()
11 | print('How exciting! A connection from', clientAddr)
12 | clientSocket.send("Hi there\n".encode())
13 |
14 | while True:
15 | line = clientSocket.recv(100).decode().strip()
16 | if not line:
17 | break
18 | print(clientAddr, line)
19 | parts = line.split(' ')
20 | if len(parts) >= 3:
21 | if parts[0] == 'add':
22 | sum = int(parts[1]) + int(parts[2])
23 | clientSocket.send(('%d\n' % sum).encode())
24 |
25 | print('Bye bye,', clientAddr)
26 | clientSocket.close()
27 |
28 | serverSocket.close()
29 |
--------------------------------------------------------------------------------
/Pygame/SimplePygame/showcolors.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from pygame.constants import KEYDOWN, K_UP, K_DOWN, K_ESCAPE, QUIT
3 |
4 | pygame.init()
5 | pygame.key.set_repeat(100, 50)
6 | screen = pygame.display.set_mode((200, 100))
7 | clock = pygame.time.Clock()
8 | framesPerSec = 10
9 | run = True
10 |
11 | for name, rgb in pygame.color.THECOLORS.iteritems():
12 | for event in pygame.event.get():
13 | if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
14 | run = False
15 | elif event.type == KEYDOWN:
16 | if event.key == K_DOWN and framesPerSec > 1:
17 | framesPerSec -= 1
18 | elif event.key == K_UP:
19 | framesPerSec += 1
20 |
21 | if not run:
22 | break
23 |
24 | screen.fill(rgb)
25 | pygame.display.set_caption(name)
26 | pygame.display.flip()
27 | clock.tick(framesPerSec)
28 |
29 | pygame.quit()
30 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 2/TKinter/simple-gui.py:
--------------------------------------------------------------------------------
1 | from tkinter import *
2 |
3 | class Application(Frame):
4 | def greet(self):
5 | self.greeting.set("What's up?")
6 |
7 | def createWidgets(self):
8 | self.greeting = StringVar()
9 | self.greetingLabel = Label(self, textvariable = self.greeting)
10 | self.greetingLabel.grid(row = 2, column = 1, columnspan = 2)
11 |
12 | self.quitButton = Button(self, text = 'Quit', command = self.quit)
13 | self.quitButton.grid(row = 3, column = 1, padx = 5, pady = 5)
14 |
15 | self.greetMeButton = Button(self, text = "Greet Me", command = self.greet)
16 | self.greetMeButton.grid(row = 3, column = 2, padx = 5)
17 |
18 | def __init__(self, master=None):
19 | Frame.__init__(self, master)
20 | self.grid()
21 | self.createWidgets()
22 |
23 | app = Application()
24 | app.master.title("Greeting Program")
25 | app.mainloop()
26 |
--------------------------------------------------------------------------------
/Web/Old-Style/webserver2.py:
--------------------------------------------------------------------------------
1 | from random import choice
2 | from http.server import SimpleHTTPRequestHandler
3 | from socketserver import TCPServer
4 |
5 | class RequestHandler(SimpleHTTPRequestHandler):
6 |
7 | def write(self, s):
8 | self.wfile.write(bytes(s, "utf-8"))
9 |
10 | def do_GET(self):
11 | if self.path == "/":
12 | self.send_response(200)
13 | self.send_header('Content-Type', 'text/plain')
14 | self.end_headers()
15 | user_agent = self.headers.get('User-Agent')
16 | messages = ('Have a nice day', 'So long', 'Come again soon')
17 | self.write("""
18 | Hello person from %s.
19 | Your user agent is %s.
20 | %s.
21 | """ % (self.client_address[0], user_agent or "unknown", choice(messages)))
22 | return
23 |
24 | SimpleHTTPRequestHandler.do_GET(self)
25 |
26 | httpd = TCPServer(("", 8080), RequestHandler)
27 | httpd.serve_forever()
--------------------------------------------------------------------------------
/Pygame/One Bee/bee.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from util import loadImages
3 |
4 | class Bee(pygame.sprite.Sprite):
5 | images = []
6 |
7 | @staticmethod
8 | def loadImages():
9 | Bee.images = loadImages('bee1.png', 'bee2.png', 'bee3.png')
10 |
11 | def __init__(self, screenRect):
12 | pygame.sprite.Sprite.__init__(self)
13 | self.imagesRotated = Bee.images
14 | self.image = self.images[0]
15 | imgRect = self.image.get_rect()
16 | self.rect = imgRect.move(screenRect.centerx - imgRect.centerx,
17 | screenRect.centery - imgRect.centery)
18 | self.animIdx = 0
19 |
20 | def update(self):
21 | self.animIdx = (self.animIdx + 1) % len(self.images)
22 | self.image = self.imagesRotated[self.animIdx]
23 |
24 | def setAngle(self, angle):
25 | self.imagesRotated = []
26 | for image in Bee.images:
27 | self.imagesRotated.append(pygame.transform.rotate(image, angle))
--------------------------------------------------------------------------------
/Pygame/Two Bees/bee.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from util import loadImages
3 |
4 | class Bee(pygame.sprite.Sprite):
5 | images = []
6 |
7 | @staticmethod
8 | def loadImages():
9 | Bee.images = loadImages('bee1.png', 'bee2.png', 'bee3.png')
10 |
11 | def __init__(self, screenRect):
12 | pygame.sprite.Sprite.__init__(self)
13 | self.imagesRotated = Bee.images
14 | self.image = self.images[0]
15 | imgRect = self.image.get_rect()
16 | self.rect = imgRect.move(screenRect.centerx - imgRect.centerx,
17 | screenRect.centery - imgRect.centery)
18 | self.animIdx = 0
19 |
20 | def update(self):
21 | self.animIdx = (self.animIdx + 1) % len(self.images)
22 | self.image = self.imagesRotated[self.animIdx]
23 |
24 | def setAngle(self, angle):
25 | self.imagesRotated = []
26 | for image in Bee.images:
27 | self.imagesRotated.append(pygame.transform.rotate(image, angle))
--------------------------------------------------------------------------------
/Course-2004/Lesson 3/LessonPlan.txt:
--------------------------------------------------------------------------------
1 | Computer Programming with Dave Briccetti
2 | Wed, Mar 3, 2004, Introduction to Python, Concise Notes
3 |
4 | Topics:
5 | 1) Lists
6 |
7 | LISTS
8 |
9 | Creating a list:
10 | l = list() or l = [] or l = [1,2,3] or l = ['rice', 'butter']
11 |
12 | Adding to a list:
13 | l.append('soup')
14 |
15 | Seeing if an element is in a list:
16 | if 'rice' in l:
17 |
18 | Accessing the elements of a list:
19 | for item in l:
20 |
21 | Problem 1:
22 | Write a program with a list, which prompts for words until an
23 | empty word is entered. For each word:
24 |
25 | If it is already in the list, display a message to that effect
26 | Otherwise add it to the list
27 |
28 | Finally, display the list.
29 |
30 | Problem 2:
31 | Write a program to prompt for a series of numbers and store them
32 | in a list. For each element in the list, prompt the user for a
33 | number to add to the first. Store the sums in a second list. At
34 | the end display the second list.
35 |
36 |
--------------------------------------------------------------------------------
/Pygame/Bees/bee.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from util import loadImages
3 |
4 | class Bee(pygame.sprite.Sprite):
5 | images = []
6 | imagesRotated = []
7 |
8 | @staticmethod
9 | def loadImages():
10 | Bee.images = loadImages('bee1.png', 'bee2.png', 'bee3.png')
11 | Bee.imagesRotated = Bee.images
12 |
13 | def __init__(self, screenRect):
14 | pygame.sprite.Sprite.__init__(self)
15 | self.image = self.images[0]
16 | imgRect = self.image.get_rect()
17 | self.rect = imgRect.move(screenRect.centerx - imgRect.centerx,
18 | screenRect.centery - imgRect.centery)
19 | self.animIdx = 0
20 |
21 | def update(self):
22 | self.animIdx = (self.animIdx + 1) % len(self.images)
23 | self.image = self.imagesRotated[self.animIdx]
24 |
25 | def setAngle(self, angle):
26 | Bee.imagesRotated = []
27 | for image in Bee.images:
28 | Bee.imagesRotated.append(pygame.transform.rotate(image, angle))
--------------------------------------------------------------------------------
/Harder/magic-squares.py:
--------------------------------------------------------------------------------
1 | 'Finds all 3 by 3 magic squares by brute force'
2 |
3 | from itertools import permutations
4 | from typing import Iterable, cast
5 |
6 | Permutation = tuple[int, int, int, int, int, int, int, int, int]
7 |
8 | lines = [
9 | (0, 1, 2), (3, 4, 5), (6, 7, 8), # Rows
10 | (0, 3, 6), (1, 4, 7), (2, 5, 8), # Columns
11 | (0, 4, 8), (2, 4, 6) # Diagonals
12 | ]
13 |
14 |
15 | def is_magic(permutation: Permutation) -> bool:
16 |
17 | def line_sum(line_index: int) -> int:
18 | return sum(permutation[cell_index] for cell_index in lines[line_index])
19 |
20 | sum0 = line_sum(0)
21 | all_but_first = range(1, len(lines))
22 | return all(line_sum(line_index) == sum0 for line_index in all_but_first)
23 |
24 |
25 | magic_squares: Iterable[Permutation] = (
26 | cast(Permutation, p) for p in permutations(range(1, 10)) if is_magic(cast(Permutation, p)))
27 |
28 | for ms in magic_squares:
29 | print()
30 | for i in range(0, 9, 3):
31 | print(ms[i], ms[i+1], ms[i+2])
32 |
--------------------------------------------------------------------------------
/Internet/locdraw/client.py:
--------------------------------------------------------------------------------
1 | from threading import Thread, current_thread, local
2 | from random import randint, random
3 | from time import sleep
4 | from socket import socket, AF_INET, SOCK_STREAM
5 | from port import PORT
6 |
7 |
8 | def rc():
9 | 'Return random numbers for coordinates'
10 | return randint(-300, 300)
11 |
12 |
13 | colors = ('red', 'blue', 'yellow', 'brown', 'green', 'gray', 'purple')
14 |
15 |
16 | def draw(color):
17 | tl = local()
18 | tl.color = color
19 | tl.socket = socket(AF_INET, SOCK_STREAM)
20 | tl.socket.connect(('127.0.0.1', PORT))
21 |
22 | name = 'client%f' % random()
23 | try:
24 | for i in range(100):
25 | print('Socket file %i, %s sending' % (tl.socket.fileno(), current_thread().name))
26 | tl.socket.send(('%s\t%i\t%i\t%s' % (name, rc(), rc(), tl.color)).encode())
27 | sleep(0.5 + random())
28 | except KeyboardInterrupt:
29 | pass
30 |
31 | tl.socket.close()
32 |
33 | for color in colors:
34 | Thread(target=draw, args=(color,)).start()
35 |
--------------------------------------------------------------------------------
/Web/flask/gmap/templates/map.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Local Schools
7 |
10 |
12 |
20 |
21 |
22 |
23 |
{{school.name}} School
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/Turtle/centered_triangle.py:
--------------------------------------------------------------------------------
1 | from math import sqrt
2 | from turtle import *
3 |
4 | def center_equilateral_triangle(x: float, y: float, side_length=300) -> None:
5 | height = find_equilateral_triangle_height(side_length)
6 | x_offset = -side_length / 2
7 | y_offset = -height / 2
8 | print(f'{side_length=}, {height=}, {x_offset=}, {y_offset=}')
9 |
10 | penup()
11 | goto(x + x_offset, y + y_offset)
12 | pendown()
13 |
14 | for _ in range(3):
15 | fd(side_length)
16 | lt(360 / 3)
17 |
18 | def find_equilateral_triangle_height(side_length: float) -> float:
19 | base = side_length / 2
20 | base_squared = base * base
21 | hypotenuse = side_length
22 | hyp_squared = hypotenuse * hypotenuse
23 | # hyp² = base² + height² Pythagoras!
24 | # hyp² - base² = height² Algebra
25 | # height² = hyp² - base²
26 | height_squared = hyp_squared - base_squared
27 | height = sqrt(height_squared)
28 | return height
29 |
30 |
31 | center_equilateral_triangle(0, 0, side_length=200)
32 |
33 | input('Press enter/return to exit')
34 |
--------------------------------------------------------------------------------
/simple/mathquiz.py:
--------------------------------------------------------------------------------
1 | from random import randint
2 | from time import time
3 |
4 | print('Enjoy a math quiz, and respond with nothing to stop.')
5 | num_right = 0
6 | num_wrong = 0
7 | total_right_answer_seconds = 0.0
8 |
9 | while True:
10 | num1 = randint(2, 9)
11 | num2 = randint(11, 99)
12 | product = num1 * num2
13 | start_time = time()
14 | response = input(f'What is {num1} × {num2}? ')
15 | if not response:
16 | break
17 | elapsed = time() - start_time
18 | try: # `int` may fail
19 | if int(response) == product:
20 | print(f'Right, in {elapsed:.2f} seconds')
21 | num_right += 1
22 | total_right_answer_seconds += elapsed
23 | else:
24 | print(f'Wrong, the answer was {product}')
25 | num_wrong += 1
26 | except ValueError:
27 | print('You entered something other than an integer')
28 |
29 | print(f'You got {num_right} right and {num_wrong} wrong.')
30 | if num_right:
31 | print(f'Average time for right answers: {total_right_answer_seconds / num_right :.2f} seconds.')
32 |
--------------------------------------------------------------------------------
/Pygame/Bee Invaders/bee.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from util import loadImages
3 |
4 | class Bee(pygame.sprite.Sprite):
5 | images = []
6 |
7 | @staticmethod
8 | def loadImages():
9 | Bee.images = loadImages('bee1.png', 'bee2.png', 'bee3.png')
10 |
11 | def __init__(self, x, y):
12 | pygame.sprite.Sprite.__init__(self)
13 | self.imagesRotated = Bee.images
14 | self.image = self.images[0]
15 | imgRect = self.image.get_rect()
16 | self.rect = imgRect.move(x, y)
17 | self.animIdx = 0
18 | self.update_freq = 5
19 | self.update_place = 0
20 |
21 | def update(self):
22 | self.update_place += 1
23 | if self.update_place >= self.update_freq:
24 | self.animIdx = (self.animIdx + 1) % len(self.images)
25 | self.image = self.imagesRotated[self.animIdx]
26 | self.update_place = 0
27 |
28 | def setAngle(self, angle):
29 | self.imagesRotated = []
30 | for image in Bee.images:
31 | self.imagesRotated.append(pygame.transform.rotate(image, angle))
--------------------------------------------------------------------------------
/Course-2004/Lesson 4/LessonPlan.txt:
--------------------------------------------------------------------------------
1 | Computer Programming with Dave Briccetti
2 | Wed, Mar 17, 2004, Introduction to Python, Concise Notes
3 |
4 | Topics:
5 | 1) Dictionaries
6 | 2) Applications of previous topics
7 |
8 | DICTIONARIES
9 |
10 | Creating a dictionary:
11 | d = dict() or d = {} or d = {'dave': 20, 'eric': 25}
12 |
13 | Adding:
14 | d['sam'] = 30
15 |
16 | Displaying all the keys:
17 | d.keys()
18 |
19 | Displaying all the values:
20 | d.values()
21 |
22 | Seeing if a key 'rice' is in a list:
23 | if 'rice' in d:
24 |
25 | Problem 1:
26 | Write a word counting program with a dictionary, which prompts for
27 | words until an empty word is entered. For each word:
28 |
29 | If it is not in the dictionary, add an element with the word as
30 | the key, and 1 as the value.
31 | Else increment the value of the element with the word
32 |
33 | Finally, display the dictionary, display just the keys, and
34 | display just the values.
35 |
36 | APPLICATIONS OF PREVIOUS TOPICS
37 |
38 | Problem 2:
39 | Create one or more programs of your own design, to apply elements
40 | of Pyton that you have learned.
41 |
--------------------------------------------------------------------------------
/Pygame/SimplePygame/gradients.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from pygame.locals import *
3 |
4 | GRADIENT_HEIGHT = 100
5 | MARGIN_HEIGHT = 2
6 |
7 | def red(intensity):
8 | return (intensity, 0, 0)
9 |
10 | def green(intensity):
11 | return (0, intensity, 0)
12 |
13 | def blue(intensity):
14 | return (0, 0, intensity)
15 |
16 | def gradient(surface, y, color_fn):
17 | for i in range(256):
18 | pygame.draw.line(surface, color_fn(i), (i, y), (i, y + GRADIENT_HEIGHT))
19 |
20 | color_fns = red, green, blue
21 | pygame.init()
22 | num_margins = len(color_fns) - 1
23 | screen = pygame.display.set_mode((256, GRADIENT_HEIGHT * len(color_fns) +
24 | num_margins * MARGIN_HEIGHT), 0)
25 | screen.fill((255, 255, 255))
26 | pygame.display.set_caption('Gradients')
27 | y = 0
28 |
29 | for fn in color_fns:
30 | gradient(screen, y, fn)
31 | y += GRADIENT_HEIGHT + MARGIN_HEIGHT
32 |
33 | pygame.display.flip()
34 |
35 | loop = True
36 | while loop:
37 | event = pygame.event.wait()
38 | if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
39 | loop = False
40 |
41 | pygame.quit()
42 |
--------------------------------------------------------------------------------
/Pygame/Bee Invaders/monster.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from util import loadImage
3 | from monster_dropping import MonsterDropping
4 | from random import randint
5 |
6 | class Monster(pygame.sprite.Sprite):
7 |
8 | def __init__(self, screen_rect, drawing_group):
9 | pygame.sprite.Sprite.__init__(self)
10 | self.screen_rect = screen_rect
11 | self.drawing_group = drawing_group
12 | self.image = loadImage('monster.png')
13 | self.rect = self.image.get_rect()
14 | self.x = 10
15 | self.y = randint(0, screen_rect.centery)
16 | self.pixels_per_movement = randint(1, 5)
17 |
18 | def update(self):
19 | imgRect = self.image.get_rect()
20 | self.x += self.pixels_per_movement
21 | self.rect = imgRect.move(self.x, self.y)
22 | if self.x > self.screen_rect.right:
23 | self.kill()
24 | elif randint(1, 100) == 1:
25 | dropping = MonsterDropping(
26 | self.x + imgRect.width / 2 - 15,
27 | self.y + imgRect.height * 3 / 4, self.pixels_per_movement)
28 | self.drawing_group.add(dropping)
29 |
--------------------------------------------------------------------------------
/Harder/Hash-Attack/permuter.py:
--------------------------------------------------------------------------------
1 | import logging
2 |
3 | logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
4 | log = logging.getLogger('permute')
5 |
6 |
7 | def chars_range(start, end):
8 | "Make a string with all characters in the range, e.g., ('a', 'z')"
9 | return ''.join([chr(a) for a in range(ord(start), ord(end) + 1)])
10 |
11 |
12 | class Permuter:
13 | def __init__(self, chars, length):
14 | self.chars = chars
15 | self.length = length
16 | self.generated = 0
17 |
18 | def next(self, starting_sequence=''):
19 | log.debug('next(%s)' % starting_sequence)
20 | for char in self.chars:
21 | result = starting_sequence + char
22 | self._count()
23 | yield result
24 | if len(result) < self.length:
25 | for nested_result in self.next(result):
26 | self._count()
27 | yield nested_result
28 |
29 | def _count(self):
30 | self.generated += 1
31 | if self.generated % 1000000 == 0:
32 | log.info('Generated %.3e', self.generated)
33 |
--------------------------------------------------------------------------------
/Harder/patternquiz.py:
--------------------------------------------------------------------------------
1 | 'Drill pilots on the mental math of airport traffic pattern flying'
2 |
3 | from random import randint, choice
4 |
5 | legs = [
6 | ('crosswind', 270),
7 | ('downwind', 180),
8 | ('45 to downwind', 135),
9 | ('base', 90)
10 | ]
11 |
12 | while True:
13 | # Randomly choose a runway heading
14 | runway_heading = randint(1, 360)
15 |
16 | # Randomly choose a leg
17 | leg_name, angle = choice(legs)
18 |
19 | # Calculate the runway number
20 | runway = runway_heading // 10
21 |
22 | # Ask the pilot for the leg direction
23 | response = input(
24 | f'You are landing on runway {runway}, left traffic. What direction will you fly on the {leg_name} leg? ')
25 | if not response:
26 | break
27 |
28 | leg_heading = int(response)
29 |
30 | # Tell the pilot if they are correct
31 | actual_leg_heading = ((runway * 10) + angle) % 360
32 |
33 | print('Right! Perhaps you will land successfully.' if leg_heading == actual_leg_heading else
34 | f'Your error may lead to catastrophe. The correct answer is {actual_leg_heading}.')
35 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 David C. Briccetti
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Web/flask/gmap/gmap.py:
--------------------------------------------------------------------------------
1 | '''
2 | A Web application that shows Google Maps around schools, using
3 | the Flask framework, and the Google Maps API.
4 | '''
5 |
6 | from flask import Flask, render_template, abort
7 | app = Flask(__name__)
8 |
9 |
10 | class School:
11 | def __init__(self, key, name, lat, lng):
12 | self.key = key
13 | self.name = name
14 | self.lat = lat
15 | self.lng = lng
16 |
17 | schools = (
18 | School('hv', 'Happy Valley Elementary', 37.9045286, -122.1445772),
19 | School('stanley', 'Stanley Middle', 37.8884474, -122.1155922),
20 | School('wci', 'Walnut Creek Intermediate', 37.9093673, -122.0580063)
21 | )
22 | schools_by_key = {school.key: school for school in schools}
23 |
24 |
25 | @app.route("/")
26 | def index():
27 | return render_template('index.html', schools=schools)
28 |
29 |
30 | @app.route("/")
31 | def show_school(school_code):
32 | school = schools_by_key.get(school_code)
33 | if school:
34 | return render_template('map.html', school=school)
35 | else:
36 | abort(404)
37 |
38 | app.run(host='localhost', debug=True)
39 |
--------------------------------------------------------------------------------
/Physical-Computing/tilt_to_wheel_power.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from typing import Tuple
3 |
4 | MAX_POWER = 20
5 |
6 | def tilt_to_wheel_power(tilt: float) -> Tuple[int, int]:
7 |
8 | def power(tilt: float) -> int:
9 | power_reduction = MAX_POWER * tilt
10 | return int(MAX_POWER - power_reduction)
11 |
12 | left_tilt = -min(tilt, 0)
13 | right_tilt = max(tilt, 0)
14 | left_power = power(left_tilt)
15 | right_power = power(right_tilt)
16 | return left_power, right_power
17 |
18 | for n in range(-10, 11, 2):
19 | tilt = n / 10.0
20 | print(tilt, tilt_to_wheel_power(tilt))
21 |
22 | f = tilt_to_wheel_power
23 |
24 | class Test(unittest.TestCase):
25 |
26 | def test_straight(self):
27 | self.assertEqual(f(0), (MAX_POWER, MAX_POWER))
28 |
29 | def test_half_left(self):
30 | self.assertEqual(f(-0.5), (MAX_POWER / 2, MAX_POWER))
31 |
32 | def test_left(self):
33 | self.assertEqual(f(-1), (0, MAX_POWER))
34 |
35 | def test_half_right(self):
36 | self.assertEqual(f(0.5), (MAX_POWER, MAX_POWER / 2))
37 |
38 | def test_right(self):
39 | self.assertEqual(f(1), (MAX_POWER, 0))
40 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 4/homework/homework.txt:
--------------------------------------------------------------------------------
1 | Homework 4
2 |
3 | Due Tues, Apr 6, 5pm (email to daveb@davebsoft.com, all in a single email with no attachments)
4 | Late homework will not be accepted.
5 |
6 | 1. Write a program to do this:
7 |
8 | Prompt for a series of game character names and magical power values. Use a dictionary to store the data. The character name is the key, and the magical power is the value. Display the names of the characters with magic over 80.
9 |
10 | Here's a sample run of my solution:
11 |
12 | Player name? Hemoglobin the Great Oxygenator
13 | Magic power value? 90
14 | Player name? Mitochondrion the Metabolizer
15 | Magic power value? 75
16 | Player name?
17 | These characters have magic power values over 80:
18 | Hemoglobin the Great Oxygenator
19 |
20 | 2. Find the equivalent of Python dictionaries in one or more of these other languages: Perl, C++, Java. Describe it briefly. Hint: this type of data structure is also known as an associative array, hash, or map.
21 |
22 | Useful websites:
23 |
24 | http://java.sun.com/docs/books/tutorial/collections/index.html
25 | http://www.perl.com/pub/a/2000/10/begperl1.html
26 |
27 | 3. Why do you think I had you do the exercise in problem 2?
28 |
--------------------------------------------------------------------------------
/Jython/Life2/GridMutator.py:
--------------------------------------------------------------------------------
1 | class GridMutator(object):
2 | def generateNext(self, grid):
3 | return [[self._isNewCellOn(grid,r,c) for c in range(len(grid))]
4 | for r in range(len(grid[0]))]
5 |
6 | def _isNewCellOn(self, grid, row, col):
7 | neighbors = self._countNeighbors(grid, row, col)
8 | return neighbors == 3 if not grid[row][col] else neighbors in (2,3)
9 |
10 | def _countNeighbors(self, grid, row, col):
11 | (ROWS, COLS) = (len(grid), len(grid[0]))
12 | neighbors = 0
13 | if row > 0: # Look above unless at top
14 | if col > 0 and grid[row-1][col-1]: neighbors += 1
15 | if grid[row-1][col]: neighbors += 1
16 | if col < COLS-1 and grid[row-1][col+1]: neighbors += 1
17 |
18 | # Look at same row
19 | if col > 0 and grid[row][col-1]: neighbors += 1
20 | if col < COLS-1 and grid[row][col+1]: neighbors += 1
21 |
22 | if row < ROWS-1: # Look below unless at bottom
23 | if col > 0 and grid[row+1][col-1]: neighbors += 1
24 | if grid[row+1][col]: neighbors += 1
25 | if col < COLS-1 and grid[row+1][col+1]: neighbors += 1
26 |
27 | return neighbors
28 |
--------------------------------------------------------------------------------
/Multithreading/simplethread-timed.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from threading import Thread
3 | from time import sleep
4 | from timeit import timeit
5 | from random import random
6 |
7 | logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(threadName)-11s %(message)s')
8 | log = logging.getLogger(__name__)
9 | NUM_COUNTERS = 3
10 | COUNT_TO = 5
11 |
12 |
13 | def count_and_sleep():
14 | for n in range(COUNT_TO):
15 | seconds = random() / 2
16 | log.info('%2d. Waiting %.2f seconds.' % (n + 1, seconds))
17 | sleep(seconds)
18 |
19 |
20 | def use_the_main_thread():
21 | for n in range(NUM_COUNTERS):
22 | count_and_sleep()
23 |
24 |
25 | def use_multiple_threads():
26 | threads = [Thread(target=count_and_sleep) for n in range(NUM_COUNTERS)]
27 | for thread in threads:
28 | thread.start()
29 | for thread in threads:
30 | thread.join()
31 |
32 |
33 | log.info('All in the main thread')
34 | seconds = timeit(use_the_main_thread, number=1)
35 | log.info('Completed in %.2f seconds' % seconds)
36 |
37 | log.info('')
38 | log.info('With multiple threads')
39 | seconds = timeit(use_multiple_threads, number=1)
40 | log.info('Completed in %.2f seconds' % seconds)
41 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 2/TKinter/gui.py:
--------------------------------------------------------------------------------
1 | from tkinter import *
2 |
3 | class Application(Frame):
4 | def greet(self):
5 | if self.formal.get():
6 | self.greeting.set('Hello. How are you?')
7 | else:
8 | self.greeting.set("What's up?")
9 |
10 | def createWidgets(self):
11 | self.formal = IntVar()
12 | self.button = Checkbutton(self, text = 'Formal', variable = self.formal)
13 | self.button.grid(row = 1, column = 1, columnspan = 2)
14 |
15 | self.greeting = StringVar()
16 | self.greetingLabel = Label(self, textvariable = self.greeting)
17 | self.greetingLabel.grid(row = 2, column = 1, columnspan = 2)
18 |
19 | self.quitButton = Button(self, text = 'Quit', command = self.quit)
20 | self.quitButton.grid(row = 3, column = 1, padx = 5, pady = 5)
21 |
22 | self.greetMeButton = Button(self, text = "Greet Me", command = self.greet)
23 | self.greetMeButton.grid(row = 3, column = 2, padx = 5)
24 |
25 | def __init__(self, master=None):
26 | Frame.__init__(self, master)
27 | self.grid()
28 | self.createWidgets()
29 |
30 | app = Application()
31 | app.master.title("My Cool Application")
32 | app.mainloop()
33 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 3/Homework/homework.txt:
--------------------------------------------------------------------------------
1 | Homework 3.5
2 |
3 | Due Tues, Mar 16, 5pm (email to daveb@davebsoft.com, all in a single email with no attachments)
4 | Late homework will not be accepted.
5 |
6 | 1. Write a program to prompt for strings and store them in a list. Shuffle the list and display
7 | it in its new order.
8 |
9 | 2. Create two class rosters (lists) of student names, by prompting for all the names.
10 |
11 | Have the program display both rosters, and then display the names of any students who are in
12 | both classes. Use this approach: Loop over the elements of the first list, and see if each is
13 | also in the second list. If it is, display it.
14 |
15 | Here's the output from my solution:
16 |
17 | ----------------------
18 | Math class
19 | Enter names, one per line. Give an empty name when done.
20 | ==> dave
21 | ==> sue
22 | ==> tim
23 | ==>
24 | English class
25 | Enter names, one per line. Give an empty name when done.
26 | ==> sue
27 | ==> steve
28 | ==> pete
29 | ==>
30 | Math class: ['dave', 'sue', 'tim']
31 | English class: ['sue', 'steve', 'pete']
32 | In both classes:
33 | sue
34 | ----------------------
35 |
36 | My solution uses a function to fetch the list of names. Extra credit if yours does.
37 |
38 | 3. Practice your presention(s)
39 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 6/adventure3/place.py:
--------------------------------------------------------------------------------
1 | from textwrap import wrap
2 |
3 | class Place:
4 |
5 | def __init__(self, name, description):
6 | self.name = name
7 | self.description = description
8 | self.objects = {}
9 | self.connections = {}
10 |
11 | def addObject(self, objectName):
12 | self.objects[objectName] = 1
13 |
14 | def deleteObject(self, objectName):
15 | del self.objects[objectName]
16 |
17 | def addConnection(self, connectionName):
18 | self.connections[connectionName] = 1
19 |
20 | def show(self):
21 | print()
22 | descLines = wrap(self.description)
23 | for descLine in descLines:
24 | print(descLine)
25 |
26 | print()
27 | self.showObjects()
28 |
29 | print()
30 | self.showConnections()
31 |
32 | def showObjects(self):
33 | if self.objects:
34 | print('These objects are here:')
35 | for object in self.objects:
36 | print("\t", object)
37 |
38 | def showConnections(self):
39 | if self.connections:
40 | print('From here you can go to: ')
41 | for connection in self.connections:
42 | print("\t", connection)
43 |
44 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 6/adventure3/placexml.py:
--------------------------------------------------------------------------------
1 | from xml.dom.ext.reader.Sax import FromXmlFile
2 | from xml.dom.NodeFilter import NodeFilter
3 | from place import Place
4 |
5 | class PlaceXml:
6 |
7 | def __init__(self, filename, places):
8 |
9 | root = FromXmlFile(filename)
10 |
11 | walker = root.createTreeWalker(root.documentElement,
12 | NodeFilter.SHOW_ELEMENT, None, 0)
13 |
14 | while 1:
15 | nodeName = walker.currentNode.nodeName
16 | attribs = walker.currentNode.attributes
17 |
18 | if nodeName == 'game':
19 | self.startingPlace = attribs['startingPlace'].value
20 |
21 | elif nodeName == 'place':
22 | placeName = attribs['name'].value
23 | desc = attribs['description'].value
24 | currentPlace = Place(placeName, desc)
25 | places[placeName] = currentPlace
26 |
27 | elif nodeName == 'object':
28 | currentPlace.addObject(attribs['name'].value)
29 |
30 | elif nodeName == 'connection':
31 | currentPlace.addConnection(attribs['place'].value)
32 |
33 | next = walker.nextNode()
34 |
35 | if next is None: break
36 |
--------------------------------------------------------------------------------
/Generic-Duel/duel.py:
--------------------------------------------------------------------------------
1 | results = {}
2 | attack_names = []
3 |
4 | with open('outcomes.tsv') as vs:
5 | for line in vs.readlines()[1:]:
6 | parts = line.strip().split('\t')
7 | attack_name = parts[0]
8 | attack_names.append(attack_name)
9 | results[attack_name] = parts[1:]
10 |
11 | class Attack:
12 | def __init__(self, name, number = None):
13 | self.name = name
14 | self.number = number
15 | self.outcomes = {attack_names[n]: results[name][n] for n in range(len(attack_names))}
16 |
17 | def duel(self, other_attack):
18 | r = self.outcomes[other_attack.name]
19 | if r == 'Highest #':
20 | if self.number == other_attack.number:
21 | return 'Tie'
22 | elif self.number > other_attack.number:
23 | return '%s %d' % (self.name, self.number)
24 | else:
25 | return '%s %d' % (other_attack.name, other_attack.number)
26 | return r
27 |
28 | for n1 in attack_names:
29 | for n2 in attack_names:
30 | for numbers in ((1, 1), (1, 2), (2, 1)):
31 | a1 = Attack(n1, numbers[0])
32 | a2 = Attack(n2, numbers[1])
33 | result = a1.duel(a2)
34 | print('%s %d vs. %s %d => %s' % (n1, numbers[0], n2, numbers[1], result))
--------------------------------------------------------------------------------
/Jython/Life/GridMutator.py:
--------------------------------------------------------------------------------
1 | class GridMutator(object):
2 | def generateNext(self, grid):
3 | (ROWS, COLS) = (len(grid), len(grid[0]))
4 | nextGrid = [[False for r in range(ROWS)] for c in range(COLS)]
5 | for row in range(ROWS):
6 | for col in range(COLS):
7 | neighbors = self._countNeighbors(grid, row, col)
8 | nextGrid[row][col] = neighbors == 3 if not grid[row][col] \
9 | else neighbors in (2,3)
10 | return nextGrid
11 |
12 | def _countNeighbors(self, grid, row, col):
13 | (ROWS, COLS) = (len(grid), len(grid[0]))
14 | neighbors = 0
15 | if row > 0: # Look above unless at top
16 | if col > 0 and grid[row-1][col-1]: neighbors += 1
17 | if grid[row-1][col]: neighbors += 1
18 | if col < COLS-1 and grid[row-1][col+1]: neighbors += 1
19 |
20 | # Look at same row
21 | if col > 0 and grid[row][col-1]: neighbors += 1
22 | if col < COLS-1 and grid[row][col+1]: neighbors += 1
23 |
24 | if row < ROWS-1: # Look below unless at bottom
25 | if col > 0 and grid[row+1][col-1]: neighbors += 1
26 | if grid[row+1][col]: neighbors += 1
27 | if col < COLS-1 and grid[row+1][col+1]: neighbors += 1
28 |
29 | return neighbors
30 |
--------------------------------------------------------------------------------
/Web/flask/joke_quote_whoop.py:
--------------------------------------------------------------------------------
1 | from random import choice, randint
2 | from flask import Flask, request
3 | app = Flask(__name__)
4 | quotes = (
5 | 'Computer science is no more about computers than astronomy is about telescopes. - Edsger Dijkstra',
6 | 'People think that computer science is the art of geniuses but the actual reality is the opposite, ' +
7 | 'just many people doing things that build on each other, like a wall of mini stones. - Donald Knuth',
8 | 'Programs must be written for people to read, and only incidentally for machines to execute. - H. Abelson and G. Sussman',
9 | "I don't know how many of you have ever met Dijkstra, but you probably know that arrogance in computer science is measured in nano-Dijkstras. - Alan Kay"
10 | )
11 | jokes = (
12 | 'What does the chemist say when he finds two helium molecules? HeHe.',
13 | # Add some jokes here
14 | )
15 |
16 | @app.route("/")
17 | def index():
18 | return "Hi %s. Try /joke, /quote, or /whoop." % request.remote_addr
19 |
20 | @app.route("/joke")
21 | def joke():
22 | return choice(jokes)
23 |
24 | @app.route("/quote")
25 | def quote():
26 | return choice(quotes)
27 |
28 | @app.route("/whoop")
29 | def whoop():
30 | return "whoop " * randint(1, 20)
31 |
32 | if __name__ == "__main__":
33 | app.run(host='0.0.0.0', debug=True)
34 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 7/LessonPlan.txt:
--------------------------------------------------------------------------------
1 | Computer Programming with Dave Briccetti
2 | Wed, May 5, 2004, Introduction to Python, Concise Notes
3 |
4 | Outline
5 |
6 | 1) XML
7 | 2) More from Lesson 6 if time permits
8 |
9 |
10 | from xml.dom.ext.reader.Sax import FromXmlFile
11 | from xml.dom.NodeFilter import NodeFilter
12 |
13 | root = FromXmlFile('problem1.xml')
14 |
15 | walker = root.createTreeWalker(root.documentElement,
16 | NodeFilter.SHOW_ELEMENT, None, 0)
17 |
18 | while 1:
19 | nodeName = walker.currentNode.nodeName
20 |
21 | if nodeName == 'game':
22 | print "Hey, I found the game tag!"
23 |
24 | next = walker.nextNode()
25 |
26 | if next is None: break
27 |
28 | -----
29 |
30 |
31 |
32 |
33 | -----
34 |
35 | from xml.dom.ext.reader.Sax import FromXmlFile
36 | from xml.dom.NodeFilter import NodeFilter
37 |
38 | root = FromXmlFile('problem2.xml')
39 | walker = root.createTreeWalker(root.documentElement,
40 | NodeFilter.SHOW_ELEMENT, None, 0)
41 |
42 | while 1:
43 | print walker.currentNode
44 | print walker.currentNode.attributes
45 | next = walker.nextNode()
46 | if next is None: break
47 |
48 | -----
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 6/adventure4/place.py:
--------------------------------------------------------------------------------
1 | from textwrap import wrap
2 |
3 | class Place:
4 |
5 | def __init__(self, name, description):
6 | self.name = name
7 | self.description = description
8 | self.objects = {}
9 | self.connections = {}
10 |
11 | def addObject(self, objectName):
12 | self.objects[objectName] = 1
13 |
14 | def deleteObject(self, objectName):
15 | del self.objects[objectName]
16 |
17 | def addConnection(self, connectionName):
18 | self.connections[connectionName] = 1
19 |
20 | def getLongDescription(self):
21 | result = "\n" + self.description + "\n\n" + \
22 | self.getObjectsDescription() + \
23 | "\n" + self.getConnectionsDescription()
24 | return result
25 |
26 | def getObjectsDescription(self):
27 | result = ""
28 | if self.objects:
29 | result += 'These objects are here:\n'
30 | for object in self.objects:
31 | result += "\t" + object + "\n"
32 | return result
33 |
34 | def getConnectionsDescription(self):
35 | result = ""
36 | if self.connections:
37 | result += 'From here you can go to:\n'
38 | for connection in self.connections:
39 | result += "\t" + connection + "\n"
40 | return result
41 |
42 |
--------------------------------------------------------------------------------
/Harder/cardorder.py:
--------------------------------------------------------------------------------
1 | '''
2 | A brute-force solution to the problem posed in
3 | http://marilynburnsmathblog.com/wordpress/when-should-and-shouldnt-we-give-answers/
4 |
5 | Earlier versions (see history in Github) better match the YouTube video.
6 | '''
7 |
8 | from time import time
9 |
10 | decks_tried = 0
11 |
12 |
13 | def correct_order(read_only_deck):
14 | 'Determine whether the cards in the deck are in the correct order'
15 | global decks_tried
16 | decks_tried += 1
17 | deck = list(read_only_deck)
18 |
19 | for expected in range(1, 11):
20 | if deck.pop(0) != expected:
21 | return False
22 |
23 | if len(deck) > 1:
24 | deck.append(deck.pop(0))
25 |
26 | return True
27 |
28 |
29 | def permutations():
30 | 'Return a generator of deck tuples'
31 | r = range(6, 11) # We know where 1–5 are
32 | return ((1, c2, 2, c4, 3, c6, 4, c8, 5, c10)
33 | for c2 in r for c4 in r for c6 in r for c8 in r for c10 in r
34 | if len({c2, c4, c6, c8, c10}) == 5) # All numbers must be different
35 |
36 |
37 | start = time()
38 | correct_deck = next(filter(correct_order, permutations()))
39 | assert correct_deck == (1, 6, 2, 10, 3, 7, 4, 9, 5, 8)
40 | print('Deck {} found in {:,.2f} microseconds. {:,} decks tried.'.format(
41 | correct_deck, (time() - start) * 1000000, decks_tried))
42 |
--------------------------------------------------------------------------------
/Physical-Computing/tilt_microbit_makecode.py:
--------------------------------------------------------------------------------
1 | PAUSE_MS = 10
2 | SPEED_DIVISOR = 20
3 | FRICTION_MULTIPLIER = 0.5
4 | TILT_IGNORE_THRESHOLD = 10 # In milligravity units
5 |
6 | x = 0.0 # world unit coordinates (from -1 to 1)
7 | y = 0.0
8 | speed_x = 0.0
9 | speed_y = 0.0
10 |
11 | def world_to_led(coordinate: float):
12 | 'Convert a coordinate in world units (-1 to 1) to LED units (0 to 4)'
13 | return Math.round(pins.map(coordinate, -1, 1, 0, 4))
14 |
15 | def adjusted_acceleration(dimension: float):
16 | acceleration = input.acceleration(dimension)
17 | enough_tilt = abs(acceleration) > TILT_IGNORE_THRESHOLD
18 | return acceleration / 1000 / SPEED_DIVISOR if enough_tilt else 0.0
19 |
20 | while True:
21 | basic.clear_screen()
22 | x_led = world_to_led(x)
23 | y_led = world_to_led(y)
24 | led.plot(x_led, y_led)
25 | music.play_tone(pins.map(x_led, 0, 4, 440, 880), 10)
26 | music.play_tone(pins.map(y_led, 0, 4, 880*2, 440*2), 10)
27 |
28 | speed_x += adjusted_acceleration(Dimension.X)
29 | x = Math.constrain(x + speed_x, -1, 1)
30 | if abs(x) == 1:
31 | speed_x = 0
32 | speed_x *= FRICTION_MULTIPLIER
33 |
34 | speed_y += adjusted_acceleration(Dimension.Y)
35 | y = Math.constrain(y + speed_y, -1, 1)
36 | if abs(y) == 1:
37 | speed_y = 0
38 | speed_y *= FRICTION_MULTIPLIER
39 |
40 | pause(PAUSE_MS)
41 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 6/adventure4/gamexml.py:
--------------------------------------------------------------------------------
1 | from xml.dom.ext.reader.Sax import FromXmlFile
2 | from xml.dom.NodeFilter import NodeFilter
3 | from place import Place
4 |
5 | class GameXml:
6 |
7 | def __init__(self, filename, places):
8 |
9 | root = FromXmlFile(filename)
10 |
11 | walker = root.createTreeWalker(root.documentElement,
12 | NodeFilter.SHOW_ELEMENT, None, 0)
13 |
14 | while 1:
15 | nodeName = walker.currentNode.nodeName
16 | attribs = walker.currentNode.attributes
17 |
18 | if nodeName == 'game':
19 | self.startingPlace = attribs['startingPlace'].value
20 | self.serverHost = attribs['serverHost'].value
21 | self.serverPort = attribs['serverPort'].value
22 |
23 | elif nodeName == 'place':
24 | placeName = attribs['name'].value
25 | desc = attribs['description'].value
26 | currentPlace = Place(placeName, desc)
27 | places[placeName] = currentPlace
28 |
29 | elif nodeName == 'object':
30 | currentPlace.addObject(attribs['name'].value)
31 |
32 | elif nodeName == 'connection':
33 | currentPlace.addConnection(attribs['place'].value)
34 |
35 | next = walker.nextNode()
36 |
37 | if next is None: break
38 |
--------------------------------------------------------------------------------
/Harder/roshambo.py:
--------------------------------------------------------------------------------
1 | '''
2 | Rock, paper scissors game.
3 |
4 | Illustrates use of Enum, tuples, join, strip, lower, enumerate, randint,
5 | custom functions, while, break, and if/elif/else.
6 | '''
7 |
8 | from random import choice
9 | from enum import Enum
10 |
11 | class Item(Enum):
12 | ROCK = 0
13 | PAPER = 1
14 | SCISSORS = 2
15 |
16 | def __str__(self) -> str:
17 | return self.name.lower()
18 |
19 | def beats(self, item) -> bool:
20 | 'Return whether this item beats the given item'
21 | # Each beats the item that precedes it (wrapping around)
22 | beats_value: int = (self.value - 1) % 3
23 | return item == Item(beats_value)
24 |
25 | item_names = [item.name for item in Item]
26 | formatted_items = ', '.join(name.lower() for name in item_names)
27 |
28 | while True:
29 | my_item = choice(list(Item))
30 | player_item_string = input(formatted_items + '? ').strip()
31 | if not player_item_string:
32 | break
33 | if player_item_string.upper() not in item_names:
34 | print(player_item_string, 'is not one of', formatted_items)
35 | else:
36 | player_item = Item[player_item_string.upper()]
37 | if player_item.beats(my_item):
38 | print('You win against my', my_item)
39 | elif my_item.beats(player_item):
40 | print(f'My {my_item} beats your {player_item}.')
41 | else:
42 | print('We both chose', my_item)
43 |
--------------------------------------------------------------------------------
/Pygame/SimplePygame/Collide.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from pygame.locals import *
3 |
4 | pygame.init()
5 | screen = pygame.display.set_mode((600, 400), 0)
6 | pygame.display.set_caption('Collision Detection Demo')
7 | bee = pygame.image.load('bee1.png')
8 | beeRect = bee.get_rect()
9 | beeRect.topleft = (0, 0)
10 | bird = pygame.image.load('bird.png')
11 | birdRect = bird.get_rect()
12 | birdRect.topleft = (100, 200)
13 |
14 | loop = True
15 | while loop:
16 | for event in pygame.event.get():
17 | if event.type == QUIT \
18 | or (event.type == KEYDOWN and event.key == K_ESCAPE):
19 | loop = False
20 |
21 | keys = pygame.key.get_pressed()
22 | if keys[K_RIGHT]:
23 | beeRect = beeRect.move(5, 0)
24 | if keys[K_LEFT]:
25 | beeRect = beeRect.move(-5, 0)
26 | if keys[K_UP]:
27 | beeRect = beeRect.move(0, -5)
28 | if keys[K_DOWN]:
29 | beeRect = beeRect.move(0, 5)
30 |
31 | if keys[K_d]:
32 | birdRect = birdRect.move(5, 0)
33 | if keys[K_a]:
34 | birdRect = birdRect.move(-5, 0)
35 | if keys[K_w]:
36 | birdRect = birdRect.move(0, -5)
37 | if keys[K_s]:
38 | birdRect = birdRect.move(0, 5)
39 |
40 | if birdRect.colliderect(beeRect):
41 | print("Ouch!")
42 |
43 | screen.fill((0,180,0))
44 | screen.blit(bee, beeRect.topleft)
45 | screen.blit(bird, birdRect.topleft)
46 | pygame.display.flip()
47 |
48 | pygame.quit()
49 |
--------------------------------------------------------------------------------
/Web/Treasure-Hunt/thclient2.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import re
3 |
4 | treasure_found = False
5 | url_base = 'http://192.168.1.7:5000/'
6 | clue_loc = url_base
7 |
8 |
9 | def solve_largest_puzzle(text):
10 | open_paren = text.index('(')
11 | close_paren = text.index(')')
12 | nums_str = text[open_paren + 1:close_paren]
13 | nums = [int(n) for n in nums_str.split(', ')]
14 | return url_base + str(max(nums))
15 |
16 |
17 | def solve_multiply_puzzle():
18 | m1 = int(requests.get(url_base + 'multiplier').text)
19 | m2 = int(requests.get(url_base + 'multiplicand').text)
20 | return url_base + str(m1 * m2)
21 |
22 |
23 | def solve_three_vowels_puzzle(text):
24 | open_paren = text.index('(')
25 | close_paren = text.index(')')
26 | words = text[open_paren + 1:close_paren].split(', ')
27 | r = re.compile('.*[aeiou]{3}.*')
28 | matching = [word for word in words if r.search(word)]
29 | return url_base + matching[0]
30 |
31 |
32 | while not treasure_found:
33 | resp = requests.get(clue_loc)
34 | text = resp.text
35 | print(text)
36 |
37 | if text == 'You have reached the treasure!':
38 | treasure_found = True
39 | else:
40 | if 'where number is the largest' in text:
41 | clue_loc = solve_largest_puzzle(text)
42 | elif '×' in text:
43 | clue_loc = solve_multiply_puzzle()
44 | elif 'three vowels in a row' in text:
45 | clue_loc = solve_three_vowels_puzzle(text)
46 | else:
47 | clue_loc = text
48 |
--------------------------------------------------------------------------------
/Web/Old-Style/webserver.py:
--------------------------------------------------------------------------------
1 | # Run this, then in your web browser, go to http://localhost:8080/quote or http://localhost:8080/joke
2 |
3 | from http.server import HTTPServer, SimpleHTTPRequestHandler
4 | from random import choice
5 |
6 | quotes = (
7 | 'Computer science is no more about computers than astronomy is about telescopes. - Edsger Dijkstra',
8 | 'People think that computer science is the art of geniuses but the actual reality is the opposite, ' +
9 | 'just many people doing things that build on each other, like a wall of mini stones. - Donald Knuth',
10 | 'Programs must be written for people to read, and only incidentally for machines to execute. - H. Abelson and G. Sussman',
11 | "I don't know how many of you have ever met Dijkstra, but you probably know that arrogance in computer science is measured in nano-Dijkstras. - Alan Kay"
12 | )
13 |
14 | jokes = (
15 | 'Why did the chicken cross the road? To get to the other side.',
16 | )
17 |
18 | class Handler(SimpleHTTPRequestHandler):
19 | def do_GET(self):
20 | self.send_response(200)
21 | self.send_header("Content-type", "text/html")
22 | self.end_headers()
23 | category = quotes if self.path == '/quote' else jokes
24 | html = """
25 |
26 |
27 | %s
28 |
29 |
30 | """ % choice(category)
31 | self.wfile.write(html.encode("utf-8"))
32 |
33 | server = HTTPServer(('', 8080), Handler)
34 | server.serve_forever()
35 |
--------------------------------------------------------------------------------
/Pygame/Planet/planet.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from pygame.constants import KEYDOWN, K_ESCAPE, K_UP, K_DOWN, QUIT
3 | from stars import draw_field
4 |
5 | pg = pygame
6 | pd = pg.display
7 | pg.init()
8 | pd.set_caption("Approaching a Class M Planet")
9 | pg.key.set_repeat(1, 20)
10 | screen = pd.set_mode((1280, 700))
11 | sr = screen.get_rect()
12 | planet = pg.image.load('planet.png')
13 | star_field = screen.copy()
14 | draw_field(star_field)
15 |
16 | clock = pygame.time.Clock()
17 |
18 | planet_size = sr.width / 20
19 | planet_size_increment = max(5, sr.width / 500)
20 | image_changed = True
21 | keep_running = True
22 |
23 | while keep_running:
24 | for event in pg.event.get():
25 | if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
26 | keep_running = False
27 | elif event.type == KEYDOWN:
28 | if event.key == K_UP:
29 | planet_size += planet_size_increment
30 | image_changed = True
31 | elif event.key == K_DOWN and planet_size - planet_size_increment >= 1:
32 | planet_size -= planet_size_increment
33 | image_changed = True
34 |
35 | if image_changed:
36 | screen.blit(star_field, (0, 0))
37 | planet_scaled = pg.transform.scale(planet, (planet_size, planet_size))
38 | x = sr.centerx - planet_size / 2
39 | y = sr.centery - planet_size / 2
40 | screen.blit(planet_scaled, (x, y))
41 | pd.flip()
42 | image_changed = False
43 |
44 | clock.tick(100)
45 |
46 | pg.quit()
47 |
--------------------------------------------------------------------------------
/Harder/memorygame.py:
--------------------------------------------------------------------------------
1 | from random import randint, choice, shuffle
2 | from time import sleep
3 | from typing import Sequence, Optional, Iterator
4 |
5 | def clear():
6 | for n in range(100): # “Clear” the console
7 | print()
8 |
9 | def create_sequence(
10 | include: Optional[int] = None,
11 | exclude: Optional[Iterator[int]] = None) -> Sequence[int]:
12 | unique_numbers: set[int] = {include} if include else set()
13 | excluding: set[int] = exclude or set()
14 | while len(unique_numbers) < seq_length:
15 | candidate = randint(1, highest_num)
16 | if candidate not in excluding:
17 | unique_numbers.add(candidate)
18 | unique_numbers_list = list(unique_numbers)
19 | shuffle(unique_numbers_list)
20 | return unique_numbers_list
21 |
22 | seq_length = 3
23 | highest_num = 20
24 |
25 | while True:
26 | first_sequence = create_sequence()
27 | clear()
28 | print(f'Remember these numbers:\n{first_sequence}')
29 | sleep(2)
30 |
31 | number_in_both_sequences = choice(first_sequence)
32 | second_sequence = create_sequence(include=number_in_both_sequences, exclude=first_sequence)
33 |
34 | clear()
35 | response = input(f'Which one of these numbers was in the previous sequence?\n{second_sequence}')
36 | if not response:
37 | break
38 | if response == str(number_in_both_sequences):
39 | print('Correct')
40 | seq_length += 1
41 | else:
42 | print('Wrong')
43 | if seq_length > 1:
44 | seq_length -= 1
45 |
46 | sleep(1)
47 |
48 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 2/homework/Answers.txt:
--------------------------------------------------------------------------------
1 | Homework 3 Answers
2 |
3 | 1. The program has a block of almost identical code which is repeated. It should
4 | be "factored out" and put in a function.
5 |
6 | 2.
7 |
8 | def getNum():
9 | num = float(input('Please enter a number: '))
10 | if num < 0:
11 | num *= 2
12 | else:
13 | num *= 3
14 | return num
15 |
16 | num1 = getNum()
17 | num2 = getNum()
18 |
19 | print 'The result is', num1 + num2
20 |
21 |
22 | 3.
23 |
24 | def getSpecialNum():
25 | while 1:
26 | try:
27 | num = float(input('Enter a number > 10: '))
28 | if num > 10:
29 | break
30 |
31 | print 'That is not > 10'
32 |
33 | except (ValueError):
34 | print 'That is not a number'
35 |
36 | print 'Thank you'
37 |
38 | getSpecialNum()
39 |
40 | 4. You might need to use such functionality from several places in your program.
41 |
42 | 5.
43 |
44 | class InputCollector:
45 | def getSpecialNum(self):
46 | while 1:
47 | try:
48 | num = float(input('Enter a number > 10: '))
49 | if num > 10:
50 | break
51 |
52 | print 'That is not > 10'
53 |
54 | except (ValueError):
55 | print 'That is not a number'
56 |
57 | print 'Thank you'
58 |
59 | inputCollector = InputCollector()
60 | inputCollector.getSpecialNum()
61 |
62 |
63 | 6. A geometry manager arranges user interface components.
64 |
65 |
--------------------------------------------------------------------------------
/Physical-Computing/tilt_microbit_micropython.py:
--------------------------------------------------------------------------------
1 | from microbit import *
2 | import music
3 |
4 | PAUSE_MS = 10
5 | SPEED_DIVISOR = 20
6 | FRICTION_MULTIPLIER = 0.5
7 | TILT_IGNORE_THRESHOLD = 10 # In milligravity units
8 |
9 | x = 0.0 # world unit coordinates (from -1 to 1)
10 | y = 0.0
11 | speed_x = 0.0
12 | speed_y = 0.0
13 |
14 | def world_to_led(coordinate: float) -> int:
15 | 'Convert a coordinate in world units (-1 to 1) to LED units (0 to 4)'
16 | return round(scale(coordinate, from_=(-1, 1), to=(0, 4)))
17 |
18 | def adjusted_acceleration(acceleration: float) -> float:
19 | enough_tilt = abs(acceleration) > TILT_IGNORE_THRESHOLD
20 | return acceleration / 1000 / SPEED_DIVISOR if enough_tilt else 0.0
21 |
22 | def constrain(value: float, low: float, high: float) -> float:
23 | return min(max(value, low), high)
24 |
25 | while True:
26 | display.clear()
27 | x_led = world_to_led(x)
28 | y_led = world_to_led(y)
29 | display.set_pixel(x_led, y_led, 9)
30 | music.pitch(scale(x_led, from_=(0, 4), to=(440, 880)))
31 | sleep(10)
32 | music.pitch(scale(y_led, from_=(0, 4), to=(880*2, 440*2)))
33 | sleep(10)
34 | music.stop()
35 |
36 | speed_x += adjusted_acceleration(accelerometer.get_x())
37 | x = constrain(x + speed_x, -1, 1)
38 | if abs(x) == 1:
39 | speed_x = 0
40 | speed_x *= FRICTION_MULTIPLIER
41 |
42 | speed_y += adjusted_acceleration(accelerometer.get_y())
43 | y = constrain(y + speed_y, -1, 1)
44 | if abs(y) == 1:
45 | speed_y = 0
46 | speed_y *= FRICTION_MULTIPLIER
47 |
48 | sleep(PAUSE_MS)
49 |
--------------------------------------------------------------------------------
/Pygame/One Bee/bees.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from pygame.locals import *
3 | from bee import Bee
4 |
5 | pygame.init()
6 | screen = pygame.display.set_mode((700, 394), 0)
7 | screen_rect = screen.get_rect()
8 | background = screen.copy()
9 | for y in range(screen_rect.height):
10 | color_val = 255 - 255 * y / screen_rect.height
11 | pygame.draw.line(background, (0, color_val, 0), (0, y), (screen_rect.width, y))
12 | Bee.loadImages()
13 |
14 | screen.blit(background, (0, 0))
15 | pygame.display.flip()
16 |
17 | bee = Bee(screen_rect)
18 |
19 | drawing_group = pygame.sprite.RenderUpdates()
20 | drawing_group.add(bee)
21 |
22 | pygame.display.set_caption('One Bee')
23 | pygame.mouse.set_visible(0)
24 |
25 | clock = pygame.time.Clock()
26 | angles = (( 45, 0, -45),
27 | ( 90, 0, -90),
28 | (135, 180, -135))
29 |
30 | # game loop
31 | loop = True
32 | while loop:
33 | # get input
34 | for event in pygame.event.get():
35 | if event.type == QUIT \
36 | or (event.type == KEYDOWN and event.key == K_ESCAPE):
37 | loop = False
38 |
39 | keystate = pygame.key.get_pressed()
40 | xdir = keystate[K_RIGHT] - keystate[K_LEFT] # -1, 0, or 1
41 | ydir = keystate[K_DOWN] - keystate[K_UP]
42 |
43 | bee.setAngle(angles[ydir+1][xdir+1])
44 | bee.rect = bee.rect.move((xdir * 8, ydir * 8)).clamp(screen_rect)
45 |
46 | drawing_group.clear(screen, background)
47 | drawing_group.update()
48 | changed_rects = drawing_group.draw(screen)
49 | pygame.display.update(changed_rects)
50 |
51 | # maintain frame rate
52 | clock.tick(40)
53 |
54 | pygame.quit()
55 |
--------------------------------------------------------------------------------
/Harder/hangman.py:
--------------------------------------------------------------------------------
1 | import turtle as t
2 | from random import choice
3 |
4 |
5 | def draw_background():
6 | t.setup(300, 500)
7 | t.title('Hangman')
8 | t.pu()
9 | t.setpos(-100, -200)
10 | t.seth(0)
11 | t.pd()
12 | t.fd(200)
13 |
14 | def draw_head():
15 | t.pu()
16 | t.setpos(0, 0)
17 | t.pd()
18 | t.circle(10)
19 |
20 | def draw_body():
21 | t.pu()
22 | t.setpos(0, 0)
23 | t.seth(270)
24 | t.pd()
25 | t.fd(100)
26 |
27 | def draw_unfinished():
28 | pass # Not yet implemented
29 |
30 | word = choice('television absolute aircraft budget champion complex fiction introduce'.split())
31 | correct: set[str] = set()
32 | wrong: set[str] = set()
33 | MAX_GUESSES = 7
34 | num_guesses = 0
35 |
36 | draw_functions = [draw_head, draw_body] + [draw_unfinished] * (7 - 2)
37 |
38 | draw_background()
39 |
40 | while num_guesses < MAX_GUESSES:
41 | print(MAX_GUESSES - num_guesses, 'guesses left')
42 | clue = [letter if letter in correct else '-' for letter in word]
43 | print(' '.join(clue))
44 | if wrong:
45 | print('Wrong:', ' '.join(sorted(list(wrong))))
46 |
47 | guess = input('Guess? ')
48 | num_guesses += 1
49 |
50 | if guess == word:
51 | print('Right!')
52 | break
53 | if len(guess) > 1:
54 | print('Wrong')
55 | else:
56 | if guess in correct or guess in wrong:
57 | print('You already guessed that')
58 | else:
59 | if guess in word:
60 | print('Right')
61 | correct.add(guess)
62 | else:
63 | print('Wrong')
64 | wrong.add(guess)
65 | draw_functions[len(wrong) - 1]()
66 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 1/LessonPlan.txt:
--------------------------------------------------------------------------------
1 | Computer Programming with Dave Briccetti
2 | Wed, Feb 4, 2004
3 | Introduction to Python
4 |
5 | Objective: To become familiar with Python
6 |
7 | Notes
8 |
9 | interactive mode
10 |
11 | setting variables and displaying their values (integers, reals, strings
12 | a=1
13 | a
14 | b=2
15 | a+b
16 | print a+b
17 | d=7.5
18 | name='Dave'
19 |
20 | prompting for input
21 | name = input('What is your name? ')
22 | health = int(input('Enter health value: '))
23 | dist = float(input('Enter distance: '))
24 |
25 | creating a program in a .py file
26 |
27 | formatted output
28 | print 'Total cost: $%.2f' % totalCost
29 |
30 | while loop
31 | while (guess != num)
32 |
33 | for loop, range function
34 | for n in range(1,11):
35 | print n
36 |
37 | if statement
38 | if guess == num:
39 | print "That's right!"
40 | else:
41 | print "Wrong"
42 |
43 | math
44 | import math
45 | print math.pi
46 |
47 | Problems:
48 |
49 | 1) Create a variable called health and give it a value of 100. Subtract 10 from it
50 | and store the result in health.
51 |
52 | 2) Prompt for age and store it in an integer variable
53 |
54 | 3) Prompt for a distance and store it in a float variable
55 |
56 | 4) Write a program to ask for an age in years and display the age in days
57 | (assume 365 days per year)
58 |
59 | 5) Write a program that displays how far a bike moves, given the diameter of
60 | a wheel, and the number of revolutions (prompt for the two values, as floats).
61 |
62 | 6) Display the integers from 1 to 10, with their squares:
63 | 1 1
64 | 2 4
65 | 3 9
66 | ...
67 |
68 | 6) Display the integers from -5 to 3
69 |
70 | 7) Ask for an upper limit, and if the number entered is > 1
71 | then display all the integers from 1 to that limit
72 |
--------------------------------------------------------------------------------
/Input-Output/word-counts/stopwords.txt:
--------------------------------------------------------------------------------
1 | i
2 | me
3 | my
4 | myself
5 | we
6 | our
7 | ours
8 | ourselves
9 | you
10 | you're
11 | you've
12 | you'll
13 | you'd
14 | your
15 | yours
16 | yourself
17 | yourselves
18 | he
19 | him
20 | his
21 | himself
22 | she
23 | she's
24 | her
25 | hers
26 | herself
27 | it
28 | it's
29 | its
30 | itself
31 | they
32 | them
33 | their
34 | theirs
35 | themselves
36 | what
37 | which
38 | who
39 | whom
40 | this
41 | that
42 | that'll
43 | these
44 | those
45 | am
46 | is
47 | are
48 | was
49 | were
50 | be
51 | been
52 | being
53 | have
54 | has
55 | had
56 | having
57 | do
58 | does
59 | did
60 | doing
61 | a
62 | an
63 | the
64 | and
65 | but
66 | if
67 | or
68 | because
69 | as
70 | until
71 | while
72 | of
73 | at
74 | by
75 | for
76 | with
77 | about
78 | against
79 | between
80 | into
81 | through
82 | during
83 | before
84 | after
85 | above
86 | below
87 | to
88 | from
89 | up
90 | down
91 | in
92 | out
93 | on
94 | off
95 | over
96 | under
97 | again
98 | further
99 | then
100 | once
101 | here
102 | there
103 | when
104 | where
105 | why
106 | how
107 | all
108 | any
109 | both
110 | each
111 | few
112 | more
113 | most
114 | other
115 | some
116 | such
117 | no
118 | nor
119 | not
120 | only
121 | own
122 | same
123 | so
124 | than
125 | too
126 | very
127 | s
128 | t
129 | can
130 | will
131 | just
132 | don
133 | don't
134 | should
135 | should've
136 | now
137 | aren't
138 | couldn't
139 | didn't
140 | doesn't
141 | hadn't
142 | hasn't
143 | haven't
144 | isn't
145 | mightn't
146 | mustn't
147 | needn't
148 | shan't
149 | shouldn't
150 | wasn't
151 | weren't
152 | won't
153 | wouldn't
154 | shall
155 | thou
156 | come
157 | o
158 | good
159 | let
160 | us
161 | thy
162 | thee
163 |
--------------------------------------------------------------------------------
/Web/flask/morse/README.md:
--------------------------------------------------------------------------------
1 | # Morse Code Secret Server
2 |
3 | This project provides Python client and server programs for “unlocking” a server
4 | via Morse Code and then requesting a secret. It uses the Flask framework
5 | and the requests library.
6 |
7 | ## YouTube Video: Demo and Code Walkthrough
8 |
9 | [This video](https://www.youtube.com/watch?v=MJ2AF7hZUQE&list=PL7DF0D1EA1E0010FC)
10 | demonstrates the programs and walks through the code.
11 |
12 | ## The Server
13 |
14 | For each IP address connecting to it, the server keeps track of a client’s
15 | progress in supplying the password in Morse Code, in the right order,
16 | without timing out. When the password is supplied correctly, access to the
17 | secret is unlocked for a period of time.
18 |
19 | ## The Client
20 |
21 | A human could use the browser to supply the codes one by one, but that would
22 | be tedious, so we have a client program. For each letter in the password,
23 | the client looks up the Morse Code, and for each element of the Morse Code for
24 | the letter, replaces it with “dash” or “dot” and issues an HTTP GET request
25 | to the server in the form: `/codes/`, where `` is `dash` or `dot`.
26 |
27 | Once the client unlocks the secret, it can request the secret with `/secret`.
28 |
29 | ## The codes Module
30 |
31 | The codes model stores the morse code, the password, and dictionaries used to
32 | substitute “dash” for “-” (yes, this is really a hyphen and not a dash),
33 | “dot” for “.”, and vice versa. Web browsers may discard a “.” in a URI path,
34 | so we replace the symbols with words.
35 |
36 | ## Features of Python Used
37 |
38 | The server and client use many features of Python, including:
39 |
40 | - for ... in
41 | - logging
42 | - generator
43 | - dictionary
44 | - dictionary comprehension
45 | - requests
46 | - Flask
47 | - class
48 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 5/1.py:
--------------------------------------------------------------------------------
1 | def showPlace():
2 | print((place[0]))
3 | objects = place[2]
4 | if objects:
5 | print('These objects are here:')
6 | for object in objects:
7 | print("\t", object)
8 | print('From here you can go to: ')
9 | for otherPlace in place[1]:
10 | print("\t", otherPlace)
11 |
12 | def showItems():
13 | if collectedItems:
14 | print('You have collected these items:')
15 | for item in collectedItems:
16 | print("\t", item)
17 |
18 | places = {}
19 | collectedItems = []
20 | places["forest"] = [
21 | "You are in the middle of a dark forest. Strange creatures howl in the distance.",
22 | ("airstrip", "waterfall", "mars"),
23 | ["acorn", "codebook", "bicycle"]
24 | ]
25 | places["airstrip"] = [
26 | "You are at the airstrip. The place is covered with weeds.",
27 | ("forest",),
28 | ["propeller"]
29 | ]
30 | places["waterfall"] = [
31 | "The waterfall makes a deafening sound.",
32 | ("forest",),
33 | ["fish"]
34 | ]
35 | places["mars"] = [
36 | "Mars is spacious.",
37 | ("airstrip",),
38 | ["rock", "robot junk"]
39 | ]
40 |
41 | place = places["forest"]
42 |
43 | while place:
44 | showPlace()
45 | showItems()
46 | cmdLine = input('--> ')
47 | cmdWords = cmdLine.split(' ')
48 | cmd = cmdWords[0]
49 | availPlaces = place[1]
50 | availItems = place[2]
51 |
52 | if cmd == 'go':
53 | newPlace = cmdWords[1]
54 | if newPlace in availPlaces:
55 | place = places[newPlace]
56 | else:
57 | print('You can\'t go there.')
58 | elif cmd == 'get':
59 | requestedItem = cmdWords[1]
60 | if requestedItem in availItems and not (cmdWords[1] in collectedItems):
61 | collectedItems.append(requestedItem)
62 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 2/homework/Homework.txt:
--------------------------------------------------------------------------------
1 | Homework 3
2 |
3 | Due Tues, Mar 2, 5pm (email to daveb@davebsoft.com, all in a single email with no attachments)
4 |
5 | 1. Considering what you've learned recently, say what is wrong with this program:
6 |
7 | num1 = float(input('Please enter a number: '))
8 | if num1 < 0:
9 | num1 *= 2
10 | else:
11 | num1 *= 3
12 |
13 | num2 = float(input('Please enter a number: '))
14 | if num2 < 0:
15 | num2 *= 2
16 | else:
17 | num2 *= 3
18 |
19 | print 'The result is', num1 + num2
20 |
21 | 2. Rewrite the program in problem 1 to correct the most serious flaw.
22 |
23 | 3. Write a function, getSpecialNum, to prompt for, and retrieve from the user, a number greater than 10. Here is what it might look like when you run it:
24 |
25 | Enter a number > 10: x
26 | That is not a number
27 | Enter a number > 10: 10
28 | That is not > 10
29 | Enter a number > 10: 10.1
30 | Thank you
31 |
32 | 4. Why might it be useful to know how to write functions like that?
33 |
34 | 5. Change your program from problem 3 so that the function is part of a class called InputCollector. To test the function, use the following code:
35 |
36 | inputCollector = InputCollector()
37 | inputCollector.getSpecialNum()
38 |
39 | 6. Read pages 3-5 of http://www.nmt.edu/tcc/help/pubs/tkinter.pdf
40 |
41 | What does a geometry manager do?
42 |
43 | 7. Look at this page: http://www.computerhistory.org/exhibits/highlights/alto.page
44 |
45 | Prepare a 30-60 second oral presentation on something related to this page. Learn the material thoroughly, and present from brief notes. The notes should remind you of key points you want to talk about. Come to class with your notes, fully prepared and ready to deliver the presentation in 30-60 seconds.
46 |
47 | Those of you who didn't deliver the last assigned presentation will be doing that one as well.
48 |
--------------------------------------------------------------------------------
/simple/advent.py:
--------------------------------------------------------------------------------
1 | from random import choice, randint
2 | from typing import List
3 |
4 | transitions = { # Each place, and where you can go from it
5 | 'airstrip': ['forest'],
6 | 'forest': ['airstrip', 'cave'],
7 | 'cave': ['forest', 'meadow'],
8 | 'meadow': ['cave'],
9 | }
10 | places: List[str] = list(transitions.keys())
11 | current_place: str = choice(places)
12 | alive = True
13 | inventory = []
14 |
15 | while alive:
16 | print('You are at the', current_place)
17 | if inventory:
18 | print(f"You are carrying: {', '.join(inventory)}")
19 | destinations: List[str] = transitions[current_place]
20 | print('From here you can go to', ', '.join(destinations))
21 | new_place = input('Where would you like to go? ')
22 | if not new_place:
23 | print('You have left the game')
24 | break
25 | else:
26 | if new_place in destinations:
27 | # Things that can happen anywhere
28 | if randint(1, 10) == 1:
29 | print('You were struck by lightning. Game over.')
30 | alive = False
31 | else:
32 | current_place = new_place
33 | # Things that can happen in specific places
34 | if current_place == 'meadow':
35 | if randint(1, 4) == 1:
36 | print('You fell in a hole and you are stuck.')
37 | alive = False
38 | elif randint(1, 3) == 1:
39 | print('You discover an amazing treasure!')
40 | inventory.append('an amazing treasure')
41 | elif current_place == 'cave':
42 | if randint(1, 2) == 1:
43 | print('You have a new pet bat')
44 | inventory.append('a bat')
45 | else:
46 | print("You can't go there.")
47 |
--------------------------------------------------------------------------------
/Pygame/Chessboard/tiledraw.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from pygame.locals import *
3 | from time import sleep
4 |
5 | sqlen = 50
6 |
7 | class Board(object):
8 | def __init__(self):
9 | self.squares = [[None for r in range(8)] for c in range(8)]
10 | for c in range(8):
11 | self.squares[1][c] = Pawn(0)
12 | self.squares[6][c] = Pawn(1)
13 |
14 | def draw(self, screen):
15 | self._drawBackground(screen)
16 |
17 | for r in range(8):
18 | for c in range(8):
19 | square = self.squares[r][c]
20 | if square:
21 | square.draw(screen, r, c)
22 |
23 | pygame.display.flip()
24 |
25 | def _drawBackground(self, screen):
26 | gray = 80, 80, 80
27 | white = 240, 240, 240
28 | for r in range(8):
29 | for c in range(8):
30 | screen.fill(gray if (r + c) % 2 else white,
31 | Rect(r * sqlen, c * sqlen, sqlen, sqlen))
32 |
33 | class Chessman(object):
34 | def __init__(self, color):
35 | self.color = color
36 |
37 | def draw(self, screen, row, col):
38 | self._blitCentered(self.images[self.color], sqlen * col, sqlen * row)
39 |
40 | def _blitCentered(self, surface, x, y):
41 | rect = surface.get_rect()
42 | screen.blit(surface, (x + (sqlen - rect.width) / 2,
43 | y + (sqlen - rect.height) / 2))
44 |
45 | class Pawn(Chessman):
46 | images = [pygame.image.load(n) for n in ("whitepawn.png", "blackpawn.png")]
47 |
48 | pygame.init()
49 | board_len = sqlen * 8
50 | screen = pygame.display.set_mode((board_len, board_len), 0)
51 | pygame.display.set_caption("Chess?")
52 | board = Board()
53 | loop = True
54 | while loop:
55 | for event in pygame.event.get():
56 | if event.type == QUIT \
57 | or (event.type == KEYDOWN and event.key == K_ESCAPE):
58 | loop = False
59 | board.draw(screen)
60 | sleep(.1)
61 | pygame.quit()
62 |
--------------------------------------------------------------------------------
/Web/Treasure-Hunt/thserver2.py:
--------------------------------------------------------------------------------
1 | import string
2 | from random import randint, choice
3 | from flask import Flask, abort
4 | app = Flask(__name__)
5 |
6 | URL_BASE = "http://192.168.1.7:5000/"
7 |
8 |
9 | def path_gen():
10 | chars = string.ascii_lowercase + string.digits
11 | while True:
12 | yield ''.join([choice(chars) for a in range(5)])
13 |
14 | multiplier = randint(1, 10)
15 | multiplicand = randint(1, 10)
16 | actual_product = multiplier * multiplicand
17 | rg = path_gen()
18 | max_puzzle_path = next(rg)
19 | treasure = str(1000 + randint(0, 999))
20 | max_of = [3000 + randint(0, 999) for n in range(500)]
21 | largest = str(max(max_of))
22 | max_of_str = [str(n) for n in max_of]
23 |
24 |
25 | def u(p): return URL_BASE + p
26 |
27 |
28 | @app.route("/")
29 | def start():
30 | return "%s where number = %s × %s" % (u("number"), u('multiplier'), u('multiplicand'))
31 |
32 |
33 | @app.route('/multiplier')
34 | def m1():
35 | return str(multiplier)
36 |
37 |
38 | @app.route('/multiplicand')
39 | def m2():
40 | return str(multiplicand)
41 |
42 |
43 | @app.route("/" + max_puzzle_path)
44 | def max_puzzle():
45 | return "%s where number is the largest of (%s)" % (u('number'), ', '.join(max_of_str))
46 |
47 |
48 | @app.route("/")
49 | def product(product_guess):
50 | return u(max_puzzle_path) if product_guess == actual_product else abort(404)
51 |
52 |
53 | @app.route("/" + largest)
54 | def words_matching_regex():
55 | return '%s where string is the word from this list with three vowels in a row: (kidnapper, bindweed, euonymus, almost, marabou, dismembered, underused, struma, assumptions, tzar, naze, wore, bare, jones, stick, zebrine, laxative, reynard, uninjured, river, manners, faulty, neglect, required, shabby, lobster, dour, fraise, colognes, expressing, eardrop, sneaker, adultery)' % \
56 | u("string")
57 |
58 |
59 | @app.route("/euonymus")
60 | def treasure():
61 | return "You have reached the treasure!"
62 |
63 |
64 | if __name__ == "__main__":
65 | app.run(host='192.168.1.7', debug=True)
--------------------------------------------------------------------------------
/Pygame/Two Bees/bees.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from pygame.locals import *
3 | from bee import Bee
4 |
5 | pygame.init()
6 | screen = pygame.display.set_mode((700, 394), 0)
7 | screen_rect = screen.get_rect()
8 | background = screen.copy()
9 | for y in range(screen_rect.height):
10 | color_val = 255 - 255 * y / screen_rect.height
11 | pygame.draw.line(background, (0, color_val, 0), (0, y), (screen_rect.width, y))
12 | Bee.loadImages()
13 |
14 | screen.blit(background, (0, 0))
15 | pygame.display.flip()
16 |
17 | auto_bees = pygame.sprite.Group()
18 |
19 | player_bee = Bee(screen_rect)
20 | player_bee.rect = player_bee.rect.move((50, 50))
21 | auto_bee = Bee(screen_rect)
22 | auto_bees.add(auto_bee)
23 | imgRect = player_bee.image.get_rect()
24 | player_bee.rect = imgRect.move(50, screen_rect.centery - imgRect.centery)
25 |
26 | drawing_group = pygame.sprite.RenderUpdates()
27 | drawing_group.add(player_bee, auto_bee)
28 |
29 | pygame.display.set_caption('One Bee')
30 | pygame.mouse.set_visible(0)
31 |
32 | clock = pygame.time.Clock()
33 | angles = (( 45, 0, -45),
34 | ( 90, 0, -90),
35 | (135, 180, -135))
36 |
37 | # game loop
38 | loop = True
39 | while loop:
40 | # get input
41 | for event in pygame.event.get():
42 | if event.type == QUIT \
43 | or (event.type == KEYDOWN and event.key == K_ESCAPE):
44 | loop = False
45 |
46 | keystate = pygame.key.get_pressed()
47 | xdir = keystate[K_RIGHT] - keystate[K_LEFT] # -1, 0, or 1
48 | ydir = keystate[K_DOWN] - keystate[K_UP]
49 |
50 | player_bee.setAngle(angles[ydir+1][xdir+1])
51 | player_bee.rect = player_bee.rect.move((xdir * 8, ydir * 8)).clamp(screen_rect)
52 |
53 | # Detect collisions
54 | for bee in pygame.sprite.spritecollide(player_bee, auto_bees, True):
55 | bee.kill()
56 |
57 | drawing_group.clear(screen, background)
58 | drawing_group.update()
59 | changed_rects = drawing_group.draw(screen)
60 | pygame.display.update(changed_rects)
61 |
62 | # maintain frame rate
63 | clock.tick(40)
64 |
65 | pygame.quit()
66 |
--------------------------------------------------------------------------------
/Harder/auto-high-low.py:
--------------------------------------------------------------------------------
1 | from random import randint
2 | from math import log2
3 | import logging
4 | logging.basicConfig(format='%(message)s', level=logging.INFO)
5 | POWERS_OF_TEN_FOR_HIGHEST = range(3, 13, 3)
6 | NUM_TRIALS = 1000
7 |
8 | class Guesser:
9 | def __init__(self, highest, smart=False):
10 | self.low = 1
11 | self.high = self.highest = highest
12 | self.smart = smart
13 | self.last_guess = None
14 |
15 | def guess(self, too_high):
16 | if too_high is None:
17 | pass # Not set on first guess
18 | elif too_high:
19 | self.high = self.last_guess - 1
20 | else:
21 | self.low = self.last_guess + 1
22 | self.last_guess = self._middle() if self.smart else randint(self.low, self.high)
23 | logging.debug(f'{self.low:,}-{self.high:,}: {self.last_guess:,}')
24 | return self.last_guess
25 |
26 | def win(self, guesses):
27 | logging.info(f'I got it in {guesses} guesses.')
28 |
29 | def _middle(self):
30 | return self.low + (self.high - self.low) // 2
31 |
32 |
33 | with open('high-low-results.tsv', 'w') as results:
34 | results.write('Highest\tStrategy\tTrial\tGuesses\n')
35 |
36 | for power in POWERS_OF_TEN_FOR_HIGHEST:
37 | highest: int = 10 ** power
38 | logging.info(f'Between 1 and {highest:,} (binary logarithm of {highest:,} is {log2(highest):.2f}).')
39 |
40 | for smart in (True, False):
41 | logging.info('Smart' if smart else 'Random')
42 |
43 | for trial in range(1, NUM_TRIALS + 1):
44 | logging.info(f'Trial {trial}')
45 | guesser = Guesser(highest, smart=smart)
46 | number = randint(1, highest)
47 | guess = guesser.guess(None)
48 | guesses = 1
49 |
50 | while guess != number:
51 | guesses += 1
52 | guess = guesser.guess(guess > number)
53 |
54 | guesser.win(guesses)
55 | results.write(f'{highest}\t{"Halving" if smart else "Random"}\t{trial:>4}\t{guesses}\n')
56 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 5/2.py:
--------------------------------------------------------------------------------
1 | class Place:
2 |
3 | def __init__(self, desc, targets, objects):
4 | self.desc = desc
5 | self.targets = targets
6 | self.objects = objects
7 |
8 | def show(self):
9 | print((place.desc))
10 | self.showObjects()
11 | self.showTargets()
12 |
13 | def showObjects(self):
14 | if self.objects:
15 | print('These objects are here:')
16 | for object in self.objects:
17 | print(("\t", object))
18 |
19 | def showTargets(self):
20 | if self.targets:
21 | print('From here you can go to: ')
22 | for target in self.targets:
23 | print(("\t", target))
24 |
25 | def showItems():
26 | if collectedItems:
27 | print('You have collected these items:')
28 | for item in collectedItems:
29 | print(("\t", item))
30 |
31 | places = {}
32 | collectedItems = []
33 |
34 | places["forest"] = Place(
35 | "You are in the middle of a dark forest. Strange creatures howl in the distance.",
36 | ("airstrip", "waterfall"),
37 | ["acorn", "codebook", "bicycle"]
38 | )
39 | places["airstrip"] = Place(
40 | "You are at the airstrip. The place is covered with weeds.",
41 | ("forest",),
42 | ["propeller"]
43 | )
44 | places["waterfall"] = Place(
45 | "The waterfall makes a deafening sound.",
46 | ("forest",),
47 | ["fish"]
48 | )
49 |
50 | place = places["forest"]
51 |
52 | while 1:
53 | place.show()
54 | showItems()
55 | cmdLine = eval(input('--> '))
56 | cmdWords = cmdLine.split(' ')
57 | cmd = cmdWords[0]
58 | cmdArgs = cmdWords[1]
59 | availPlaces = place.targets
60 | availItems = place.objects
61 |
62 | if cmd == 'go':
63 | newPlace = cmdArgs
64 | if newPlace in availPlaces:
65 | place = places[newPlace]
66 | else:
67 | print('You can\'t go there.')
68 | elif cmd == 'get':
69 | requestedItem = cmdArgs
70 | if requestedItem in availItems and not (cmdArgs in collectedItems):
71 | collectedItems.append(requestedItem)
72 |
--------------------------------------------------------------------------------
/Jython/Life/life1.py:
--------------------------------------------------------------------------------
1 | # Conway's Game of Life, for the Young Programmers Podcast
2 |
3 | from javax.swing import JFrame, JPanel, JButton, JToggleButton, JCheckBox, Timer
4 | from java.awt import FlowLayout, GridLayout
5 | from java.awt.BorderLayout import SOUTH
6 | from GridMutator import GridMutator
7 |
8 | class LifeGame(object):
9 | def __init__(self, numRows, numCols):
10 | self.numRows = numRows
11 | self.numCols = numCols
12 | self.timer = Timer(250, None, actionPerformed=self._step)
13 |
14 | def startGui(self):
15 | frame = JFrame("Life", defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
16 | (R, C) = (self.numRows, self.numCols)
17 | gridPanel = JPanel(GridLayout(R, C))
18 | self.checkBoxes = [[JCheckBox() for c in range(C)] for r in range(R)]
19 | self.grid = [[False for c in range(C)] for r in range(R)]
20 | for r in range(R):
21 | for c in range(C):
22 | gridPanel.add(self.checkBoxes[r][c])
23 | frame.add(gridPanel)
24 | buttonPanel = JPanel(FlowLayout())
25 | stepButton = JButton("Step", actionPerformed=self._step)
26 | runButton = JToggleButton("Run", actionPerformed=self._run)
27 | buttonPanel.add(stepButton)
28 | buttonPanel.add(runButton)
29 | frame.add(buttonPanel, SOUTH)
30 | frame.pack()
31 | frame.locationRelativeTo = None
32 | frame.visible = True
33 |
34 | def _getGridFromCheckBoxes(self):
35 | return [[self.checkBoxes[r][c].selected for c in range(self.numCols)]
36 | for r in range(self.numRows)]
37 |
38 | def _step(self, event):
39 | self.grid = GridMutator().generateNext(self._getGridFromCheckBoxes())
40 | self._selectCheckBoxesFromGrid()
41 |
42 | def _run(self, event):
43 | if self.timer.running:
44 | self.timer.stop()
45 | else:
46 | self.timer.start()
47 |
48 | def _selectCheckBoxesFromGrid(self):
49 | for r in range(self.numRows):
50 | for c in range(self.numCols):
51 | self.checkBoxes[r][c].selected = self.grid[r][c]
52 |
53 | LifeGame(15,15).startGui()
--------------------------------------------------------------------------------
/Pygame/SimplePygame/random_color_grid.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | from random import randint
3 | from pygame.locals import *
4 |
5 | pygame.init()
6 | screen = pygame.display.set_mode((0, 0), FULLSCREEN)
7 | font = pygame.font.Font(None, 24)
8 | clock = pygame.time.Clock()
9 | side_length = 50
10 | frame_rate = 5
11 | bg_color = Color('black')
12 |
13 | loop = True
14 |
15 | def draw_grid():
16 | def rc():
17 | return randint(0, 255)
18 |
19 | for x in range(0, screen.get_width(), spacing):
20 | for y in range(0, screen.get_height(), spacing):
21 | pygame.draw.rect(screen, Color(rc(), rc(), rc()),
22 | Rect(x + margin, y + margin + 20, side_length, side_length))
23 |
24 | def draw_info_text():
25 | font_surface = font.render('Size: %d; FPS: Desired: %d, Avg. Actual: %.2f; Time Used (ms): %d' % (
26 | side_length, frame_rate, clock.get_fps(), clock.get_rawtime()), True, Color('white'), bg_color)
27 | screen.blit(font_surface, (margin, 5))
28 |
29 | def process_input():
30 | global loop, side_length, frame_rate
31 |
32 | event = pygame.event.poll()
33 | if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
34 | loop = False
35 |
36 | changed = False
37 | keys = pygame.key.get_pressed()
38 | mods = pygame.key.get_mods()
39 | shift = mods & KMOD_SHIFT
40 |
41 | if keys[K_UP]:
42 | side_length += 10 if shift else 1
43 | changed = True
44 | elif keys[K_DOWN]:
45 | side_length -= 10 if shift else 1
46 | changed = True
47 | if keys[K_RIGHT]:
48 | frame_rate += 10 if shift else 1
49 | elif keys[K_LEFT]:
50 | frame_rate -= 10 if shift else 1
51 | if frame_rate < 1:
52 | frame_rate = 1
53 | if side_length < 2:
54 | side_length = 2
55 | return changed
56 |
57 | while loop:
58 | changed = process_input()
59 |
60 | screen.fill(bg_color)
61 | margin = max(side_length / 10, 1)
62 | spacing = side_length + margin
63 |
64 | draw_grid()
65 | draw_info_text()
66 | pygame.display.flip()
67 |
68 | clock.tick(60 if changed else frame_rate)
69 |
70 | pygame.quit()
71 |
--------------------------------------------------------------------------------
/Pygame/Bees/bees.py:
--------------------------------------------------------------------------------
1 | import pygame, random
2 | from pygame.locals import *
3 | from util import loadImage
4 | from bee import Bee
5 | from flower import Flower
6 | from score import Score
7 |
8 | pygame.init()
9 | TITLE = 'Bee, Get the Nectar!'
10 | screen = pygame.display.set_mode((1280, 720), 0)
11 | screenRect = screen.get_rect()
12 | Bee.loadImages()
13 | Flower.loadImages()
14 | background = loadImage('clover-large.jpg')
15 |
16 | font = pygame.font.Font(None, 48)
17 | text = font.render(TITLE, 1, Color('white'))
18 | textpos = text.get_rect(centerx=screenRect.width/2, centery=25)
19 | background.blit(text, textpos)
20 |
21 | screen.blit(background, (0, 0))
22 | pygame.display.flip()
23 |
24 | bee = Bee(screenRect)
25 | flowers = pygame.sprite.Group()
26 | score = Score()
27 |
28 | drawingGroup = pygame.sprite.RenderUpdates()
29 | drawingGroup.add(bee)
30 | drawingGroup.add(score)
31 |
32 | pygame.display.set_caption(TITLE)
33 | pygame.mouse.set_visible(0)
34 |
35 | clock = pygame.time.Clock()
36 | angles = (( 45, 0, -45),
37 | ( 90, 0, -90),
38 | (135, 180, -135))
39 |
40 | # game loop
41 | loop = True
42 | while loop:
43 | # get input
44 | for event in pygame.event.get():
45 | if event.type == QUIT \
46 | or (event.type == KEYDOWN and event.key == K_ESCAPE):
47 | loop = False
48 |
49 | keystate = pygame.key.get_pressed()
50 | xdir = keystate[K_RIGHT] - keystate[K_LEFT] # -1, 0, or 1
51 | ydir = keystate[K_DOWN] - keystate[K_UP]
52 |
53 | bee.setAngle(angles[ydir+1][xdir+1])
54 | bee.rect = bee.rect.move((xdir * 8, ydir * 8)).clamp(screenRect)
55 |
56 | # Detect collisions
57 | for flower in pygame.sprite.spritecollide(bee, flowers, True):
58 | score.score += 1
59 | flower.kill()
60 |
61 | if random.randint(0, 50) == 0:
62 | flower = Flower(screenRect)
63 | drawingGroup.add(flower)
64 | flowers.add(flower)
65 |
66 | drawingGroup.clear(screen, background)
67 | drawingGroup.update()
68 | changedRects = drawingGroup.draw(screen)
69 | pygame.display.update(changedRects)
70 |
71 | # maintain frame rate
72 | clock.tick(40)
73 |
74 | pygame.quit()
75 |
--------------------------------------------------------------------------------
/Pygame/jump/platform.py:
--------------------------------------------------------------------------------
1 | '''
2 | Demonstration of jumping.
3 | Dave Briccetti, Young Programmers Podcast: http://young-programmers.blogspot.com/
4 | '''
5 |
6 | import pygame
7 | from pygame.locals import *
8 |
9 | MAN_SCREEN_MARGIN = 5 # pixels
10 | JUMPING_DURATION = 500 # milliseconds
11 | HORZ_MOVE_INCREMENT = 4 # pixels
12 | TIME_AT_PEAK = JUMPING_DURATION / 2
13 | JUMP_HEIGHT = 200 # pixels
14 |
15 | pygame.init()
16 | clock = pygame.time.Clock()
17 | screen = pygame.display.set_mode((500, 300), 0)
18 | pygame.display.set_caption('Jumping Man')
19 | man = pygame.image.load('red-man.png').convert_alpha()
20 |
21 | def floorY():
22 | ''' The Y coordinate of the floor, where the man is placed '''
23 | return 0#screen.get_height() - man.get_height() - MAN_SCREEN_MARGIN
24 |
25 | def jumpHeightAtTime(elapsedTime):
26 | ''' The height of the jump at the given elapsed time (milliseconds) '''
27 | return 0#((-1.0/TIME_AT_PEAK**2)* \
28 | #((elapsedTime-TIME_AT_PEAK)**2)+1)*JUMP_HEIGHT
29 |
30 | manX = screen.get_width() / 2
31 | manY = floorY()
32 | jumping = False
33 | jumpingHorz = 0
34 |
35 | loop = False
36 | while loop:
37 | for event in pygame.event.get():
38 | if event.type == QUIT \
39 | or (event.type == KEYDOWN and event.key == K_ESCAPE):
40 | loop = False
41 |
42 | keys = pygame.key.get_pressed()
43 |
44 | def horzMoveAmt():
45 | ''' Amount of horizontal movement based on left/right arrow keys '''
46 | return (keys[K_RIGHT] - keys[K_LEFT]) * HORZ_MOVE_INCREMENT
47 |
48 | if not jumping:
49 | manX += horzMoveAmt()
50 | if keys[K_SPACE]:
51 | jumping = True
52 | jumpingHorz = horzMoveAmt()
53 | jumpingStart = pygame.time.get_ticks()
54 |
55 | if jumping:
56 | t = pygame.time.get_ticks() - jumpingStart
57 | if t > JUMPING_DURATION:
58 | jumping = False
59 | jumpHeight = 0
60 | else:
61 | jumpHeight = jumpHeightAtTime(t)
62 |
63 | manY = floorY() - jumpHeight
64 | manX += jumpingHorz
65 |
66 | screen.fill((180,120,120))
67 | screen.blit(man, (manX, manY))
68 | pygame.display.flip()
69 | clock.tick(50)
70 |
--------------------------------------------------------------------------------
/Jython/Life2/LifeGame.py:
--------------------------------------------------------------------------------
1 | # Conway's Game of Life, for the Young Programmers Podcast
2 |
3 | from javax.swing import JFrame, JPanel, JButton, JToggleButton, Timer
4 | from java.awt import FlowLayout, GridLayout
5 | from java.awt.BorderLayout import SOUTH
6 | from GridMutator import GridMutator
7 |
8 | class LifeGame(object):
9 | def __init__(self, numRows, numCols):
10 | self.numRows = numRows
11 | self.numCols = numCols
12 | self.timer = Timer(250, None, actionPerformed=self._step)
13 | self.gridMutator = GridMutator()
14 |
15 | def startGui(self):
16 | frame = JFrame("Life", defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
17 | self.gridPanel = JPanel(GridLayout(self.numRows, self.numCols))
18 | self.cellButtons = self._doForAllCells(self._createCellButton)
19 | self.grid = self._doForAllCells(lambda r,c: False)
20 | frame.add(self.gridPanel)
21 | buttonPanel = JPanel(FlowLayout())
22 | stepButton = JButton("Step", actionPerformed=self._step)
23 | runButton = JToggleButton("Run", actionPerformed=self._run)
24 | buttonPanel.add(stepButton)
25 | buttonPanel.add(runButton)
26 | frame.add(buttonPanel, SOUTH)
27 | frame.pack()
28 | frame.locationRelativeTo = None
29 | frame.visible = True
30 |
31 | def _step(self, event):
32 | self.grid = self.gridMutator.generateNext(
33 | self._doForAllCells(lambda r,c: self.cellButtons[r][c].selected))
34 | self._doForAllCells(self._selectCellButtonFromGrid)
35 |
36 | def _run(self, event):
37 | if self.timer.running:
38 | self.timer.stop()
39 | else:
40 | self.timer.start()
41 |
42 | def _createCellButton(self, r, c):
43 | button = JToggleButton()
44 | s = button.preferredSize
45 | button.preferredSize = (s.height, s.height) # Make square
46 | self.gridPanel.add(button)
47 | return button
48 |
49 | def _doForAllCells(self, fn):
50 | return [[fn(r,c) for c in range(self.numCols)] for r in range(self.numRows)]
51 |
52 | def _selectCellButtonFromGrid(self, r, c):
53 | self.cellButtons[r][c].selected = self.grid[r][c]
54 |
55 | LifeGame(15, 15).startGui()
56 |
--------------------------------------------------------------------------------
/Pygame/InvisibleMaze/invisiblemaze.py:
--------------------------------------------------------------------------------
1 | import math
2 | import pygame
3 | from pygame.locals import *
4 | from imageutil import loadImage
5 |
6 | def main():
7 | pygame.init()
8 | title = 'Invisible Maze'
9 | screen = pygame.display.set_mode((500, 500), 0)
10 | screenRect = screen.get_rect()
11 | pygame.display.flip()
12 |
13 | player = loadImage('player.png')
14 | playerRect = player.get_rect()
15 | playerRect.y = screenRect.height - playerRect.height
16 | obstacles = (ob(100, 400), ob(200, 220), ob(350, 230), ob(450, 100),
17 | ob(460, 350))
18 | exitRect = Rect(490, 200, 10, 100)
19 |
20 | pygame.display.set_caption(title)
21 | pygame.mouse.set_visible(0)
22 | clock = pygame.time.Clock()
23 |
24 | # game loop
25 | loop = True
26 | hit = False
27 | playerVisible = True
28 | while loop:
29 | # get input
30 | for event in pygame.event.get():
31 | if event.type == QUIT \
32 | or (event.type == KEYDOWN and event.key == K_ESCAPE):
33 | loop = False
34 |
35 | keystate = pygame.key.get_pressed()
36 | xdir = keystate[K_RIGHT] - keystate[K_LEFT]
37 | ydir = keystate[K_DOWN] - keystate[K_UP]
38 | if xdir or ydir:
39 | playerVisible = False
40 | if not hit:
41 | playerRect = playerRect.move((xdir * 2, ydir * 2)).clamp(screenRect)
42 |
43 | screen.fill((0,0,0))
44 | screen.fill((0,255,0), exitRect)
45 |
46 | for obstacle in obstacles:
47 | screen.fill(colorFromDistance(playerRect.center, obstacle.center),
48 | obstacle)
49 | if playerRect.colliderect(obstacle):
50 | hit = True
51 | playerVisible = True
52 | if playerVisible:
53 | screen.blit(player, playerRect)
54 | pygame.display.flip()
55 |
56 | # maintain frame rate
57 | clock.tick(40)
58 |
59 | pygame.quit()
60 |
61 | def ob(x, y):
62 | return Rect(x, y, 30, 30)
63 |
64 | def colorFromDistance(loc1, loc2):
65 | dx = loc2[0] - loc1[0]
66 | dy = loc2[1] - loc1[1]
67 | dist = min(127, math.sqrt(dx * dx + dy * dy))
68 | return (255-dist*2, 0, 0)
69 |
70 | if __name__ == '__main__':
71 | main()
72 |
--------------------------------------------------------------------------------
/Web/Screen-Scraping/web_crawler.py:
--------------------------------------------------------------------------------
1 | # A simple web crawler using requests and Beautiful Soup
2 | # Use with care, as it fetches pages serially without any delays, and doesn't look at robots.txt.
3 |
4 | from queue import Queue
5 | from typing import Dict
6 | from urllib.parse import urlparse
7 |
8 | import requests
9 | from bs4 import BeautifulSoup
10 |
11 | STARTING_URL = 'https://your web site'
12 | IGNORE_PATHS = ('', '/')
13 |
14 | found_paths_with_titles: Dict[str, str] = dict()
15 | queue = Queue()
16 | queue.put_nowait(STARTING_URL)
17 |
18 | while not queue.empty():
19 | current_url: str = queue.get()
20 | parsed_current_url = urlparse(current_url)
21 | if parsed_current_url.path not in found_paths_with_titles:
22 | print('fetching ' + parsed_current_url.path)
23 | response = requests.get(current_url, headers={'User-Agent': 'Simple web crawler'})
24 | print('done fetching ' + parsed_current_url.path)
25 | if response.status_code != 200:
26 | print(f'Status code {response.status_code}')
27 | else:
28 | if 'text/html' in response.headers['content-type']:
29 | html_doc = response.text
30 | soup = BeautifulSoup(html_doc, 'html.parser')
31 | title = soup.find('title')
32 | found_paths_with_titles[parsed_current_url.path] = title.text if title else ''
33 |
34 | unique_paths = set()
35 | for parsed_url in (urlparse(a['href']) for a in soup.find_all('a', href=True)):
36 | if parsed_url.path not in IGNORE_PATHS and not parsed_url.scheme:
37 | start = 1 if parsed_url.path[0] == '/' else 0
38 | unique_paths.add(parsed_url.path[start:])
39 |
40 | for path in unique_paths:
41 | url: str = parsed_current_url.scheme + '://' + parsed_current_url.netloc + '/' + path
42 | queue.put_nowait(url)
43 |
44 | print(f'Found {len(found_paths_with_titles)}, enqueued: {queue.qsize()}')
45 | queue.task_done()
46 |
47 | longest_path: int = max((len(key) for key in found_paths_with_titles.keys()))
48 | for key in sorted(found_paths_with_titles.keys()):
49 | print(f'{key:{longest_path + 1}s}{found_paths_with_titles[key]}')
50 |
--------------------------------------------------------------------------------
/Internet/locdraw/server.py:
--------------------------------------------------------------------------------
1 | import socket
2 | from queue import Queue
3 | import turtle
4 | from turtle import Turtle
5 | from threading import Thread, current_thread
6 | from port import PORT
7 |
8 | serverSocket = None
9 | cmd_queue = Queue()
10 |
11 | class Move:
12 | def __init__(self, parts):
13 | self.name = parts[0]
14 | self.x = int(parts[1])
15 | self.y = int(parts[2])
16 | self.color = parts[3]
17 |
18 | turtles = {} # Client name -> turtle
19 |
20 | def handle_client(client_socket, address):
21 | print('handle_client on ' + current_thread().name)
22 | client_socket.send("Hi there\n".encode())
23 | while True:
24 | line = client_socket.recv(1024).decode()
25 | parts = line.split('\t')
26 | if len(parts) == 4:
27 | cmd_queue.put(Move(parts))
28 | print(address, line)
29 | client_socket.send('Thanks for that\n'.encode())
30 |
31 |
32 | def listen_thread():
33 | global serverSocket
34 | print('listen_thread on ' + current_thread().name)
35 | serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
36 | serverSocket.bind(('', PORT))
37 | serverSocket.listen(100)
38 |
39 | while True:
40 | print('Game server waiting for connection')
41 | (client_socket, address) = serverSocket.accept()
42 | print('How exciting! A connection from', address)
43 | Thread(target=handle_client, args=(client_socket, address)).start()
44 |
45 | Thread(target=listen_thread).start()
46 |
47 | turtle_shapes = ('arrow', 'circle', 'square', 'triangle', 'classic', 'turtle')
48 |
49 |
50 | def add_turtle(name):
51 | t = Turtle()
52 | t.speed('fast')
53 | #t.penup()
54 | t.shape(turtle_shapes[len(turtles) % len(turtle_shapes)])
55 | turtles[name] = t
56 | t.setheading(90) # Point up
57 | return t
58 |
59 | try:
60 | turtle.setup(650, 650)
61 | turtle.hideturtle()
62 | for n in range(100000):
63 | cmd = cmd_queue.get()
64 | client_turtle = turtles.get(cmd.name) or add_turtle(cmd.name)
65 | if n % 50 == 0: # Clear all turtles periodically
66 | for turtle in turtles.values():
67 | turtle.clear()
68 | client_turtle.pencolor(cmd.color)
69 | client_turtle.goto(cmd.x, cmd.y)
70 | except KeyboardInterrupt:
71 | print('Stopping server')
72 | serverSocket.close()
73 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 6/adventure3/adventure3.py:
--------------------------------------------------------------------------------
1 | # Dave's Exciting Text Adventure Game, Version 3
2 |
3 | from place import Place
4 | from placexml import PlaceXml
5 | from commandline import CommandLine
6 |
7 | def showDirections():
8 | directions = ['', '', 'Welcome to',
9 | 'Dave\'s Exciting Text Adventure Game, now with XML.',
10 | '(The X is for eXtra fun!!!)', '']
11 | for dirLine in directions:
12 | print(dirLine.center(70))
13 |
14 | print('''
15 | Commands:
16 | go "place"
17 | get "object"
18 | quit
19 | ''')
20 |
21 | def showItems():
22 | if collectedItems:
23 | print('You have collected these items:')
24 | for item in collectedItems:
25 | print("\t", item)
26 |
27 |
28 | # Load all the places from the XML file into the places hash
29 | places = {}
30 | placeXml = PlaceXml("game.xml", places)
31 |
32 | # Set the starting place, from an attribute in the XML file
33 | place = places[placeXml.startingPlace]
34 |
35 | # Keep our collected items in a list
36 | collectedItems = []
37 |
38 | showDirections()
39 |
40 |
41 | keepPlaying = 1
42 |
43 | # Create one of these to parse our command lines
44 | commandLine = CommandLine()
45 |
46 | # Loop until the user wants to quit
47 | while keepPlaying:
48 | place.show()
49 | print()
50 | showItems()
51 |
52 | # Get a line, and give it to the parser
53 | rawLine = input('--> ')
54 | commandLine.set(rawLine)
55 |
56 | if commandLine.cmd == 'go':
57 | newPlace = commandLine.args
58 | if newPlace in place.connections:
59 | # The requested place is valid. "Move" to it.
60 | place = places[newPlace]
61 | else:
62 | print('There\'s no place called "%s," now, is there?' % newPlace)
63 |
64 | elif commandLine.cmd == 'get':
65 | requestedItem = commandLine.args
66 | if requestedItem in place.objects:
67 | print('You got the', requestedItem)
68 | collectedItems.append(requestedItem)
69 | place.deleteObject(requestedItem)
70 | else:
71 | print('There\'s no object called "%s," and everyone knows it.' % requestedItem)
72 |
73 | elif commandLine.cmd == 'quit':
74 | keepPlaying = 0
75 | print('Come back real soon, now, you hear?')
76 |
77 | else:
78 | print('Why would you type something like, "%s"?' % (rawLine))
79 |
--------------------------------------------------------------------------------
/Web/flask/morse/morseserver.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from time import time
3 | from flask import Flask, request
4 | from codes import PASSWORD, morse_codes, symbols_by_word
5 |
6 | logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(threadName)s %(message)s')
7 | log = logging.getLogger('morseserver')
8 | app = Flask(__name__)
9 |
10 | PLAIN_HEADER = {'Content-Type': 'text/plain; charset=utf-8'}
11 | STAY_UNLOCKED_SECS = 20
12 | TIMEOUT_SECONDS = 10
13 | SECRET_PATTERN = ''.join((morse_codes[letter] for letter in PASSWORD))
14 | states_by_addr = {}
15 |
16 |
17 | class UserState:
18 | 'Stores data needed for each remote user making requests'
19 | def __init__(self):
20 | self.elements_matched = 0
21 | self.last_request_time = time()
22 | self.unlocked_at = None # The time last unlocked, or None if locked
23 |
24 |
25 | @app.route('/code/')
26 | def code(code_word):
27 | code = symbols_by_word.get(code_word)
28 | if not code:
29 | return 'Must be dash or dot.', 404, PLAIN_HEADER
30 | addr = request.remote_addr
31 | state = states_by_addr.get(addr, UserState())
32 | states_by_addr[addr] = state
33 | if time() > state.last_request_time + TIMEOUT_SECONDS:
34 | log.info('Timed out')
35 | state.elements_matched = 0
36 | state.last_request_time = time()
37 | next_code = SECRET_PATTERN[state.elements_matched]
38 | if code == next_code:
39 | state.elements_matched += 1
40 | if state.elements_matched == len(SECRET_PATTERN):
41 | state.elements_matched = 0 # Reset so they can run again
42 | state.unlocked_at = time()
43 | log.info(addr + ' unlocked')
44 | return 'Unlocked!', 200, PLAIN_HEADER
45 | else:
46 | log.debug('%s elements matched: %d', addr, state.elements_matched)
47 | return "Keep going.", 200, PLAIN_HEADER
48 | else:
49 | state.unlocked_at = None
50 | state.elements_matched = 0
51 | return 'Wrong. Start again.', 400, PLAIN_HEADER
52 |
53 |
54 | @app.route('/secret')
55 | def secret():
56 | state = states_by_addr.get(request.remote_addr)
57 | if state and state.unlocked_at and state.unlocked_at > time() - STAY_UNLOCKED_SECS:
58 | return 'The secret is 42'
59 |
60 | return ('Give the password via Morse Code, then request the secret within %d seconds.' %
61 | STAY_UNLOCKED_SECS, 403, PLAIN_HEADER)
62 |
63 |
64 | app.run(host='localhost', debug=True, threaded=True)
65 |
--------------------------------------------------------------------------------
/Harder/runways.py:
--------------------------------------------------------------------------------
1 | 'Give information about airports and their runways'
2 |
3 | from os import mkdir, path
4 |
5 | import pandas as pd
6 | import requests
7 | from requests import Response
8 |
9 |
10 | def run():
11 | DATA_URL = 'https://github.com/davidmegginson/ourairports-data/raw/main'
12 | CACHE_DIR = 'aviation-cache'
13 |
14 | def cache_files_if_needed():
15 | try:
16 | mkdir(CACHE_DIR)
17 | except FileExistsError:
18 | pass
19 | for filename in ['airports.csv', 'runways.csv']:
20 | path_fn = f'{CACHE_DIR}/{filename}'
21 | if not path.exists(path_fn):
22 | print('fetching', path_fn)
23 | with open(path_fn, 'w') as f:
24 | full_url = f'{DATA_URL}/{filename}'
25 | response: Response = requests.get(full_url)
26 | if response.status_code == 200:
27 | f.write(response.text)
28 |
29 | def create_airports_df():
30 | cols = 'name ident type latitude_deg longitude_deg elevation_ft iso_country iso_region municipality'.split()
31 | df = pd.read_csv(f'{CACHE_DIR}/airports.csv', index_col='ident', usecols=cols)
32 | df['type'] = df['type'].astype('category')
33 | df['elevation_ft'] = df['elevation_ft'].fillna(0).astype('int32')
34 | return df
35 |
36 | def create_runways_df():
37 | cols = 'id airport_ref airport_ident length_ft width_ft surface closed le_ident he_ident'.split()
38 | df = pd.read_csv(f'{CACHE_DIR}/runways.csv', index_col='id', usecols=cols)
39 | df['length_ft'] = df['length_ft'].fillna(0).astype('int16')
40 | df['width_ft' ] = df['width_ft' ].fillna(0).astype('int16')
41 | return df
42 |
43 | def print_airport_info(ident) -> None:
44 | ap = airports.loc[ident]
45 | print(f"{ap['name']} is in {ap.iso_region}, {ap.municipality}, elev. {ap.elevation_ft} ft")
46 |
47 | def print_runway_info(ident) -> None:
48 | print('Runways')
49 | airport_rws = runways[runways['airport_ident'] == ident]
50 | for row in airport_rws.itertuples():
51 | print(f"{row.le_ident}/{row.he_ident}: {row.length_ft}×{row.width_ft} ft")
52 |
53 | cache_files_if_needed()
54 | airports = create_airports_df()
55 | runways = create_runways_df()
56 |
57 | while True:
58 | if not (ident := input('\nWhat airport ID? ').strip().upper()):
59 | break
60 | if ident not in airports.index and ('K' + ident) in airports.index:
61 | ident = 'K' + ident # Add the K automatically
62 | if ident in airports.index:
63 | print_airport_info(ident)
64 | print_runway_info(ident)
65 | else:
66 | print('Can’t find that airport')
67 |
68 | if __name__ == '__main__':
69 | run()
70 |
--------------------------------------------------------------------------------
/Pygame/Bee Invaders/bees.py:
--------------------------------------------------------------------------------
1 | from time import time
2 | from random import randint
3 | import pygame
4 | from pygame.locals import *
5 | from bee import Bee
6 | from projectile import Projectile
7 | from monster import Monster
8 |
9 | pygame.init()
10 | screen = pygame.display.set_mode((700, 700), 0)
11 | screen_rect = screen.get_rect()
12 | background = screen.copy()
13 | for y in range(screen_rect.height):
14 | color_val = 255 - 255 * y / screen_rect.height
15 | pygame.draw.line(background, (0, color_val, 0), (0, y), (screen_rect.width, y))
16 | Bee.loadImages()
17 |
18 | screen.blit(background, (0, 0))
19 | pygame.display.flip()
20 |
21 | invaders = pygame.sprite.Group()
22 | projectiles = pygame.sprite.Group()
23 | monsters = pygame.sprite.Group()
24 |
25 | drawing_group = pygame.sprite.OrderedUpdates()
26 | player_bee = Bee(10, screen.get_height() - 200)
27 |
28 | for x in range(10, screen.get_width(), 100):
29 | for y in range(10, screen.get_height() - 300, 100):
30 | auto_bee = Bee(x, y)
31 | auto_bee.setAngle(180)
32 | invaders.add(auto_bee)
33 | drawing_group.add(auto_bee)
34 |
35 | drawing_group.add(player_bee)
36 |
37 | pygame.display.set_caption('Bee Invaders')
38 | pygame.mouse.set_visible(False)
39 |
40 | clock = pygame.time.Clock()
41 | angles = (( 45, 0, -45),
42 | ( 90, 0, -90),
43 | (135, 180, -135))
44 |
45 | loop = True
46 | time_last_fire = 0
47 |
48 | while loop:
49 | for event in pygame.event.get():
50 | if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
51 | loop = False
52 |
53 | if randint(1, 800) == 1:
54 | monster = Monster(screen_rect, drawing_group)
55 | drawing_group.add(monster)
56 | monsters.add(monster)
57 |
58 | keystate = pygame.key.get_pressed()
59 | mods = pygame.key.get_mods()
60 | shift = mods & KMOD_SHIFT
61 |
62 | if keystate[K_SPACE]:
63 | time_now = time()
64 | time_since_fire = time_now - time_last_fire
65 | if time_since_fire > (.2 if shift else .5):
66 | time_last_fire = time()
67 | projectile = Projectile(player_bee.rect.x + player_bee.rect.width / 2, player_bee.rect.y)
68 | drawing_group.add(projectile)
69 | projectiles.add(projectile)
70 |
71 | xdir = keystate[K_RIGHT] - keystate[K_LEFT] # -1, 0, or 1
72 | ydir = keystate[K_DOWN] - keystate[K_UP]
73 |
74 | player_bee.setAngle(angles[ydir+1][xdir+1])
75 | player_bee.rect = player_bee.rect.move((xdir * 8, ydir * 8)).clamp(screen_rect)
76 |
77 | pygame.sprite.groupcollide(projectiles, invaders, True, True)
78 | pygame.sprite.groupcollide(projectiles, monsters, True, True)
79 |
80 | drawing_group.clear(screen, background)
81 | drawing_group.update()
82 | changed_rects = drawing_group.draw(screen)
83 | pygame.display.update(changed_rects)
84 |
85 | clock.tick(60)
86 |
87 | pygame.quit()
88 |
--------------------------------------------------------------------------------
/Course-2004/Lesson 2/LessonPlan.txt:
--------------------------------------------------------------------------------
1 | Computer Programming with Dave Briccetti
2 | Wed, Feb 18, 2004
3 | Introduction to Python
4 | Concise Notes
5 |
6 | Topics:
7 | 1) Functions
8 | 2) Exceptions
9 | 3) Classes
10 | 4) GUI
11 |
12 | FUNCTIONS
13 |
14 | Example 1:
15 | def showIntro():
16 | print "This is the exciting introduction ..."
17 |
18 | showIntro()
19 |
20 | Example 2:
21 | def addNumbers(num1, num2):
22 | return num1 + num2
23 |
24 | sum = addNumbers(3,4)
25 | print sum
26 |
27 | Problem 1:
28 | Write a program with a function which prompts the user for a
29 | float, and returns it.
30 |
31 | EXCEPTIONS
32 |
33 | Example 3:
34 | try:
35 | num = float(input('Give us a number: '))
36 | except ValueError:
37 | print 'Bad number'
38 |
39 | Problem 2:
40 | Prompt for two numbers. Display the result of dividing the first
41 | number by the second. Prevent the program from "crashing" when
42 | the divisor is 0.
43 |
44 | CLASSES
45 |
46 | Example 4:
47 | class Robot:
48 | def workOn(self, task):
49 | print 'I am working on', task
50 |
51 | robot = Robot()
52 | robot.workOn('welding')
53 |
54 | Problem 3:
55 | Create a class called Calculator. Give it functions add, multiply
56 | and divide. Handle a divide by 0 error.
57 |
58 | GUI
59 |
60 | Example 5:
61 | from Tkinter import *
62 |
63 | class Application(Frame):
64 | def createWidgets(self):
65 | self.quitButton = Button(self, text = 'Quit', command = self.quit)
66 | self.quitButton.pack()
67 | def __init__(self, master=None):
68 | Frame.__init__(self, master)
69 | self.pack()
70 | self.createWidgets()
71 |
72 | app = Application()
73 | app.mainloop()
74 |
75 | Example 6:
76 | from Tkinter import *
77 |
78 | class Application(Frame):
79 | def greet(self):
80 | if self.formal.get():
81 | self.greeting.set('Hello. How are you?')
82 | else:
83 | self.greeting.set("What's up?")
84 |
85 | def createWidgets(self):
86 | self.formal = IntVar()
87 | self.button = Checkbutton(self, text = 'Formal', variable = self.formal)
88 | self.button.grid(row = 1, column = 1, columnspan = 2)
89 |
90 | self.greeting = StringVar()
91 | self.greetingLabel = Label(self, textvariable = self.greeting)
92 | self.greetingLabel.grid(row = 2, column = 1, columnspan = 2)
93 |
94 | self.quitButton = Button(self, text = 'Quit', command = self.quit)
95 | self.quitButton.grid(row = 3, column = 1, padx = 5, pady = 5)
96 |
97 | self.greetMeButton = Button(self, text = "Greet Me", command = self.greet)
98 | self.greetMeButton.grid(row = 3, column = 2, padx = 5)
99 |
100 | def __init__(self, master=None):
101 | Frame.__init__(self, master)
102 | self.grid()
103 | self.createWidgets()
104 |
105 | app = Application()
106 | app.master.title("My Cool Application")
107 | app.mainloop()
108 |
--------------------------------------------------------------------------------
/Web/dumpmeetup.py:
--------------------------------------------------------------------------------
1 | import datetime
2 | import requests
3 |
4 |
5 | def pt(type, *args):
6 | args_list = [str(arg) for arg in args]
7 | args_list.insert(0, type)
8 | print('\t'.join(args_list))
9 |
10 |
11 | events = requests.get('https://api.meetup.com/Young-Programmers/events', params={
12 | 'status': 'past',
13 | 'key': 'your-key',
14 | }).json()
15 |
16 | questions = {}
17 |
18 | def remnl(text): return text.replace('\n', '
')
19 |
20 | def fmttm(ms):
21 | time = int(ms) // 1000
22 | return datetime.datetime.fromtimestamp(time)
23 |
24 | for event in events:
25 | time = fmttm(event['time'])
26 | duration = event.get('duration', '')
27 | if duration:
28 | duration = int(duration) / 360000.0
29 | fee = event['fee']['amount'] if 'fee' in event and 'amount' in event['fee'] else ''
30 | pt('e', time, duration, event['name'], fee, remnl(event['description']))
31 |
32 | comments = requests.get('https://api.meetup.com/Young-Programmers/events/%s/comments' % event['id'], params={
33 | 'key': 'your-key',
34 | }).json()
35 |
36 | for comment in comments:
37 | member = comment['member']
38 | name = member['name']
39 | pt('c', name, remnl(comment['comment']))
40 |
41 | rsvps = requests.get('https://api.meetup.com/Young-Programmers/events/%s/rsvps' % event['id'], params={
42 | 'key': 'your-key',
43 | 'fields': 'attendance_status,answers'
44 | }).json()
45 |
46 | for rsvp in rsvps:
47 | response = rsvp['response']
48 | name = rsvp['member']['name']
49 | if response != 'no' and name != 'Dave Briccetti':
50 | pt('r', name, response, rsvp['guests'], rsvp.get('attendance_status', ''))
51 | answers = rsvp.get('answers', [])
52 | for answer in answers:
53 | a = remnl(answer['answer'])
54 | if a:
55 | qid = answer['question_id']
56 | questions[qid] = answer['question']
57 | pt('a', qid, a)
58 |
59 | for id, question in questions.items():
60 | pt('q', id, question)
61 |
62 | members = []
63 | for offset in range(3): # Works for 483 members, which is < 200 * 3 pages todo Make work for all
64 | mr = requests.get('https://api.meetup.com/Young-Programmers/members', params={
65 | 'key': 'your-key',
66 | 'fields': 'attendance_status,answers',
67 | 'offset': offset
68 | })
69 | members += mr.json()
70 |
71 | pt('m', 'ID', 'Name', 'City', 'Joined', 'Bio', 'Intro', 'Photo link')
72 | for member in members:
73 | id = member['id']
74 | name = member['name']
75 | city = member['city']
76 | joined = fmttm(member['joined'])
77 | bio = remnl(member.get('bio', ''))
78 | intro = remnl(member['group_profile']['intro']) if 'group_profile' in member and 'intro' in member['group_profile'] else ''
79 | photo = member['photo']['highres_link'] if 'photo' in member and 'highres_link' in member['photo'] else ''
80 | pt('m', id, name, city, joined, bio, intro, photo)
--------------------------------------------------------------------------------