├── LSystemFractalTrees ├── __init__.py ├── triangle.txt ├── dragon.txt ├── tree.txt ├── plant.txt ├── sierpinski.txt ├── .vscode │ ├── settings.json │ └── launch.json ├── __pycache__ │ ├── main.cpython-38.pyc │ └── LSystem.cpython-38.pyc ├── Lsystems.txt ├── main.py ├── LSystem.py ├── system.py └── LSys.py ├── README.md ├── .DS_Store ├── Hangman ├── .idea │ ├── .gitignore │ ├── misc.xml │ ├── inspectionProfiles │ │ └── profiles_settings.xml │ ├── modules.xml │ └── Hangman.iml ├── images │ └── images │ │ ├── hangman0.png │ │ ├── hangman1.png │ │ ├── hangman2.png │ │ ├── hangman3.png │ │ ├── hangman4.png │ │ ├── hangman5.png │ │ └── hangman6.png └── main.py ├── .gitattributes ├── FractalTrees ├── .idea │ ├── .gitignore │ ├── misc.xml │ ├── inspectionProfiles │ │ └── profiles_settings.xml │ ├── modules.xml │ └── TicTacToe.iml ├── .vscode │ ├── settings.json │ └── launch.json ├── tree.py └── main.py ├── Life ├── main.py ├── .vscode │ └── settings.json ├── __pycache__ │ ├── board.cpython-38.pyc │ ├── life.cpython-38.pyc │ └── piece.cpython-38.pyc ├── piece.py ├── board.py └── life.py ├── Minesweeper ├── win.wav ├── .DS_Store ├── images │ ├── 0.png │ ├── 1.png │ ├── 2.png │ ├── 3.png │ ├── 4.png │ ├── 5.png │ ├── 6.png │ ├── 7.png │ ├── 8.png │ ├── flag.png │ ├── .DS_Store │ ├── empty-block.png │ ├── wrong-flag.png │ ├── unclicked-bomb.png │ └── bomb-at-clicked-block.png ├── .vscode │ ├── settings.json │ └── launch.json ├── __pycache__ │ ├── board.cpython-38.pyc │ ├── board.cpython-39.pyc │ ├── game.cpython-38.pyc │ ├── game.cpython-39.pyc │ ├── piece.cpython-38.pyc │ ├── piece.cpython-39.pyc │ ├── solver.cpython-38.pyc │ └── solver.cpython-39.pyc ├── main.py ├── piece.py ├── solver.py ├── board.py └── game.py ├── TicTacToe ├── main.py ├── .vscode │ ├── settings.json │ └── launch.json ├── __pycache__ │ ├── board.cpython-38.pyc │ ├── board.cpython-39.pyc │ ├── game.cpython-38.pyc │ └── solver.cpython-38.pyc ├── solver.py ├── board.py └── game.py ├── AStar ├── .vscode │ └── settings.json ├── __pycache__ │ └── piece.cpython-38.pyc ├── piece.py └── main.py ├── PiMonte ├── .vscode │ └── settings.json └── main.py ├── Snake ├── .vscode │ └── settings.json ├── __pycache__ │ ├── apple.cpython-38.pyc │ ├── block.cpython-38.pyc │ └── snake.cpython-38.pyc ├── block.py ├── snake.py └── game.py ├── Sudoku ├── .vscode │ └── settings.json ├── __pycache__ │ ├── board.cpython-38.pyc │ └── solver.cpython-38.pyc ├── main.py ├── expert.txt ├── sample.txt ├── board.py └── solver.py ├── Mandelbrot ├── .vscode │ └── settings.json ├── test.py ├── julia.py └── main.py └── PiCollisions ├── .vscode └── settings.json ├── no_visuals.py └── main.py /LSystemFractalTrees/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /LSystemFractalTrees/triangle.txt: -------------------------------------------------------------------------------- 1 | F+F+F 2 | 1 3 | F F-F+F 4 | 120 -------------------------------------------------------------------------------- /LSystemFractalTrees/dragon.txt: -------------------------------------------------------------------------------- 1 | FX 2 | 2 3 | X X+YF+ 4 | Y -FX-Y 5 | 90 -------------------------------------------------------------------------------- /LSystemFractalTrees/tree.txt: -------------------------------------------------------------------------------- 1 | F 2 | 1 3 | F FF+[+F-F-F]-[-F+F+F] 4 | 30 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Pygame 2 | Simple games created with the pygame module 3 | -------------------------------------------------------------------------------- /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/.DS_Store -------------------------------------------------------------------------------- /LSystemFractalTrees/plant.txt: -------------------------------------------------------------------------------- 1 | X 2 | 2 3 | X F+[[X]-X]-F[-FX]+X 4 | F FF 5 | 25 -------------------------------------------------------------------------------- /Hangman/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /LSystemFractalTrees/sierpinski.txt: -------------------------------------------------------------------------------- 1 | F-G-G 2 | 2 3 | F F-G+F+G-F 4 | G GG 5 | 120 -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /FractalTrees/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /Life/main.py: -------------------------------------------------------------------------------- 1 | from life import Life 2 | size = 20, 20 3 | life = Life(size) 4 | life.run() -------------------------------------------------------------------------------- /Minesweeper/win.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/win.wav -------------------------------------------------------------------------------- /Minesweeper/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/.DS_Store -------------------------------------------------------------------------------- /Minesweeper/images/0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/images/0.png -------------------------------------------------------------------------------- /Minesweeper/images/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/images/1.png -------------------------------------------------------------------------------- /Minesweeper/images/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/images/2.png -------------------------------------------------------------------------------- /Minesweeper/images/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/images/3.png -------------------------------------------------------------------------------- /Minesweeper/images/4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/images/4.png -------------------------------------------------------------------------------- /Minesweeper/images/5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/images/5.png -------------------------------------------------------------------------------- /Minesweeper/images/6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/images/6.png -------------------------------------------------------------------------------- /Minesweeper/images/7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/images/7.png -------------------------------------------------------------------------------- /Minesweeper/images/8.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/images/8.png -------------------------------------------------------------------------------- /TicTacToe/main.py: -------------------------------------------------------------------------------- 1 | from game import Game 2 | 3 | screenSize = 800, 800 4 | g = Game(screenSize) 5 | g.run() -------------------------------------------------------------------------------- /Minesweeper/images/flag.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/images/flag.png -------------------------------------------------------------------------------- /AStar/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "/Users/daniel/opt/anaconda3/envs/pygame/bin/python" 3 | } -------------------------------------------------------------------------------- /Life/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "/Users/daniel/opt/anaconda3/envs/pygame/bin/python" 3 | } -------------------------------------------------------------------------------- /Minesweeper/images/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/images/.DS_Store -------------------------------------------------------------------------------- /PiMonte/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "/Users/daniel/opt/anaconda3/envs/pygame/bin/python" 3 | } -------------------------------------------------------------------------------- /Snake/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "/Users/daniel/opt/anaconda3/envs/pygame/bin/python" 3 | } -------------------------------------------------------------------------------- /Sudoku/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "/Users/daniel/opt/anaconda3/envs/pygame/bin/python" 3 | } -------------------------------------------------------------------------------- /Mandelbrot/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "/Users/daniel/opt/anaconda3/envs/pygame/bin/python" 3 | } -------------------------------------------------------------------------------- /Minesweeper/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "/Users/daniel/opt/anaconda3/envs/pygame/bin/python" 3 | } -------------------------------------------------------------------------------- /PiCollisions/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "/Users/daniel/opt/anaconda3/envs/pygame/bin/python" 3 | } -------------------------------------------------------------------------------- /TicTacToe/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "/Users/daniel/opt/anaconda3/envs/pygame/bin/python" 3 | } -------------------------------------------------------------------------------- /Hangman/images/images/hangman0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Hangman/images/images/hangman0.png -------------------------------------------------------------------------------- /Hangman/images/images/hangman1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Hangman/images/images/hangman1.png -------------------------------------------------------------------------------- /Hangman/images/images/hangman2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Hangman/images/images/hangman2.png -------------------------------------------------------------------------------- /Hangman/images/images/hangman3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Hangman/images/images/hangman3.png -------------------------------------------------------------------------------- /Hangman/images/images/hangman4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Hangman/images/images/hangman4.png -------------------------------------------------------------------------------- /Hangman/images/images/hangman5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Hangman/images/images/hangman5.png -------------------------------------------------------------------------------- /Hangman/images/images/hangman6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Hangman/images/images/hangman6.png -------------------------------------------------------------------------------- /Minesweeper/images/empty-block.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/images/empty-block.png -------------------------------------------------------------------------------- /Minesweeper/images/wrong-flag.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/images/wrong-flag.png -------------------------------------------------------------------------------- /LSystemFractalTrees/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "/Users/daniel/opt/anaconda3/envs/pygame/bin/python" 3 | } -------------------------------------------------------------------------------- /Life/__pycache__/board.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Life/__pycache__/board.cpython-38.pyc -------------------------------------------------------------------------------- /Life/__pycache__/life.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Life/__pycache__/life.cpython-38.pyc -------------------------------------------------------------------------------- /Life/__pycache__/piece.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Life/__pycache__/piece.cpython-38.pyc -------------------------------------------------------------------------------- /Minesweeper/images/unclicked-bomb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/images/unclicked-bomb.png -------------------------------------------------------------------------------- /AStar/__pycache__/piece.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/AStar/__pycache__/piece.cpython-38.pyc -------------------------------------------------------------------------------- /Snake/__pycache__/apple.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Snake/__pycache__/apple.cpython-38.pyc -------------------------------------------------------------------------------- /Snake/__pycache__/block.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Snake/__pycache__/block.cpython-38.pyc -------------------------------------------------------------------------------- /Snake/__pycache__/snake.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Snake/__pycache__/snake.cpython-38.pyc -------------------------------------------------------------------------------- /Sudoku/__pycache__/board.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Sudoku/__pycache__/board.cpython-38.pyc -------------------------------------------------------------------------------- /Sudoku/__pycache__/solver.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Sudoku/__pycache__/solver.cpython-38.pyc -------------------------------------------------------------------------------- /TicTacToe/__pycache__/board.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/TicTacToe/__pycache__/board.cpython-38.pyc -------------------------------------------------------------------------------- /TicTacToe/__pycache__/board.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/TicTacToe/__pycache__/board.cpython-39.pyc -------------------------------------------------------------------------------- /TicTacToe/__pycache__/game.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/TicTacToe/__pycache__/game.cpython-38.pyc -------------------------------------------------------------------------------- /Minesweeper/__pycache__/board.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/__pycache__/board.cpython-38.pyc -------------------------------------------------------------------------------- /Minesweeper/__pycache__/board.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/__pycache__/board.cpython-39.pyc -------------------------------------------------------------------------------- /Minesweeper/__pycache__/game.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/__pycache__/game.cpython-38.pyc -------------------------------------------------------------------------------- /Minesweeper/__pycache__/game.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/__pycache__/game.cpython-39.pyc -------------------------------------------------------------------------------- /Minesweeper/__pycache__/piece.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/__pycache__/piece.cpython-38.pyc -------------------------------------------------------------------------------- /Minesweeper/__pycache__/piece.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/__pycache__/piece.cpython-39.pyc -------------------------------------------------------------------------------- /Minesweeper/__pycache__/solver.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/__pycache__/solver.cpython-38.pyc -------------------------------------------------------------------------------- /Minesweeper/__pycache__/solver.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/__pycache__/solver.cpython-39.pyc -------------------------------------------------------------------------------- /Minesweeper/images/bomb-at-clicked-block.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/Minesweeper/images/bomb-at-clicked-block.png -------------------------------------------------------------------------------- /TicTacToe/__pycache__/solver.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/TicTacToe/__pycache__/solver.cpython-38.pyc -------------------------------------------------------------------------------- /FractalTrees/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "C:\\Users\\Daniel\\AppData\\Local\\Programs\\Python\\Python38-32\\python.exe" 3 | } -------------------------------------------------------------------------------- /LSystemFractalTrees/__pycache__/main.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/LSystemFractalTrees/__pycache__/main.cpython-38.pyc -------------------------------------------------------------------------------- /Sudoku/main.py: -------------------------------------------------------------------------------- 1 | from solver import Solver 2 | from board import Board 3 | 4 | size = 9, 9 5 | board = Board(size) 6 | solver = Solver(board) 7 | solver.run() 8 | -------------------------------------------------------------------------------- /LSystemFractalTrees/__pycache__/LSystem.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danielchang2002/Pygame/HEAD/LSystemFractalTrees/__pycache__/LSystem.cpython-38.pyc -------------------------------------------------------------------------------- /FractalTrees/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | {"name":"Python: Current File","type":"python","request":"launch","program":"${file}","console":"internalConsole"} 4 | ] 5 | } -------------------------------------------------------------------------------- /Hangman/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /FractalTrees/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LSystemFractalTrees/Lsystems.txt: -------------------------------------------------------------------------------- 1 | Tree,F,30,150,250,500,F->FF+[+F-F-F]-[-F+F+F] 2 | Plant,X,30,200,250,500,X->F+[[X]-X]-F[-FX]+X F->FF 3 | Sierpinski,F-G-G,120,500,500,500,F->F-G+F+G-F G->GG 4 | Dragon,FX,90,500,250,250,X->X+YF+ Y->-FX-Y -------------------------------------------------------------------------------- /Hangman/.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /FractalTrees/.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /Snake/block.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | 3 | class Block: 4 | def __init__(self, x, y, color): 5 | self.x, self.y = x, y 6 | self.color = color 7 | 8 | def equals(self, other): 9 | return other.x == self.x and other.y == self.y -------------------------------------------------------------------------------- /Minesweeper/main.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from game import Game 3 | 4 | def main(): 5 | size = int(sys.argv[1]), int(sys.argv[2]) 6 | prob = float(sys.argv[3]) 7 | g = Game(size, prob) 8 | g.run() 9 | 10 | if __name__ == '__main__': 11 | main() -------------------------------------------------------------------------------- /Sudoku/expert.txt: -------------------------------------------------------------------------------- 1 | 0, 0, 9, 0, 0, 0, 0, 0, 1 2 | 0, 0, 1, 0, 4, 0, 9, 0, 0 3 | 0, 5, 6, 0, 0, 0, 0, 0, 0 4 | 4, 0, 0, 0, 1, 0, 0, 6, 0 5 | 9, 0, 0, 7, 0, 0, 3, 0, 0 6 | 0, 0, 0, 4, 5, 0, 0, 0, 7 7 | 0, 0, 0, 9, 0, 0, 6, 8, 0 8 | 0, 0, 0, 2, 0, 0, 0, 0, 4 9 | 7, 0, 0, 8, 0, 0, 0, 0, 0 -------------------------------------------------------------------------------- /Sudoku/sample.txt: -------------------------------------------------------------------------------- 1 | 0, 9, 3, 4, 2, 7, 5, 0, 0 2 | 0, 0, 7, 0, 1, 5, 3, 0, 0 3 | 0, 2, 4, 6, 8, 0, 0, 0, 7 4 | 3, 0, 0, 7, 6, 0, 2, 1, 9 5 | 6, 0, 0, 0, 0, 0, 0, 0, 0 6 | 0, 0, 0, 1, 3, 0, 0, 0, 0 7 | 4, 0, 5, 8, 0, 0, 9, 2, 6 8 | 0, 0, 1, 2, 0, 6, 0, 7, 3 9 | 0, 7, 0, 0, 0, 9, 8, 0, 0 -------------------------------------------------------------------------------- /Hangman/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /FractalTrees/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Hangman/.idea/Hangman.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Mandelbrot/test.py: -------------------------------------------------------------------------------- 1 | string = """ 2 | def mandelbrot(a, b, iters, bound):\noriginalA = a\n 3 | originalB = b\n 4 | for i in range(iters): 5 | aTemp = a**2 - b**2 + originalA 6 | b = 2 * a * b + originalB 7 | a = aTemp 8 | if (a**2 + b**2 >= bound): 9 | return i 10 | return iters 11 | """ 12 | 13 | import pyautogui 14 | 15 | pyautogui.write(string, interval=0.05) -------------------------------------------------------------------------------- /FractalTrees/.idea/TicTacToe.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /TicTacToe/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Python: Current File", 9 | "type": "python", 10 | "request": "launch", 11 | "program": "${file}", 12 | "console": "internalConsole" 13 | } 14 | ] 15 | } -------------------------------------------------------------------------------- /PiMonte/main.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import random 3 | 4 | pygame.init() 5 | WIDTH, HEIGHT = 500, 500 6 | screen = pygame.display.set_mode((WIDTH, HEIGHT)) 7 | 8 | class Monte: 9 | def __init__(self): 10 | self.numIn = 0 11 | self.total = 0 12 | 13 | def getPoint(self): 14 | pass 15 | 16 | running = True 17 | while running: 18 | for event in pygame.event.get(): 19 | if event.type == pygame.QUIT: 20 | running = False 21 | screen.fill((0, 0, 0)) 22 | pygame.display.flip() 23 | 24 | pygame.quit() -------------------------------------------------------------------------------- /Minesweeper/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Python: Current File", 9 | "type": "python", 10 | "request": "launch", 11 | "program": "${file}", 12 | "console": "internalConsole", 13 | "args": ["10", "10", "0.07"] 14 | } 15 | ] 16 | } -------------------------------------------------------------------------------- /LSystemFractalTrees/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Python: Current File", 9 | "type": "python", 10 | "request": "launch", 11 | "program": "${file}", 12 | "console": "internalConsole", 13 | "args": ["dragon.txt", "500", "500", "250", "250", "150"] 14 | 15 | } 16 | ] 17 | } -------------------------------------------------------------------------------- /Life/piece.py: -------------------------------------------------------------------------------- 1 | class Piece(): 2 | def __init__(self, alive): 3 | self.alive = alive 4 | 5 | def getAlive(self): 6 | return self.alive 7 | 8 | def setNeighbors(self, neighbors): 9 | self.neighbors = neighbors 10 | 11 | def getNeighbors(self): 12 | return self.neighbors 13 | 14 | def setAlive(self, alive): 15 | self.alive = alive 16 | 17 | def getNumAroundAlive(self): 18 | alive = 0 19 | for neighbor in self.neighbors: 20 | if neighbor.getAlive(): 21 | alive += 1 22 | return alive 23 | 24 | def toggle(self): 25 | self.alive = not self.alive -------------------------------------------------------------------------------- /AStar/piece.py: -------------------------------------------------------------------------------- 1 | from math import inf 2 | 3 | class Piece: 4 | def __init__(self, row, col): 5 | self.row, self.col = row, col 6 | self.isStart = False 7 | self.isWall = False 8 | self.isEnd = False 9 | self.visited = False 10 | self.popped = False 11 | self.parent = None 12 | self.path = False 13 | self.g = inf 14 | self.h = inf 15 | self.timePopped = -1 16 | 17 | def setNeighbors(self, neighbors): 18 | self.neighbors = neighbors 19 | 20 | def f(self): 21 | return self.g + self.h 22 | 23 | def __lt__(self, other): 24 | return self.f() < other.f() 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /Snake/snake.py: -------------------------------------------------------------------------------- 1 | from block import Block 2 | 3 | class Snake: 4 | def __init__(self, x, y, color): 5 | self.color = color 6 | self.blocks = [Block(x - 2, y, color), Block(x - 1, y, color), Block(x, y, color)] 7 | self.head = self.blocks[-1] 8 | self.v_x, self.v_y = 1, 0 9 | self.alive = True 10 | 11 | def step(self, apple): 12 | self.blocks.append(Block(self.blocks[-1].x + self.v_x, self.blocks[-1].y + self.v_y, self.color)) 13 | if not apple: 14 | self.blocks = self.blocks[1:] 15 | self.head = self.blocks[-1] 16 | 17 | def checkCollisions(self, numRows, numCols): 18 | if self.head.x >= numCols or self.head.y >= numRows \ 19 | or self.head.x < 0 or self.head.y < 0: 20 | self.alive = False 21 | return 22 | for block in self.blocks[:-1]: 23 | if block.equals(self.head): 24 | self.alive = False 25 | return 26 | 27 | 28 | -------------------------------------------------------------------------------- /FractalTrees/tree.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import math 3 | 4 | pygame.init() 5 | 6 | WIDTH = 600 7 | HEIGHT = 500 8 | r = 0.67 9 | deltaTheta = math.pi / 6 10 | 11 | 12 | screen = pygame.display.set_mode([WIDTH, HEIGHT]) 13 | 14 | 15 | def line(screen, x, y, length, theta): 16 | if (length <= 1): 17 | return 18 | x2 = x - length * math.cos(theta) 19 | y2 = y - length * math.sin(theta) 20 | pygame.draw.line(screen, (length, 255 / length, 0), (x, y), (x2, y2)) 21 | line(screen, x2, y2, length * r, theta + deltaTheta) 22 | line(screen, x2, y2, length * r, theta - deltaTheta) 23 | 24 | 25 | running = True 26 | while running: 27 | for event in pygame.event.get(): 28 | if event.type == pygame.QUIT: 29 | running = False 30 | screen.fill((255, 255, 255)) 31 | line(screen, WIDTH / 2, HEIGHT, 150, math.pi / 2) 32 | 33 | x, y = pygame.mouse.get_pos() 34 | 35 | r = (y / 500) * 0.7 36 | deltaTheta = (x / 250) * math.pi 37 | 38 | pygame.display.flip() 39 | 40 | pygame.quit() 41 | -------------------------------------------------------------------------------- /FractalTrees/main.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import sys 3 | import random 4 | import math 5 | 6 | dtheta = math.pi / 4 7 | ratio = 0.7 8 | 9 | 10 | def line(screen, x, y, len, theta): 11 | if (len >= 1): 12 | x2 = int(x - len * math.cos(theta)) 13 | y2 = int(y - len * math.sin(theta)) 14 | pygame.draw.line(screen, (len, 255 / len, 0), (x, y), (x2, y2)) 15 | line(screen, x2, y2, len * ratio, theta - dtheta) 16 | line(screen, x2, y2, len * ratio, theta + dtheta) 17 | 18 | 19 | pygame.init() 20 | 21 | WIDTH = 500 22 | HEIGHT = 500 23 | 24 | screen = pygame.display.set_mode([WIDTH, HEIGHT]) 25 | 26 | running = True 27 | while running: 28 | 29 | for event in pygame.event.get(): 30 | if event.type == pygame.QUIT: 31 | running = False 32 | screen.fill((255, 255, 255)) 33 | 34 | line(screen, WIDTH / 2, HEIGHT, 150, math.pi / 2) 35 | pygame.display.flip() 36 | x, y = pygame.mouse.get_pos() 37 | dtheta = (x / 250) * math.pi 38 | ratio = (y / 500) * 0.7 39 | 40 | 41 | pygame.quit() 42 | -------------------------------------------------------------------------------- /Minesweeper/piece.py: -------------------------------------------------------------------------------- 1 | class Piece: 2 | # States: Not clicked, clicked, flagged 3 | def __init__(self, hasBomb): 4 | self.hasBomb = hasBomb 5 | self.around = 0 6 | self.clicked = False 7 | self.flagged = False 8 | self.neighbors = [] 9 | 10 | def __str__(self): 11 | return str(self.hasBomb) 12 | 13 | def getNumAround(self): 14 | return self.around 15 | 16 | def getHasBomb(self): 17 | return self.hasBomb 18 | 19 | def getClicked(self): 20 | return self.clicked 21 | 22 | def getFlagged(self): 23 | return self.flagged 24 | 25 | def toggleFlag(self): 26 | self.flagged = not self.flagged 27 | 28 | def handleClick(self): 29 | self.clicked = True 30 | 31 | def setNumAround(self): 32 | num = 0 33 | for neighbor in self.neighbors: 34 | if neighbor.getHasBomb(): 35 | num += 1 36 | self.around = num 37 | 38 | def setNeighbors(self, neighbors): 39 | self.neighbors = neighbors 40 | 41 | def getNeighbors(self): 42 | return self.neighbors 43 | -------------------------------------------------------------------------------- /Minesweeper/solver.py: -------------------------------------------------------------------------------- 1 | import pyautogui 2 | 3 | class Solver: 4 | def __init__(self, board): 5 | self.board = board 6 | 7 | def move(self): 8 | for row in self.board.getBoard(): 9 | for piece in row: 10 | if not piece.getClicked(): 11 | continue 12 | around = piece.getNumAround() 13 | unknown = 0 14 | flagged = 0 15 | neighbors = piece.getNeighbors() 16 | for p in neighbors: 17 | if not p.getClicked(): 18 | unknown += 1 19 | if p.getFlagged(): 20 | flagged += 1 21 | if around == flagged: 22 | self.openUnflagged(neighbors) 23 | if around == unknown: 24 | self.flagAll(neighbors) 25 | 26 | def openUnflagged(self, neighbors): 27 | for piece in neighbors: 28 | if not piece.getFlagged(): 29 | self.board.handleClick(piece, False) 30 | 31 | 32 | def flagAll(self, neighbors): 33 | for piece in neighbors: 34 | if not piece.getFlagged(): 35 | self.board.handleClick(piece, True) -------------------------------------------------------------------------------- /TicTacToe/solver.py: -------------------------------------------------------------------------------- 1 | from math import inf 2 | 3 | class Solver(): 4 | def getBestMove(self, board, maximizer): 5 | maxScore = -1 * inf 6 | bestBoard = None 7 | self.maximizer = maximizer 8 | self.minimizer = 'X' if maximizer == 'O' else 'O' 9 | for b in board.getNeighbors(maximizer): 10 | score = self.getScore(b, False, 0) 11 | if (score > maxScore): 12 | maxScore = score 13 | bestBoard = b 14 | return bestBoard 15 | 16 | def getScore(self, board, isMaximizer, move): 17 | if (board.getHasWon(self.maximizer)): 18 | return 10 - move 19 | elif (board.getHasWon(self.minimizer)): 20 | return -10 + move 21 | elif (board.isFull()): 22 | return 0 23 | 24 | if (isMaximizer): 25 | bestScore = -1 * inf 26 | for b in board.getNeighbors(self.maximizer): 27 | score = self.getScore(b, False, move + 1) 28 | bestScore = max(bestScore, score) 29 | return bestScore 30 | else: 31 | bestScore = inf 32 | for b in board.getNeighbors(self.minimizer): 33 | score = self.getScore(b, True, move + 1) 34 | bestScore = min(bestScore, score) 35 | return bestScore 36 | 37 | -------------------------------------------------------------------------------- /LSystemFractalTrees/main.py: -------------------------------------------------------------------------------- 1 | import re 2 | from LSystem import LSystem 3 | import math 4 | import pygame 5 | 6 | systems = [] 7 | 8 | with open('Lsystems.txt') as text: 9 | for line in text: 10 | stringList = re.split(',|\n', line) 11 | axiom = stringList[1] 12 | angle = math.radians(int(stringList[2])) 13 | length = int(stringList[3]) 14 | x, y = int(stringList[4]), int(stringList[5]) 15 | rulesList = stringList[6].split() 16 | rules = [] 17 | for rule in rulesList: 18 | rules.append({ 19 | 'in': rule.split('->')[0], 20 | 'out': rule.split('->')[1] 21 | }) 22 | systems.append(LSystem(axiom, rules, x, y, length, angle)) 23 | 24 | 25 | curr = systems[4] 26 | 27 | pygame.init() 28 | screen = pygame.display.set_mode([500, 500]) 29 | 30 | 31 | first = True 32 | running = True 33 | while running: 34 | for event in pygame.event.get(): 35 | if event.type == pygame.QUIT: 36 | running = False 37 | if event.type == pygame.MOUSEBUTTONDOWN: 38 | screen.fill((255, 255, 255)) 39 | curr.draw(screen) 40 | curr.printSent() 41 | curr.generate() 42 | 43 | if (first): 44 | screen.fill((255, 255, 255)) 45 | first = False 46 | 47 | pygame.display.flip() 48 | 49 | pygame.quit() 50 | -------------------------------------------------------------------------------- /Mandelbrot/julia.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import numpy as np 3 | from math import sqrt 4 | 5 | def mandelbrot(a, b, iters, bound, ca, cb): 6 | """ 7 | Runs iters iterations of the mandelbrot function, f(z) = z^2 + c, 8 | where c = a + bi. Returns number of iterations that a**2 + b**2 < bound 9 | """ 10 | # a^2 - b^2 + 2abi + a + bi 11 | for i in range(iters): 12 | aTemp = a**2 - b**2 + ca 13 | b = 2 * a * b + cb 14 | a = aTemp 15 | if (a**2 + b**2 >= bound): 16 | return i 17 | return iters 18 | 19 | width, height = 800, 500 20 | minX, maxX, minY, maxY = -1.5, 1.5, -1, 1 21 | 22 | def getGrid(ca, cb): 23 | mandelbrotGrid = np.zeros((width, height, 3)) 24 | maxIters = 50 25 | for x in range(width): 26 | for y in range(height): 27 | a = minX + (x / width) * (maxX - minX) 28 | b = minY + (y / height) * (maxY - minY) 29 | n = mandelbrot(a, b, maxIters, 4, ca, cb) 30 | color = 0 31 | if n != maxIters: 32 | c = sqrt(n / maxIters) * 360 33 | color = pygame.Color(0, 0, 0) 34 | color.hsva = c, 100, 100, 100 35 | mandelbrotGrid[x, y] = color.r, color.g, color.b 36 | else: 37 | mandelbrotGrid[x, y] = 0 38 | return mandelbrotGrid 39 | 40 | # = −0.8 + 0.156i 41 | grid = getGrid(-0.8, 0.156) 42 | pygame.init() 43 | screen = pygame.display.set_mode((width, height)) 44 | running = True 45 | while running: 46 | for event in pygame.event.get(): 47 | if event.type == pygame.QUIT: 48 | running = False 49 | pygame.surfarray.blit_array(screen, grid) 50 | pygame.display.flip() 51 | pygame.quit() 52 | -------------------------------------------------------------------------------- /Mandelbrot/main.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import numpy as np 3 | from math import sqrt 4 | 5 | def mandelbrot(a, b, iters, bound): 6 | originalA = a 7 | originalB = b 8 | for i in range(iters): 9 | aTemp = a**2 - b**2 + originalA 10 | b = 2 * a * b + originalB 11 | a = aTemp 12 | if (a**2 + b**2 >= bound): 13 | return i 14 | return iters 15 | 16 | width, height = 500, 300 17 | 18 | minX, maxX, minY, maxY = -2.5, 1, -1, 1 19 | 20 | def getColor(n, maxIters): 21 | c = sqrt(n / maxIters) * 360 22 | color = pygame.Color(0, 0, 0) 23 | color.hsva = c, 100, 100, 100 24 | return color.r, color.g, color.b 25 | 26 | def getGrid(): 27 | mandelbrotGrid = np.zeros((width, height, 3)) 28 | maxIters = 50 29 | for x in range(width): 30 | for y in range(height): 31 | a = minX + (x / width) * (maxX - minX) 32 | b = minY + (y / height) * (maxY - minY) 33 | n = mandelbrot(a, b, maxIters, 4) 34 | mandelbrotGrid[x, y] = 0 if n == maxIters else getColor(n, maxIters) 35 | return mandelbrotGrid 36 | 37 | grid = getGrid() 38 | 39 | pygame.init() 40 | screen = pygame.display.set_mode((width, height)) 41 | running = True 42 | while running: 43 | for event in pygame.event.get(): 44 | if event.type == pygame.QUIT: 45 | running = False 46 | if event.type == pygame.MOUSEBUTTONDOWN: 47 | x, y = pygame.mouse.get_pos() 48 | x = minX + (maxX - minX) * (x / width) 49 | y = minY + (maxY - minY) * (y / height) 50 | minX = minX + (x - minX) * 0.8 51 | maxX = maxX - (maxX - x) * 0.8 52 | minY = minY + (y - minY) * 0.8 53 | maxY = maxY - (maxY - y) * 0.8 54 | grid = getGrid() 55 | break 56 | pygame.surfarray.blit_array(screen, grid) 57 | pygame.display.flip() 58 | pygame.quit() 59 | -------------------------------------------------------------------------------- /TicTacToe/board.py: -------------------------------------------------------------------------------- 1 | from copy import deepcopy 2 | 3 | class Board(): 4 | def __init__(self, board): 5 | if (not board): 6 | self.board = [] 7 | for i in range(3): 8 | row = [] 9 | for j in range(3): 10 | row.append('-') 11 | self.board.append(row) 12 | else: 13 | self.board = board 14 | 15 | def getPiece(self, index): 16 | return self.board[index[0]][index[1]] 17 | 18 | def getMovedBoard(self, index, player): 19 | newBoard = self.board 20 | newBoard[index[0]][index[1]] = player 21 | return Board(newBoard) 22 | 23 | def getHasWon(self, player): 24 | for row in range(3): 25 | won = True 26 | for col in range(0, 3): 27 | if (self.getPiece((row, col)) != player): 28 | won = False 29 | break 30 | if (won): 31 | return ((row, 0), (row, 1), (row, 2)) 32 | for col in range(3): 33 | won = True 34 | for row in range(0, 3): 35 | if (self.getPiece((row, col)) != player): 36 | won = False 37 | break 38 | if (won): 39 | return ((0, col), (1, col), (2, col)) 40 | if (self.getPiece((0, 0)) == player and self.getPiece((1, 1)) == player and self.getPiece((2, 2)) == player): 41 | return ((0, 0), (1, 1), (2, 2)) 42 | elif (self.getPiece((0, 2)) == player and self.getPiece((1, 1)) == player and self.getPiece((2, 0)) == player): 43 | return ((0, 2), (1, 1), (2, 0)) 44 | 45 | def isFull(self): 46 | num = 0 47 | for i in range(3): 48 | for j in range(3): 49 | if (self.board[i][j] != '-'): 50 | num += 1 51 | return num == 9 52 | 53 | def getNeighbors(self, player): 54 | neighbors = [] 55 | for i in range(3): 56 | for j in range(3): 57 | if self.getPiece((i, j)) == '-': 58 | board = deepcopy(self.board) 59 | board[i][j] = player 60 | neighbors.append(Board(board)) 61 | return neighbors 62 | -------------------------------------------------------------------------------- /LSystemFractalTrees/LSystem.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import math 3 | import random 4 | import time 5 | 6 | class LSystem: 7 | def __init__(self, axiom, rules, x, y, length, dtheta): 8 | self.axiom = axiom 9 | self.sentence = axiom 10 | self.rules = rules 11 | self.xInit = x 12 | self.yInit = y 13 | self.x = x 14 | self.y = y 15 | self.theta = math.pi / 2 16 | self.length = length 17 | self.dtheta = dtheta 18 | self.stack = [] 19 | 20 | def generate(self): 21 | self.x = self.xInit 22 | self.y = self.yInit 23 | self.theta = math.pi / 2 24 | self.length *= 0.75 25 | newSent = '' 26 | for char in self.sentence: 27 | match = False 28 | for rule in self.rules: 29 | if (rule['in'] == char): 30 | newSent += rule['out'] 31 | match = True 32 | break 33 | if (not match): 34 | newSent += char 35 | self.sentence = newSent 36 | 37 | def printSent(self): 38 | print(self.sentence) 39 | 40 | def draw(self, screen): 41 | color = 0 42 | dcolor = 255 / len(self.sentence) 43 | for char in self.sentence: 44 | # print(char) 45 | if (char == 'F' or char == 'G' or char == 'A' or char == 'B'): 46 | x2 = self.x - self.length * math.cos(self.theta) 47 | y2 = self.y - self.length * math.sin(self.theta) 48 | pygame.draw.line(screen, (color, 255 - color, 100 + color / 255, 100), 49 | (self.x, self.y), (x2, y2)) 50 | self.x = x2 51 | self.y = y2 52 | elif (char == '+'): 53 | self.theta += self.dtheta 54 | elif (char == '-'): 55 | self.theta -= self.dtheta 56 | elif (char == '['): 57 | self.stack.append( 58 | {'x': self.x, 'y': self.y, 'theta': self.theta}) 59 | elif (char == ']'): 60 | dict = self.stack.pop() 61 | self.x = dict['x'] 62 | self.y = dict['y'] 63 | self.theta = dict['theta'] 64 | color += dcolor 65 | -------------------------------------------------------------------------------- /Life/board.py: -------------------------------------------------------------------------------- 1 | from piece import Piece 2 | from random import random 3 | class Board(): 4 | def __init__(self, size): 5 | self.size = size 6 | self.setBoard() 7 | 8 | def setBoard(self): 9 | self.addToBoard() 10 | self.setNeighbors() 11 | 12 | def addToBoard(self): 13 | self.board = [] 14 | for row in range(self.size[0]): 15 | row = [] 16 | for col in range(self.size[1]): 17 | alive = random() < 0 18 | piece = Piece(alive) 19 | row.append(piece) 20 | self.board.append(row) 21 | 22 | def setNeighbors(self): 23 | for row in range(self.size[0]): 24 | for col in range(self.size[1]): 25 | neighbors = self.getNeighborsList(row, col) 26 | self.board[row][col].setNeighbors(neighbors) 27 | 28 | def getNeighborsList(self, row, col): 29 | neighbors = [] 30 | for r in range(row - 1, row + 2): 31 | for c in range(col - 1, col + 2): 32 | if (c < 0 or c >= self.size[1] or r < 0 or r >= self.size[0]): 33 | continue 34 | if (r == row and c == col): 35 | continue 36 | neighbors.append(self.board[r][c]) 37 | return neighbors 38 | 39 | def getBoard(self): 40 | return self.board 41 | 42 | def update(self): 43 | nextValues = [] 44 | for row in range(self.size[0]): 45 | r = [] 46 | for col in range(self.size[1]): 47 | piece = self.board[row][col] 48 | alive = False 49 | numAlive = piece.getNumAroundAlive() 50 | if piece.getAlive(): 51 | alive = numAlive == 2 or numAlive == 3 52 | else: 53 | alive = numAlive == 3 54 | r.append(alive) 55 | nextValues.append(r) 56 | self.setValues(nextValues) 57 | 58 | def setValues(self, nextValues): 59 | for row in range(self.size[0]): 60 | for col in range(self.size[1]): 61 | self.board[row][col].setAlive(nextValues[row][col]) 62 | 63 | def handleClick(self, position): 64 | self.board[position[0]][position[1]].toggle() -------------------------------------------------------------------------------- /PiCollisions/no_visuals.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | 3 | 4 | class Block(): 5 | def __init__(self, length, mass, velocity, left): 6 | self.length = length 7 | self.mass = mass 8 | self.velocity = velocity 9 | self.left = left 10 | self.right = left + length 11 | 12 | def update(self, dt): 13 | self.left += self.velocity * dt 14 | self.right = self.left + self.length 15 | 16 | def switchDir(self): 17 | self.velocity = -1 * self.velocity 18 | 19 | @staticmethod 20 | def collision(block1, block2): 21 | m1, v10, m2, v20 = block1.mass, block1.velocity, block2.mass, block2.velocity 22 | block1.velocity = (m1*v10+m2*v20-m2*v10+m2*v20)/(m1+m2) 23 | block2.velocity = (m1*v10+m2*v20-m1*v20+m1*v10)/(m1+m2) 24 | 25 | class Sim(): 26 | def __init__(self, digits): 27 | self.dim = 1400, 800 28 | self.left = 10 29 | self.bot = self.dim[1] - 10 30 | self.collisions = 0 31 | self.block1 = Block(50, 1, 0, self.dim[0]*(1/3)) 32 | self.block2 = Block(100, 100 ** (digits - 1), -30, self.dim[0]*(2/3)) 33 | 34 | def run(self): 35 | dt = 0.01 36 | running = True 37 | while running: 38 | self.advance(dt) 39 | self.handleCollisions() 40 | if (self.block1.velocity > 0 and self.block2.velocity > 0 and self.block1.velocity < self.block2.velocity): 41 | break 42 | print(self.collisions) 43 | 44 | def advance(self, dt): 45 | self.block1.update(dt) 46 | self.block2.update(dt) 47 | 48 | def handleCollisions(self): 49 | collision = False 50 | if self.block1.left < self.left: 51 | distError = self.block1.left - self.left 52 | timeError = distError / self.block1.velocity 53 | self.advance(-timeError) 54 | self.block1.switchDir() 55 | collision = True 56 | elif self.block1.right > self.block2.left: 57 | timeError = (self.block1.right-self.block2.left)/(self.block1.velocity-self.block2.velocity) 58 | self.advance(-timeError) 59 | Block.collision(self.block1, self.block2) 60 | collision = True 61 | if collision: 62 | self.collisions += 1 63 | 64 | sim = Sim(3) 65 | sim.run() 66 | -------------------------------------------------------------------------------- /Minesweeper/board.py: -------------------------------------------------------------------------------- 1 | import random 2 | from piece import Piece 3 | class Board: 4 | def __init__(self, size, prob): 5 | self.size = size 6 | self.board = [] 7 | self.won = False 8 | self.lost = False 9 | for row in range(size[0]): 10 | row = [] 11 | for col in range(size[1]): 12 | bomb = random.random() < prob 13 | piece = Piece(bomb) 14 | row.append(piece) 15 | self.board.append(row) 16 | self.setNeighbors() 17 | self.setNumAround() 18 | 19 | def print(self): 20 | for row in self.board: 21 | for piece in row: 22 | print(piece, end=" ") 23 | print() 24 | 25 | def getBoard(self): 26 | return self.board 27 | 28 | def getSize(self): 29 | return self.size 30 | 31 | def getPiece(self, index): 32 | return self.board[index[0]][index[1]] 33 | 34 | def handleClick(self, piece, flag): 35 | if piece.getClicked() or (piece.getFlagged() and not flag): 36 | return 37 | if flag: 38 | piece.toggleFlag() 39 | return 40 | piece.handleClick() 41 | if piece.getNumAround() == 0: 42 | for neighbor in piece.getNeighbors(): 43 | self.handleClick(neighbor, False) 44 | if piece.getHasBomb(): 45 | self.lost = True 46 | else: 47 | self.won = self.checkWon() 48 | 49 | def checkWon(self): 50 | for row in self.board: 51 | for piece in row: 52 | if not piece.getHasBomb() and not piece.getClicked(): 53 | return False 54 | return True 55 | 56 | def getWon(self): 57 | return self.won 58 | 59 | def getLost(self): 60 | return self.lost 61 | 62 | def setNeighbors(self): 63 | for row in range(len(self.board)): 64 | for col in range(len(self.board[0])): 65 | piece = self.board[row][col] 66 | neighbors = [] 67 | self.addToNeighborsList(neighbors, row, col) 68 | piece.setNeighbors(neighbors) 69 | 70 | def addToNeighborsList(self, neighbors, row, col): 71 | for r in range(row - 1, row + 2): 72 | for c in range(col - 1, col + 2): 73 | if r == row and c == col: 74 | continue 75 | if r < 0 or r >= self.size[0] or c < 0 or c >= self.size[1]: 76 | continue 77 | neighbors.append(self.board[r][c]) 78 | 79 | def setNumAround(self): 80 | for row in self.board: 81 | for piece in row: 82 | piece.setNumAround() 83 | 84 | -------------------------------------------------------------------------------- /Life/life.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import math 3 | from board import Board 4 | BLACK = (0, 0, 0) 5 | GREY = (128, 128, 128) 6 | WHITE = (255, 255, 255) 7 | color = {} 8 | color[0] = 15, 163, 177 9 | color[1] = 181, 226, 250 10 | color[2] = 249, 247, 243 11 | color[3] = 237, 222, 164 12 | color[4] = 247, 160, 114 13 | color[5] = 247, 160, 114 14 | color[6] = 242, 27, 63 15 | color[7] = 70, 39, 73 16 | color[8] = 51, 15, 10 17 | class Life(): 18 | def __init__(self, size): 19 | self.screenSize = 800, 800 20 | self.board = Board(size) 21 | self.pieceSize = self.screenSize[0] / size[1], self.screenSize[1] / size[0] 22 | 23 | 24 | def run(self): 25 | pygame.init() 26 | self.screen = pygame.display.set_mode(self.screenSize) 27 | running = True 28 | pygame.time.set_timer(pygame.USEREVENT, 200) 29 | started = False 30 | while running: 31 | for event in pygame.event.get(): 32 | if (event.type == pygame.QUIT): 33 | running = False 34 | if (event.type == pygame.KEYDOWN): 35 | started = True 36 | if (event.type == pygame.USEREVENT and started): 37 | self.board.update() 38 | if (event.type == pygame.MOUSEBUTTONDOWN): 39 | position = pygame.mouse.get_pos() 40 | self.handleClick(position) 41 | self.drawBoard() 42 | pygame.display.flip() 43 | pygame.quit() 44 | 45 | def drawBoard(self): 46 | self.screen.fill(BLACK) 47 | topLeft = (0, 0) 48 | b = self.board.getBoard() 49 | for row in b: 50 | for piece in row: 51 | rect = pygame.Rect(topLeft, self.pieceSize) 52 | pygame.draw.rect(self.screen, GREY, rect, width = 5) 53 | if piece.getAlive(): 54 | innerRect = pygame.Rect(topLeft[0] + 5, topLeft[1] + 5, self.pieceSize[0] - 10, self.pieceSize[1] - 10) 55 | color = self.getColor(piece.getNumAroundAlive()) 56 | pygame.draw.rect(self.screen, color, innerRect) 57 | topLeft = topLeft[0] + self.pieceSize[0], topLeft[1] 58 | topLeft = 0, topLeft[1] + self.pieceSize[1] 59 | 60 | def handleClick(self, position): 61 | index = int(position[1] // self.pieceSize[1]), int(position[0] // self.pieceSize[0]) 62 | self.board.handleClick(index) 63 | 64 | def getColor(self, numAlive): 65 | # return (255, abs(255 - numAlive * (255 / 4)), abs(255 - numAlive * (255 / 4))) 66 | return rgb(0, 8, numAlive) 67 | 68 | def rgb(minimum, maximum, value): 69 | minimum, maximum = float(minimum), float(maximum) 70 | ratio = 2 * (value-minimum) / (maximum - minimum) 71 | b = int(max(0, 255*(1 - ratio))) 72 | r = int(max(0, 255*(ratio - 1))) 73 | g = 255 - b - r 74 | return r, g, b -------------------------------------------------------------------------------- /Sudoku/board.py: -------------------------------------------------------------------------------- 1 | import csv 2 | class Board(): 3 | def __init__(self, size, board=None): 4 | self.size = size 5 | self.rows, self.cols = self.size 6 | self.setBoard() 7 | if board: 8 | with open(board) as f: 9 | reader = csv.reader(f, delimiter=',') 10 | r = 0 11 | for row in reader: 12 | c = 0 13 | for square in row: 14 | self.setSquare((r, c), int(square)) 15 | c += 1 16 | r += 1 17 | 18 | def setBoard(self): 19 | self.board = [] 20 | for row in range(self.size[0]): 21 | row = [] 22 | for col in range(self.size[1]): 23 | row.append(None) 24 | self.board.append(row); 25 | 26 | def getSize(self): 27 | return self.size 28 | 29 | def getSquare(self, index): 30 | return self.board[index[0]][index[1]] 31 | 32 | def setSquare(self, index, number): 33 | self.board[index[0]][index[1]] = number if number != 0 else None 34 | 35 | def solve(self): 36 | """ 37 | Solves self in place 38 | """ 39 | emptyIndex = self.getEmptyIndex() 40 | if not emptyIndex: 41 | return True 42 | for i in range(1, 10): 43 | if not self.isValidMove(emptyIndex, i): 44 | continue 45 | self.setSquare(emptyIndex, i) 46 | if self.solve(): 47 | return True 48 | self.setSquare(emptyIndex, None) 49 | return False 50 | 51 | 52 | def isValidMove(self, index, number): 53 | row, col = index 54 | return not self.isInRow(row, number) and not self.isInCol(col, number) and not self.isInBox(index, number) 55 | 56 | def isInRow(self, row, number): 57 | for square in self.board[row]: 58 | if square == number: 59 | return True 60 | return False 61 | 62 | def isInCol(self, col, number): 63 | for row in self.board: 64 | square = row[col] 65 | if square == number: 66 | return True 67 | return False 68 | 69 | def isInBox(self, index, number): 70 | row, col = index 71 | while row % 3 != 0: 72 | row -= 1 73 | while col % 3 != 0: 74 | col -= 1 75 | for r in range(row, row + 3): 76 | for c in range(col, col + 3): 77 | square = self.board[r][c] 78 | if square == number: 79 | return True 80 | return False 81 | 82 | def getEmptyIndex(self): 83 | """Returns index of None, returns None if no None on board""" 84 | for row in range(self.rows): 85 | for col in range(self.cols): 86 | square = self.board[row][col] 87 | if not square: 88 | return row, col 89 | return None 90 | -------------------------------------------------------------------------------- /Snake/game.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from snake import Snake 3 | from block import Block 4 | from random import random 5 | 6 | RED = 255, 0, 0 7 | WHITE = 255, 255, 255 8 | BLACK = 0, 0, 0 9 | 10 | class Game(): 11 | def __init__(self, rows, cols): 12 | self.screenWidth, self.screenHeight = 800, 800 13 | self.numRows, self.numCols = rows, cols 14 | self.blockWidth, self.blockHeight = self.screenWidth / self.numRows, self.screenHeight / self.numRows 15 | self.snake = Snake(self.numRows // 2, self.numCols // 2, WHITE) 16 | self.apple = Block(self.numRows // 4, self.numCols // 4, RED) 17 | self.interval = 350 18 | 19 | def run(self): 20 | pygame.init() 21 | self.STEP = pygame.USEREVENT + 1 22 | pygame.time.set_timer(self.STEP, self.interval) 23 | self.screen = pygame.display.set_mode((self.screenWidth, self.screenHeight)) 24 | running = True 25 | while running: 26 | for event in pygame.event.get(): 27 | if (event.type == pygame.QUIT): 28 | running = False 29 | elif (event.type == pygame.KEYDOWN): 30 | if event.key == pygame.K_w: 31 | self.snake.v_y = -1 32 | self.snake.v_x = 0 33 | elif event.key == pygame.K_a: 34 | self.snake.v_y = 0 35 | self.snake.v_x = -1 36 | elif event.key == pygame.K_s: 37 | self.snake.v_y = 1 38 | self.snake.v_x = 0 39 | elif event.key == pygame.K_d: 40 | self.snake.v_y = 0 41 | self.snake.v_x = 1 42 | elif (event.type == self.STEP and self.snake.alive): 43 | self.snake.step(False) 44 | self.snake.checkCollisions(self.numRows, self.numCols) 45 | self.screen.fill(BLACK) 46 | self.checkApple() 47 | self.drawSnake() 48 | self.drawApple() 49 | pygame.display.flip() 50 | pygame.quit() 51 | 52 | def drawSnake(self): 53 | for block in self.snake.blocks: 54 | rect = pygame.Rect(self.getLeftTop(block.x, block.y), (self.blockWidth, self.blockHeight)) 55 | pygame.draw.rect(self.screen, block.color, rect) 56 | 57 | def drawApple(self): 58 | rect = pygame.Rect(self.getLeftTop(self.apple.x, self.apple.y), (self.blockWidth, self.blockHeight)) 59 | pygame.draw.rect(self.screen, self.apple.color, rect) 60 | 61 | def getLeftTop(self, x, y): 62 | return (x / self.numRows) * self.screenWidth, (y / self.numRows) * self.screenHeight 63 | 64 | def checkApple(self): 65 | if self.snake.head.equals(self.apple): 66 | self.snake.step(True) 67 | self.apple = Block((int) (random() * self.numCols), (int) (random() * self.numRows), RED) 68 | self.interval *= 0.9 69 | pygame.time.set_timer(self.STEP, (int) (self.interval)) 70 | 71 | 72 | 73 | if __name__ == '__main__': 74 | g = Game(20, 20) 75 | g.run() -------------------------------------------------------------------------------- /Minesweeper/game.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from piece import Piece 3 | from board import Board 4 | import os 5 | from solver import Solver 6 | from time import sleep 7 | 8 | class Game: 9 | def __init__(self, size, prob): 10 | self.board = Board(size, prob) 11 | pygame.init() 12 | self.sizeScreen = 800, 800 13 | self.screen = pygame.display.set_mode(self.sizeScreen) 14 | self.pieceSize = (self.sizeScreen[0] / size[1], self.sizeScreen[1] / size[0]) 15 | self.loadPictures() 16 | self.solver = Solver(self.board) 17 | 18 | def loadPictures(self): 19 | self.images = {} 20 | imagesDirectory = "images" 21 | for fileName in os.listdir(imagesDirectory): 22 | if not fileName.endswith(".png"): 23 | continue 24 | path = imagesDirectory + r"/" + fileName 25 | img = pygame.image.load(path) 26 | img = img.convert() 27 | img = pygame.transform.scale(img, (int(self.pieceSize[0]), int(self.pieceSize[1]))) 28 | self.images[fileName.split(".")[0]] = img 29 | 30 | def run(self): 31 | running = True 32 | while running: 33 | for event in pygame.event.get(): 34 | if event.type == pygame.QUIT: 35 | running = False 36 | if event.type == pygame.MOUSEBUTTONDOWN and not (self.board.getWon() or self.board.getLost()): 37 | rightClick = pygame.mouse.get_pressed(num_buttons=3)[2] 38 | self.handleClick(pygame.mouse.get_pos(), rightClick) 39 | if event.type == pygame.KEYDOWN: 40 | self.solver.move() 41 | self.screen.fill((0, 0, 0)) 42 | self.draw() 43 | pygame.display.flip() 44 | if self.board.getWon(): 45 | self.win() 46 | running = False 47 | pygame.quit() 48 | 49 | def draw(self): 50 | topLeft = (0, 0) 51 | for row in self.board.getBoard(): 52 | for piece in row: 53 | rect = pygame.Rect(topLeft, self.pieceSize) 54 | image = self.images[self.getImageString(piece)] 55 | self.screen.blit(image, topLeft) 56 | topLeft = topLeft[0] + self.pieceSize[0], topLeft[1] 57 | topLeft = (0, topLeft[1] + self.pieceSize[1]) 58 | 59 | def getImageString(self, piece): 60 | if piece.getClicked(): 61 | return str(piece.getNumAround()) if not piece.getHasBomb() else 'bomb-at-clicked-block' 62 | if (self.board.getLost()): 63 | if (piece.getHasBomb()): 64 | return 'unclicked-bomb' 65 | return 'wrong-flag' if piece.getFlagged() else 'empty-block' 66 | return 'flag' if piece.getFlagged() else 'empty-block' 67 | 68 | def handleClick(self, position, flag): 69 | index = tuple(int(pos // size) for pos, size in zip(position, self.pieceSize))[::-1] 70 | self.board.handleClick(self.board.getPiece(index), flag) 71 | 72 | def win(self): 73 | sound = pygame.mixer.Sound('win.wav') 74 | sound.play() 75 | sleep(3) -------------------------------------------------------------------------------- /LSystemFractalTrees/system.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import sys 3 | import math 4 | # [x] Define L System 5 | # [x] Implement Sentence Generation 6 | # [x] Implement drawing 7 | # [x] Set up pygame 8 | # [x] Get command line input 9 | # [x] Implement draw function 10 | 11 | # L Systems generate sentences, translate sentences into geometric structures 12 | # Axiom: initial string 13 | # produciton rules: generates longer strings 14 | # translate into geo structures 15 | 16 | class LSystem(): 17 | def __init__(self, axiom, rules, dtheta, start, length, ratio): 18 | self.sentence = axiom 19 | self.rules = rules 20 | self.theta = math.pi / 2 21 | self.dtheta = dtheta 22 | self.start = start 23 | self.x, self.y = start 24 | self.length = length 25 | self.ratio = ratio 26 | self.positions = [] 27 | 28 | def __str__(self): 29 | return self.sentence 30 | 31 | def generate(self): 32 | self.x, self.y = self.start 33 | self.theta = math.pi / 2 34 | self.length *= self.ratio 35 | newStr = "" 36 | for char in self.sentence: 37 | mapped = char 38 | try: 39 | mapped = self.rules[char] 40 | except: 41 | pass 42 | newStr += mapped 43 | self.sentence = newStr 44 | 45 | def draw(self, screen): 46 | color = 0 47 | dcolor = 255 / len(self.sentence) 48 | for char in self.sentence: 49 | if char == 'F' or char == 'G': 50 | x2 = self.x - self.length * math.cos(self.theta) 51 | y2 = self.y - self.length * math.sin(self.theta) 52 | pygame.draw.line(screen, (255 - color, color, 125 + dcolor / 2), (self.x, self.y), (x2, y2)) 53 | self.x, self.y = x2, y2 54 | elif char == '+': 55 | self.theta += self.dtheta 56 | elif char == '-': 57 | self.theta -= self.dtheta 58 | elif char == '[': 59 | self.positions.append({'x' : self.x, 'y' : self.y, 'theta' : self.theta}) 60 | elif char == ']': 61 | position = self.positions.pop() 62 | self.x, self.y, self.theta = position['x'], position['y'], position['theta'] 63 | color += dcolor 64 | 65 | def main(): 66 | l_sys_text = sys.argv[1] 67 | pygame.init() 68 | size = int(sys.argv[2]), int(sys.argv[3]) 69 | start = int(sys.argv[4]), int(sys.argv[5]) 70 | length = int(sys.argv[6]) 71 | ratio = float(sys.argv[7]) 72 | system = None 73 | with open(l_sys_text) as f: 74 | axiom = f.readline() 75 | numRules = int(f.readline()) 76 | rules = {} 77 | for i in range(numRules): 78 | rule = f.readline().split(' ') 79 | rules[rule[0]] = rule[1] 80 | dTheta = math.radians(int(f.readline())) 81 | system = LSystem(axiom, rules, dTheta, start, length, ratio) 82 | screen = pygame.display.set_mode(size) 83 | running = True 84 | while running: 85 | for event in pygame.event.get(): 86 | if event.type == pygame.QUIT: 87 | running = False 88 | if event.type == pygame.MOUSEBUTTONDOWN: 89 | screen.fill((0, 0, 0)) 90 | system.draw(screen) 91 | system.generate() 92 | pygame.display.flip() 93 | pygame.quit() 94 | 95 | main() -------------------------------------------------------------------------------- /LSystemFractalTrees/LSys.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | from typing import Dict 3 | import pygame 4 | import math 5 | import sys 6 | from time import sleep 7 | # [x] Define LSystem 8 | # [x] Implement Sentence Generation 9 | # [] Implement drawing 10 | 11 | # Axiom: Initial String 12 | # Production Rules: Change the String Iteratively 13 | # Make geometric structures using the string 14 | 15 | 16 | class LSystem(): 17 | def __init__(self, axiom: str, rules: Dict[str, str], start: tuple, length: int, theta: int, ratio: float): 18 | self.sentence = axiom 19 | self.rules = rules 20 | self.startx = start[0] 21 | self.starty = start[1] 22 | self.x = self.startx 23 | self.y = self.starty 24 | self.length = length 25 | self.dtheta = math.radians(theta) 26 | self.theta = math.pi / 2 27 | self.positions = [] 28 | self.ratio = ratio 29 | 30 | def __str__(self): 31 | return self.sentence 32 | 33 | def generate(self): 34 | self.length *= self.ratio 35 | self.theta = math.pi / 2 36 | self.x = self.startx 37 | self.y = self.starty 38 | newSentence = "" 39 | for char in self.sentence: 40 | mapped = "" 41 | try: 42 | mapped = self.rules[char] 43 | except: 44 | mapped = char 45 | newSentence += mapped 46 | self.sentence = newSentence 47 | 48 | def draw(self, screen): 49 | color = 0 50 | dcolor = 255 / len(self.sentence) 51 | for char in self.sentence: 52 | if char == 'F' or char == 'G': 53 | x2 = self.x - self.length * math.cos(self.theta) 54 | y2 = self.y - self.length * math.sin(self.theta) 55 | pygame.draw.line(screen, (255 - color, color, 125 + color / 2), (self.x, self.y), (x2, y2)) 56 | self.x = x2 57 | self.y = y2 58 | if char == '+': 59 | self.theta += self.dtheta 60 | if char == '-': 61 | self.theta -= self.dtheta 62 | if char == '[': 63 | self.positions.append({'x' : self.x, 'y' : self.y, 'theta' : self.theta}) 64 | if char == ']': 65 | positions = self.positions.pop() 66 | self.x = positions['x'] 67 | self.y = positions['y'] 68 | self.theta = positions['theta'] 69 | color += dcolor 70 | 71 | def main(): 72 | systemFile = sys.argv[1] 73 | sizeScreen = int(sys.argv[2]), int(sys.argv[3]) 74 | start = int(sys.argv[4]), int(sys.argv[5]) 75 | length = int(sys.argv[6]) 76 | ratio = float(sys.argv[7]) 77 | pygame.init() 78 | screen = pygame.display.set_mode(sizeScreen) 79 | system = None 80 | with open(systemFile, 'r') as f: 81 | axiom = f.readline() 82 | numRules = int(f.readline()) 83 | rules = {} 84 | for i in range(numRules): 85 | rule = f.readline().split(' ') 86 | rules[rule[0]] = rule[1] 87 | system = LSystem(axiom, rules, start, length, int(f.readline()), ratio) 88 | running = True 89 | while running: 90 | for event in pygame.event.get(): 91 | if event.type == pygame.QUIT: 92 | running = False 93 | if event.type == pygame.MOUSEBUTTONDOWN: 94 | screen.fill((0, 0, 0)) 95 | system.draw(screen) 96 | system.generate() 97 | pygame.display.flip() 98 | pygame.quit() 99 | 100 | if __name__ == '__main__': 101 | main() 102 | -------------------------------------------------------------------------------- /Sudoku/solver.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | 3 | BLACK = 0, 0, 0 4 | 5 | class Solver(): 6 | def __init__(self, board): 7 | self.width, self.height = 800, 800 8 | self.board = board 9 | self.rows, self.cols = self.board.getSize() 10 | self.squareWidth, self.squareHeight = self.width / self.cols, self.height / self.rows 11 | self.hRow, self.hCol = 0, 0 12 | self.setImgs() 13 | 14 | def setImgs(self): 15 | pygame.font.init() 16 | font = pygame.font.SysFont('kameron', 64) 17 | self.imgs = {} 18 | for i in range(1, 10): 19 | img = font.render(str(i), True, BLACK) 20 | self.imgs[str(i)] = img 21 | 22 | def run(self): 23 | pygame.init() 24 | self.screen = pygame.display.set_mode((self.width, self.height)) 25 | running = True 26 | while running: 27 | for event in pygame.event.get(): 28 | if (event.type == pygame.QUIT): 29 | running = False 30 | break 31 | if (event.type == pygame.MOUSEBUTTONDOWN): 32 | self.handleClick(pygame.mouse.get_pos()) 33 | if (event.type == pygame.KEYDOWN): 34 | self.handleKey(event) 35 | self.screen.fill((255, 255, 255)) 36 | self.draw() 37 | pygame.display.flip() 38 | pygame.quit() 39 | 40 | def handleClick(self, pos): 41 | x, y = pos 42 | self.hRow, self.hCol = int(self.rows * (y / self.height)), int(self.cols * (x / self.width)) 43 | 44 | def handleKey(self, event): 45 | if event.scancode == 42: 46 | self.board.setSquare((self.hRow, self.hCol), None) 47 | if event.scancode == 40: 48 | solved = self.board.solve() 49 | return 50 | key = event.unicode 51 | if key == 'w': 52 | self.hRow = (self.hRow - 1) % self.rows 53 | elif key == 'a': 54 | self.hCol = (self.hCol - 1) % self.cols 55 | elif key == 's': 56 | self.hRow = (self.hRow + 1) % self.rows 57 | elif key == 'd': 58 | self.hCol = (self.hCol + 1) % self.cols 59 | try: 60 | number = int(key) 61 | except ValueError: 62 | return 63 | if number < 1 or number > 9: 64 | return 65 | self.board.setSquare((self.hRow, self.hCol), number) 66 | 67 | def draw(self): 68 | left, top = 0, 0 69 | for row in range(self.rows): 70 | for col in range(self.cols): 71 | number = self.board.getSquare((row, col)) 72 | rect = pygame.Rect((left, top), (self.squareWidth, self.squareHeight)) 73 | if row == self.hRow and col == self.hCol: 74 | RGB = (187,222,251) 75 | width = 0 76 | pygame.draw.rect(self.screen, RGB, rect, width=width) 77 | RGB = 100, 100, 100 78 | width = 10 79 | pygame.draw.rect(self.screen, RGB, rect, width=width) 80 | if number: 81 | img = self.imgs[str(number)] 82 | w, h = img.get_size() 83 | centerX, centerY = left + self.squareWidth * 0.5, top + self.squareHeight * 0.5 84 | self.screen.blit(img, (centerX - 0.5 * w, centerY - 0.5 * h)) 85 | left, top = left + self.squareWidth, top 86 | left, top = 0, top + self.squareHeight 87 | self.drawLines() 88 | 89 | def drawLines(self): 90 | x0, y0 = self.width, self.height 91 | for i in range(1, 3): 92 | x = i * (x0 / 3) 93 | pygame.draw.line(self.screen, (50, 50, 50), (x, 0), (x, y0), width = 15) 94 | for i in range(1, 3): 95 | y = i * (y0 / 3) 96 | pygame.draw.line(self.screen, (50, 50, 50), (0, y), (x0, y), width = 15) 97 | -------------------------------------------------------------------------------- /Hangman/main.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import math 3 | import random 4 | # setup display 5 | pygame.init() 6 | WIDTH, HEIGHT = 800, 800 7 | win = pygame.display.set_mode((WIDTH, HEIGHT)) 8 | pygame.display.set_caption("Hangman Game") 9 | 10 | # button variables 11 | RADIUS = 20 12 | GAP = 15 13 | letters = [] 14 | startx = round((WIDTH - (RADIUS * 2 + GAP) * 13) / 2) 15 | starty = 400 16 | A = 65 17 | for i in range(26): 18 | x = startx + GAP * 2 + ((RADIUS * 2 + GAP) * (i % 13)) 19 | y = starty + ((i // 13) * (GAP + RADIUS * 2)) 20 | letters.append([x, y, chr(A + i), True]) 21 | 22 | # fonts 23 | LETTER_FONT = pygame.font.SysFont('comicsans', 40) 24 | WORD_FONT = pygame.font.SysFont('comicsans', 60) 25 | TITLE_FONT = pygame.font.SysFont('comicsans', 70) 26 | # load images 27 | images = [] 28 | for i in range(7): 29 | image = pygame.image.load("images/images/hangman" + str(i) + '.png') 30 | images.append(image) 31 | 32 | # game variables 33 | hangman_status = 0 34 | words = ['PYTHON', 'IDE', 'PYGAME', 'STACKOVERFLOW'] 35 | word = random.choice(words) 36 | guessed = [] 37 | 38 | WHITE = (255, 255, 255) 39 | BLACK = (0,0,0) 40 | # setup game loop 41 | 42 | 43 | def draw(): 44 | win.fill(WHITE) 45 | # draw title 46 | text = TITLE_FONT.render("DEVELOPER HANGMAN", 1, BLACK) 47 | win.blit(text, (WIDTH / 2 - text.get_width() / 2, 20)) 48 | # draw word 49 | display_word = "" 50 | for letter in word: 51 | if letter in guessed: 52 | display_word += letter + " " 53 | else: 54 | display_word += "_ " 55 | text = WORD_FONT.render(display_word, 1, BLACK) 56 | win.blit(text, (400, 200)) 57 | 58 | # draw buttons 59 | for letter in letters: 60 | x, y, ltr, visible = letter 61 | if visible: 62 | pygame.draw.circle(win, BLACK, (x,y), RADIUS, 3) 63 | text = LETTER_FONT.render(ltr, 1, BLACK) 64 | win.blit(text, (x - text.get_width() / 2, y - text.get_height() / 2)) 65 | win.blit(images[hangman_status], (150, 100)) 66 | pygame.display.update() 67 | 68 | def display_message(message): 69 | pygame.time.delay(1000) 70 | win.fill(WHITE) 71 | text = WORD_FONT.render(message, 1, BLACK) 72 | win.blit(text, ((WIDTH / 2 - text.get_width() / 2), (HEIGHT / 2 - text.get_height() / 2))) 73 | pygame.display.update() 74 | pygame.time.delay(3000) 75 | 76 | # main loop 77 | def main(): 78 | global hangman_status 79 | FPS = 60 80 | clock = pygame.time.Clock() 81 | run = True 82 | while run : 83 | clock.tick(FPS) 84 | 85 | draw() 86 | 87 | for event in pygame.event.get(): 88 | if event.type == pygame.QUIT: 89 | pygame.quit() 90 | if event.type == pygame.MOUSEBUTTONDOWN: 91 | m_x, m_y = pygame.mouse.get_pos() 92 | for letter in letters: 93 | x, y, ltr, visible = letter 94 | if visible: 95 | dis = math.sqrt((x - m_x)**2 + (y - m_y)**2) 96 | if dis < RADIUS: 97 | letter[3] = False 98 | guessed.append(ltr) 99 | if ltr not in word: 100 | hangman_status += 1 101 | draw() 102 | won = True 103 | for letter in word: 104 | if letter not in guessed: 105 | won = False 106 | break 107 | if won: 108 | display_message('YOU WON!') 109 | run = False 110 | break 111 | if hangman_status == 6: 112 | display_message('YOU LOST!') 113 | run = False 114 | break 115 | 116 | while True: 117 | win.fill(WHITE) 118 | for event in pygame.event.get(): 119 | win.fill(WHITE) 120 | text = TITLE_FONT.render("CLICK TO BEGIN", 1, BLACK) 121 | if event.type == pygame.QUIT: 122 | pygame.quit() 123 | if event.type == pygame.MOUSEBUTTONDOWN: 124 | main() 125 | 126 | pygame.quit() 127 | -------------------------------------------------------------------------------- /PiCollisions/main.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from time import sleep 3 | 4 | BLACK = (0, 0, 0) 5 | WHITE = (255, 255, 255) 6 | 7 | class Block(): 8 | def __init__(self, length, mass, velocity, left, bot): 9 | self.length = length 10 | self.mass = mass 11 | self.velocity = velocity 12 | self.left = left 13 | self.rect = pygame.Rect(left, bot - length, length, length) 14 | self.right = left + length 15 | 16 | def getPos(self): # left and right x coords 17 | return (self.left, self.right) 18 | 19 | def update(self, dt): 20 | self.left += self.velocity * dt 21 | self.right = self.left + self.length 22 | 23 | def switchDir(self): 24 | self.velocity = -1 * self.velocity 25 | 26 | def updateVisuals(self): 27 | self.rect.x = self.left 28 | 29 | def draw(self, screen): 30 | pygame.draw.rect(screen, WHITE, self.rect) 31 | 32 | @staticmethod 33 | def collision(block1, block2): 34 | m1, v10, m2, v20 = block1.mass, block1.velocity, block2.mass, block2.velocity 35 | block1.velocity = (m1*v10+m2*v20-m2*v10+m2*v20)/(m1+m2) 36 | block2.velocity = (m1*v10+m2*v20-m1*v20+m1*v10)/(m1+m2) 37 | 38 | class Sim(): 39 | def __init__(self, digits): 40 | self.dim = 1600, 800 41 | pygame.init() 42 | self.screen = pygame.display.set_mode(self.dim) 43 | self.left = 10 44 | self.bot = self.dim[1] - 10 45 | # self.font = pygame.font.SysFont(None, 24) 46 | self.collisions = 0 47 | self.block1 = Block(50, 1, 0, self.dim[0]*(1/3), self.bot) 48 | self.block2 = Block(50 * digits, 100 ** (digits - 1), -30, self.dim[0]*(2/3), self.bot) 49 | self.line = (self.left, 0, self.left, self.dim[1]) 50 | self.rate = 5 51 | 52 | def run(self): 53 | dt = 0.01 54 | running = True 55 | while running: 56 | for event in pygame.event.get(): 57 | if (event.type == pygame.QUIT): 58 | running = False 59 | self.screen.fill(BLACK) 60 | pygame.draw.line(self.screen, WHITE, (10, 0), (10, self.bot)) 61 | pygame.draw.line(self.screen, WHITE, (10, self.bot), (self.dim[0], self.bot)) 62 | r = self.fastRate() if self.block2.left < self.left + (self.block1.length * 2) else self.rate 63 | for i in range(r): 64 | self.advance(dt) 65 | self.handleCollisions() 66 | self.updateVisuals() 67 | self.drawBlocks() 68 | pygame.display.flip() 69 | 70 | pygame.quit() 71 | 72 | def drawBlocks(self): 73 | self.block1.draw(self.screen) 74 | self.block2.draw(self.screen) 75 | 76 | def fastRate(self): 77 | dist = self.block2.left - (self.left + self.block1.length) 78 | return int((self.rate * 10) / dist) 79 | 80 | def updateVisuals(self): 81 | self.block1.updateVisuals() 82 | self.block2.updateVisuals() 83 | 84 | def advance(self, dt): 85 | self.block1.update(dt) 86 | self.block2.update(dt) 87 | 88 | def handleCollisions(self): 89 | collision = False 90 | if self.block1.left < self.left: 91 | distError = self.block1.left - self.left 92 | timeError = distError / self.block1.velocity 93 | self.advance(-timeError) 94 | self.block1.switchDir() 95 | collision = True 96 | elif self.block1.right > self.block2.left: 97 | timeError = (self.block1.right-self.block2.left)/(self.block1.velocity-self.block2.velocity) 98 | self.advance(-timeError) 99 | Block.collision(self.block1, self.block2) 100 | collision = True 101 | if collision: 102 | self.collisions += 1 103 | self.drawNumber() 104 | 105 | def drawNumber(self): 106 | # img = font.render(str(self.collisions), True, WHITE) 107 | # self.screen.blit(img, (WIDTH - 100, 50)) 108 | print(self.collisions) 109 | 110 | sim = Sim(5) 111 | sim.run() 112 | -------------------------------------------------------------------------------- /TicTacToe/game.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from board import Board 3 | from time import sleep 4 | from solver import Solver 5 | 6 | RED = (255, 0, 0) 7 | GREEN = (0, 255, 0) 8 | WHITE = (255, 255, 255) 9 | BLUE = (0, 0, 255) 10 | 11 | class Game(): 12 | def __init__(self, screenSize): 13 | self.screenSize = screenSize 14 | self.pieceSize = self.screenSize[0] / 3, self.screenSize[1] / 3 15 | self.player = 'O' 16 | self.computer = 'X' 17 | self.board = Board(None) 18 | self.compTurn = False 19 | self.state = 'ask' 20 | 21 | def run(self): 22 | pygame.init() 23 | self.screen = pygame.display.set_mode(self.screenSize) 24 | running = True 25 | while running: 26 | for event in pygame.event.get(): 27 | if (event.type == pygame.QUIT): 28 | running = False 29 | if (event.type == pygame.MOUSEBUTTONDOWN): 30 | self.handleClick(pygame.mouse.get_pos()) 31 | if (self.state == 'game'): 32 | self.game() 33 | else: 34 | self.ask() 35 | pygame.display.flip() 36 | pygame.quit() 37 | 38 | def ask(self): 39 | self.screen.fill((0, 0, 0)) 40 | self.drawX((1, 0)) 41 | self.drawO((1, 2)) 42 | 43 | def game(self): 44 | self.draw() 45 | if (self.checkEnd()): 46 | self.state = 'ask' 47 | self.board = Board(None) 48 | self.compTurn = False 49 | if (self.compTurn): 50 | self.compMove() 51 | 52 | def checkEnd(self): 53 | winBoard = () 54 | if (self.board.getHasWon(self.player)): 55 | winBoard = self.board.getHasWon(self.player) 56 | elif (self.board.getHasWon(self.computer)): 57 | winBoard = self.board.getHasWon(self.computer) 58 | elif (not self.board.isFull()): 59 | return False 60 | for row, col in winBoard: 61 | self.highlight((row, col)) 62 | pygame.display.flip() 63 | sleep(3) 64 | return True 65 | 66 | 67 | def highlight(self, index): 68 | region = self.getRegion(index) 69 | pygame.draw.rect(self.screen, BLUE, region, width = 10) 70 | 71 | def draw(self): 72 | self.screen.fill((0, 0, 0)) 73 | self.drawPieces() 74 | self.drawLines() 75 | 76 | def drawPieces(self): 77 | for row in range(3): 78 | for col in range(3): 79 | piece = self.board.getPiece((row, col)) 80 | if (piece == 'X'): 81 | self.drawX((row, col)) 82 | elif (piece == 'O'): 83 | self.drawO((row, col)) 84 | 85 | def drawX(self, index): 86 | region = self.getRegion(index) 87 | pygame.draw.line(self.screen, RED, region.topleft, region.bottomright, width = 10) 88 | pygame.draw.line(self.screen, RED, region.topright, region.bottomleft, width = 10) 89 | 90 | def drawO(self, index): 91 | region = self.getRegion(index) 92 | pygame.draw.ellipse(self.screen, GREEN, region, width=10) 93 | 94 | def getRegion(self, index): 95 | buffer = 10 96 | leftTop = int(index[1] * self.pieceSize[0] + buffer), int(index[0] * self.pieceSize[1] + buffer) 97 | widthHeight = int(self.pieceSize[0] - buffer), int(self.pieceSize[1] - buffer) 98 | rect = pygame.Rect(leftTop, widthHeight) 99 | return rect 100 | 101 | def drawLines(self): 102 | for i in range(1, 3): 103 | x = i * (self.screenSize[0] / 3) 104 | pygame.draw.line(self.screen, WHITE, (x, 0), (x, self.screenSize[1]), width = 10) 105 | for i in range(1, 3): 106 | y = i * (self.screenSize[1] / 3) 107 | pygame.draw.line(self.screen, WHITE, (0, y), (self.screenSize[0], y), width = 10) 108 | 109 | def getIndex(self, position): 110 | return int(position[1] / self.pieceSize[1]), int(position[0] / self.pieceSize[0]) 111 | 112 | def handleClick(self, position): 113 | if (self.state == 'ask'): 114 | if (position[0] < self.screenSize[0] / 2): 115 | self.player = 'X' 116 | self.computer = 'O' 117 | self.compTurn = False 118 | else: 119 | self.player = 'O' 120 | self.computer = 'X' 121 | self.compTurn = True 122 | self.state = 'game' 123 | return 124 | index = self.getIndex(position) 125 | piece = self.board.getPiece(index) 126 | if (piece != '-'): 127 | return 128 | self.board = self.board.getMovedBoard(index, self.player) 129 | self.compTurn = True 130 | 131 | def compMove(self): 132 | solver = Solver() 133 | self.board = solver.getBestMove(self.board, self.computer) 134 | self.compTurn = False 135 | -------------------------------------------------------------------------------- /AStar/main.py: -------------------------------------------------------------------------------- 1 | from piece import Piece 2 | import sys 3 | import pygame 4 | from collections import deque 5 | from queue import PriorityQueue 6 | import heapq 7 | from math import exp 8 | 9 | WHITE = 255, 255, 255 10 | BLACK = 0, 0, 0 11 | CYAN = 0, 255, 255 12 | RED = 255, 0, 0 13 | GREEN = 0, 255, 0 14 | BLUE = 0, 0, 255 15 | YELLOW = 255, 255, 0 16 | 17 | class Sim: 18 | def __init__(self, size): 19 | self.screenWidth, self.screenHeight = 1600, 900 20 | self.rows, self.cols = size[0], size[1] 21 | self.pieceWidth, self.pieceHeight = self.screenWidth / self.cols, self.screenHeight / self.rows 22 | self.modes = 'begin', 'end', 'wall', 'start' 23 | self.mode = 0 24 | self.done = False 25 | self.drag = False 26 | self.STEP = pygame.USEREVENT+1 27 | self.setBoard() 28 | 29 | def setBoard(self): 30 | self.board = [] 31 | for r in range(self.rows): 32 | row = [] 33 | for c in range(self.cols): 34 | row.append(Piece(r, c)) 35 | self.board.append(row) 36 | for row in self.board: 37 | for piece in row: 38 | neighbors = self.getNeighborsList(piece) 39 | piece.setNeighbors(neighbors) 40 | 41 | def getNeighborsList(self, piece): 42 | n = [] 43 | for r in range(max(piece.row - 1, 0), min(piece.row + 2, self.rows)): 44 | for c in range(max(piece.col - 1, 0), min(piece.col + 2, self.cols)): 45 | if r == piece.row and c == piece.col: 46 | continue 47 | n.append(self.board[r][c]) 48 | # if (piece.row - 1 >= 0): 49 | # n.append(self.board[piece.row - 1][piece.col]) 50 | # if (piece.row + 1 < self.rows): 51 | # n.append(self.board[piece.row + 1][piece.col]) 52 | # if (piece.col - 1 >= 0): 53 | # n.append(self.board[piece.row][piece.col - 1]) 54 | # if (piece.col + 1 < self.cols): 55 | # n.append(self.board[piece.row][piece.col + 1]) 56 | return n 57 | 58 | def run(self): 59 | pygame.init() 60 | self.screen = pygame.display.set_mode((self.screenWidth, self.screenHeight)) 61 | running = True 62 | while running: 63 | for event in pygame.event.get(): 64 | if event.type == pygame.QUIT: 65 | running = False 66 | break 67 | if event.type == pygame.MOUSEBUTTONDOWN or self.drag: 68 | self.handleClick(pygame.mouse.get_pos()) 69 | if event.type == pygame.MOUSEBUTTONUP: 70 | self.drag = False 71 | if event.type == pygame.KEYDOWN: 72 | self.mode = 3 73 | pygame.time.set_timer(self.STEP, 10) 74 | if event.type == self.STEP and not self.done: 75 | # self.BFSStep() 76 | self.AStarStep() 77 | self.screen.fill(WHITE) 78 | self.drawBoard() 79 | pygame.display.flip() 80 | pygame.quit() 81 | 82 | def BFSStep(self): 83 | length = len(self.q) 84 | for i in range(length): 85 | piece = self.q.popleft() 86 | piece.popped = True 87 | piece.visited = True 88 | for neighbor in piece.neighbors: 89 | if neighbor.visited or neighbor.isWall: 90 | continue 91 | neighbor.parent = piece 92 | if neighbor.isEnd: 93 | self.done = True 94 | curr = neighbor 95 | while curr: 96 | curr.path = True 97 | curr = curr.parent 98 | return 99 | self.q.append(neighbor) 100 | neighbor.visited = True 101 | 102 | def AStarStep(self): 103 | # self.printBoard() 104 | # self.pq.sort(key=lambda x: x.f(),reverse=True) 105 | # piece = self.pq.pop() 106 | piece = heapq.heappop(self.pq) 107 | piece.timePopped = pygame.time.get_ticks() 108 | piece.popped = True 109 | piece.visited = True 110 | if piece.isEnd: 111 | curr = piece 112 | self.done = True 113 | while not curr.isStart: 114 | curr.path = True 115 | curr = curr.parent 116 | return 117 | for neighbor in piece.neighbors: 118 | if neighbor.popped or neighbor.isWall: 119 | continue 120 | diag = piece.row != neighbor.row and piece.col != neighbor.col 121 | g = piece.g + (14 if diag else 10) 122 | h = self.euclidean(neighbor, self.end) 123 | if (g < neighbor.g or not neighbor.visited): 124 | neighbor.g = g 125 | neighbor.h = h 126 | neighbor.parent = piece 127 | if (not neighbor.visited): 128 | # self.pq.append(neighbor) 129 | heapq.heappush(self.pq, neighbor) 130 | neighbor.visited = True 131 | 132 | def manhattan(self, curr, target): 133 | return abs(curr.row - target.row) + abs(curr.col - target.col) 134 | 135 | def euclidean(self, first, second): 136 | dy = abs(first.row - second.row) 137 | dx = abs(first.col - second.col) 138 | diag = min(dy, dx) 139 | return diag * 14 + (max(dy, dx) - diag) * 10 140 | 141 | def printBoard(self): 142 | for r in range(self.rows): 143 | for c in range(self.cols): 144 | print(self.board[r][c].f(), end=" ") 145 | print() 146 | pass 147 | 148 | def handleClick(self, pos): 149 | x, y = pos 150 | col, row = int(self.cols * x / self.screenWidth), int(self.rows * y / self.screenHeight) 151 | piece = self.board[row][col] 152 | if self.modes[self.mode] == 'begin': 153 | self.start = piece 154 | self.start.isStart = True 155 | self.q = deque() 156 | self.q.append(piece) 157 | piece.g = 0 158 | self.pq = [piece] 159 | # self.pq.sort(reverse=True) 160 | heapq.heapify(self.pq) 161 | self.mode += 1 162 | elif self.modes[self.mode] == 'end': 163 | self.end = piece 164 | self.end.isEnd = True 165 | self.mode += 1 166 | elif self.modes[self.mode] == 'wall': 167 | self.drag = True 168 | piece.isWall = True 169 | 170 | def drawBoard(self): 171 | for row in self.board: 172 | for piece in row: 173 | self.drawPiece(piece) 174 | 175 | def drawPiece(self, piece): 176 | leftTop = self.pieceWidth * piece.col, self.pieceHeight * piece.row 177 | rect = pygame.Rect(leftTop, (self.pieceWidth, self.pieceHeight)) 178 | if piece.isStart or piece.isEnd: 179 | pygame.draw.rect(self.screen, RED, rect) 180 | elif piece.path: 181 | pygame.draw.rect(self.screen, YELLOW, rect) 182 | elif piece.isWall: 183 | pygame.draw.rect(self.screen, BLACK, rect) 184 | elif piece.popped: 185 | sincePopped = pygame.time.get_ticks() - piece.timePopped 186 | val = exp(sincePopped * 0.01) 187 | # val = sincePopped * 1000 / 255 188 | RGB = (0, min(val, 255), min(val, 255)) 189 | pygame.draw.rect(self.screen, RGB, rect) 190 | # elif piece.visited: 191 | # pygame.draw.rect(self.screen, RED, rect) 192 | else: 193 | pygame.draw.rect(self.screen, BLACK, rect, width = 1) 194 | 195 | if __name__ == '__main__': 196 | rows, cols = int(sys.argv[1]), int(sys.argv[2]) 197 | sim = Sim((rows, cols)) 198 | sim.run() --------------------------------------------------------------------------------