Python Brickbreaker with Tkinter

 
from tkinter import *
import random
import time

tk = Tk()
tk.title("Game")
tk.resizable(0, 0)
tk.wm_attributes("-topmost", 1)
canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()
tk.update()

class Ball:
    def __init__(self, canvas, paddle, color):
        self.canvas = canvas
        self.paddle = paddle
        self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
        self.canvas.move(self.id, 245, 100)
        starts = [-3, -2, -1, 1, 2, 3]
        random.shuffle(starts)
        self.x = starts[0]
        self.y = -3
        self.canvas_height = self.canvas.winfo_height()
        self.canvas_width = self.canvas.winfo_width()
        
    def draw(self):
        self.canvas.move(self.id, self.x, self.y)
        pos = self.canvas.coords(self.id)
        if pos[1] <= 0:
            self.y = 3
        if pos[3] >= self.canvas_height:
            self.y = -3
        if self.hit_paddle(pos) == True:
            self.y = -3
        if pos[0] <= 0:
            self.x = 3
        if pos[2] >= self.canvas_width:
            self.x = -3
            
    def hit_paddle(self, pos):
        paddle_pos = self.canvas.coords(self.paddle.id)
        if pos[2] >= paddle_pos[0] and pos[0] <= paddle_pos[2]:
            if pos[3] >= paddle_pos[1] and pos[3] <= paddle_pos[3]:
                return True
        return False

class Paddle:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_rectangle(0, 0, 100, 10, fill=color)
        self.canvas.move(self.id, 200, 300)
        self.x = 0
        self.canvas_width = self.canvas.winfo_width()
        self.canvas.bind_all('<KeyPress-Left>', self.turn_left)
        self.canvas.bind_all('<KeyPress-Right>', self.turn_right)
        
    def turn_left(self, evt):
        self.x = -2
        
    def turn_right(self, evt):
        self.x = 2
        
    def draw(self):
        self.canvas.move(self.id, self.x, 0)
        pos = self.canvas.coords(self.id)
        if pos[0] <= 0:
            self.x = 0
        elif pos[2] >= self.canvas_width:
            self.x = 0
     
paddle = Paddle(canvas, 'blue')
ball = Ball(canvas, paddle, 'red')

while 1:
    ball.draw()
    paddle.draw()
    tk.update_idletasks()
    tk.update()
    time.sleep(0.01)

PyGame Basic Setup

 

import pygame
import random

WIDTH = 480
HEIGHT = 480
FPS = 30

# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# initialize pygame and create window
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()

# Game loop
running = True
while running:
    # keep loop running at the right speed
    clock.tick(FPS)
    # Process input (events)
    for event in pygame.event.get():
        # check for closing window
        if event.type == pygame.QUIT:
            running = False

    # Update

    # Draw / render
    screen.fill(BLACK)
    # *after* drawing everything, flip the display
    pygame.display.flip()

pygame.quit()

 

 

Python Turtle Demo Spirograph

 <br> import random,time,turtle<br>bai = turtle.Turtle()<br>bai.pendown<br>bai.speed(10)<br>bai.tracer(300)<br>bai.hideturtle()<br>for i in range (1000):<br>  for i in range(4):<br>   for i in range (40):<br>    bai.forward(50)<br>    bai.left(100)<br>    r = random.randint(0,255)<br>    g = random.randint(0,255)<br>    b = random.randint(0,255)<br>    bai.pencolor((r,g,b))<br>    for i in range(4):<br>       bai.forward(10)<br>       bai.left(90)<br>   time.sleep(0.1)<br>  bai.penup<br>  bai.forward(100)<br>  bai.pendown  

   <br><br> import turtle<br>import time<br>import random<br>bob = turtle.Turtle()<br>bob.tracer(300)<br>bob.pendown()<br>bob.hideturtle()<br>for i in range (20):<br>  for i in range(200):<br>    bob.forward(158)<br>    bob.left(200)<br>    bob.right(1)<br>    r = random.randint(1,255)<br>    g = random.randint(1,255)<br>    b = random.randint(1,255)<br>    bob.pencolor((r,g,b))<br>  time.sleep(0.1)    <br>

Hacking 3/12

PART 1
uname = “Mufasa”
password = “Circle Of Life”
realm = “testrealm@host.com
nonce=”dcd98b7102dd2f0e8b11d0f600bfb0c093″
uri=”/dir/index.html”
nc=”00000001″ # note this is a string
cnonce=”0a4f113b”
 
ha1 = hashlib.md5((uname+’:’+realm+’:’+password).encode(‘utf-8’)).hexdigest()
ha2 = hashlib.md5((‘GET:’+uri).encode(‘utf-8’)).hexdigest()
response = hashlib.md5((ha1+’:’+nonce+’:’+nc+’:’+cnonce+’:auth:’+ha2).encode(‘utf8’)).hexdigest()
print(response)
PART 2
from string import ascii_letters, digits
import itertools
import sys
 
for len in range(1,8):
    for letters in itertools.product(ascii_letters+digits, repeat=len):
        guess=”.join(letters)
        if happy_result(guess):
            print(‘Password found:’, guess)
            sys.exit()
print(‘Epic fail! Try harder next time.’)

RSA Encryption

woE7ewVfwoAzbwXCgC5iMyRvBTvCgGBiOy4=
public key: e=5, n=133
import random
import base64

'''
Euclid's algorithm to determine the greatest common divisor
'''
def gcd(a,b):
    while b != 0:
        c = a % b
        a = b
        b = c
    return a

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    g, y, x = egcd(b%a,a)
    return (g, x - (b//a) * y, y)

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        raise Exception('No modular inverse')
    return x%m

def encrypt(plaintext,keypair):
    e,n = keypair

    # Encrypt the plaintext
    cipher = ''.join([chr(pow(ord(char),e,n)) for char in plaintext])
    # Encode the ciphertext so it's more readable/sharable
    encoded = base64.b64encode(cipher.encode('utf-8'))
    return str(encoded,'utf-8')

def decrypt(ciphertext,keypair):
    d,n = keypair

    # Decode the text to the original format
    decoded = base64.b64decode(ciphertext).decode('utf-8')
    # Decrypt it
    plain = (str(chr(pow(ord(char),d,n))) for char in decoded)
    return ''.join(plain)

def generate_keypair(p,q,e=None):
    n = p * q

    #Phi is the totient of n
    phi = (p-1)*(q-1)

    #Choose an integer e such that e and phi(n) are coprime
    if e is None:
        e = random.randrange(1, phi)

    #Use Euclid's Algorithm to verify that e and phi(n) are comprime
    g = gcd(e, phi)
    while g != 1:
        e = random.randrange(1, phi)
        g = gcd(e, phi)

    #Now find the multiplicative inverse of e and phi to generate the private key
    d = modinv(e, phi)

    return ((e,n),(d,n))

#Only run this part if we're not running as an imported module
if __name__ == '__main__':
    p = int(input("Enter prime number p: "))
    q = int(input("Enter prime number q: "))

    public, private = generate_keypair(p,q)

    print("Your public key is the number pair of (e=" +  str(public[0]) + ", n=" + str(public[1]) +").\n")
    print("Your private key is the number pair of (d=" +  str(private[0]) + ", n=" + str(private[1]) +").\n")

    s = input("Enter your message: ")
    encrypted = encrypt(s,public)

    print("Encrypted message: " + encrypted)
    decrypted = decrypt(encrypted,private)
    print("Decrypt: " + decrypted)  

BMP-280 with Raspberry Pi and Python Wiring/Code

Adafruit Source

Python Computer Wiring

Since there’s dozens of Linux computers/boards you can use we will show wiring for Raspberry Pi. For other platforms, please visit the guide for CircuitPython on Linux to see whether your platform is supported.

Here’s the Raspberry Pi wired with I2C:

  • adafruit_products_raspi_bmp280_i2c_bb.png
  • Pi 3V3 to sensor VIN
  • Pi GND to sensor GND
  • Pi SCL to sensor SCK
  • Pi SDA to sensor SDI

And an example on the Raspberry Pi 3 Model B wired with SPI:

  • adafruit_products_raspi_bme280_spi_bb.png
  • Pi 3V3 to sensor VIN
  • Pi GND to sensor GND
  • Pi MOSI to sensor SDI
  • Pi MISO to sensor SDO
  • Pi SCLK to sensor SCK
  • Pi #5 to sensor CS (or use any other free GPIO pin)

CircuitPython Installation of BMP280 Library

You’ll need to install the Adafruit CircuitPython BMP280 library on your CircuitPython board.

First make sure you are running the latest version of Adafruit CircuitPython for your board.

Next you’ll need to install the necessary libraries to use the hardware–carefully follow the steps to find and install these libraries from Adafruit’s CircuitPython library bundle.  Our CircuitPython starter guide has a great page on how to install the library bundle.

For non-express boards like the Trinket M0 or Gemma M0, you’ll need to manually install the necessary libraries from the bundle:

  • adafruit_bmp280.mpy
  • adafruit_bus_device

Before continuing make sure your board’s lib folder or root filesystem has the adafruit_bmp280.mpy, and adafruit_bus_device files and folders copied over.

Next connect to the board’s serial REPL so you are at the CircuitPython >>> prompt.

Python Installation of BMP280 Library

You’ll need to install the Adafruit_Blinka library that provides the CircuitPython support in Python. This may also require enabling I2C on your platform and verifying you are running Python 3. Since each platform is a little different, and Linux changes often, please visit the CircuitPython on Linux guide to get your computer ready!

Once that’s done, from your command line run the following command:

  • sudo pip3 install adafruit-circuitpython-bmp280

If your default Python is version 3 you may need to run ‘pip’ instead. Just make sure you aren’t trying to use CircuitPython on Python 2.x, it isn’t supported!

CircuitPython & Python Usage

To demonstrate the usage of the sensor we’ll initialize it and read the temperature, humidity, and more from the board’s Python REPL.

If you’re using an I2C connection run the following code to import the necessary modules and initialize the I2C connection with the sensor:

 Download: file

  1. import board
  2. import busio
  3. import adafruit_bmp280
  4. i2c = busio.I2C(board.SCL, board.SDA)
  5. sensor = adafruit_bmp280.Adafruit_BMP280_I2C(i2c)

Or if you’re using a SPI connection run this code instead to setup the SPI connection and sensor:

 Download: file

  1. import board
  2. import busio
  3. import digitalio
  4. import adafruit_bmp280
  5. spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
  6. cs = digitalio.DigitalInOut(board.D5)
  7. sensor = adafruit_bmp280.Adafruit_BMP280_SPI(spi, cs)

Now you’re ready to read values from the sensor using any of these properties:

  • temperature – The sensor temperature in degrees Celsius.
  • pressure – The pressure in hPa.
  • altitude – The altitude in meters.

For example to print temperature and pressure:

 Download: file

  1. print(‘Temperature: {} degrees C’.format(sensor.temperature))
  2. print(‘Pressure: {}hPa’.format(sensor.pressure))
adafruit_products_Screen_Shot_2017-11-10_at_3.33.47_PM.png

For altitude you’ll want to set the pressure at sea level for your location to get the most accurate measure (remember these sensors can only infer altitude based on pressure and need a set calibration point).  Look at your local weather report for a pressure at sea level reading and set the seaLevelhPA property:

 Download: file

  1. sensor.sea_level_pressure = 1013.25

Then read the altitude property for a more accurate altitude reading (but remember this altitude will fluctuate based on atmospheric pressure changes!):

 Download: file

  1. print(‘Altitude: {} meters’.format(sensor.altitude))
adafruit_products_alti.png

That’s all there is to using the BMP280 sensor with CircuitPython!

Here’s a starting example that will print out the temperature, pressure and altitude every 2 seconds:

  1. import time
  2.  
  3. import board
  4. # import digitalio # For use with SPI
  5. import busio
  6.  
  7. import adafruit_bmp280
  8.  
  9. # Create library object using our Bus I2C port
  10. i2c = busio.I2C(board.SCL, board.SDA)
  11. bmp280 = adafruit_bmp280.Adafruit_BMP280_I2C(i2c)
  12.  
  13. # OR create library object using our Bus SPI port
  14. #spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
  15. #bmp_cs = digitalio.DigitalInOut(board.D10)
  16. #bmp280 = adafruit_bmp280.Adafruit_BMP280_SPI(spi, bmp_cs)
  17.  
  18. # change this to match the location’s pressure (hPa) at sea level
  19. bmp280.sea_level_pressure = 1013.25
  20.  
  21. while True:
  22. print(“\nTemperature: %0.1f C” % bmp280.temperature)
  23. print(“Pressure: %0.1f hPa” % bmp280.pressure)
  24. print(“Altitude = %0.2f meters” % bmp280.altitude)
  25. time.sleep(2)

Chatroom Source

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('0.0.0.0',25565))
s.listen(10)

while True:
    print('waiting for new connection')
    conn,addr = s.accept()
    print('New connection: ' + str(addr))

    motd = "Welcome to PolyChat!"
    conn.sendto(bytes(motd,'utf-8'), addr)

    char = ''
    message = ''
    while char != None and char != 'q':
        char,temp = conn.recvfrom(1024)
        char = char.decode('utf-8')
        message += char
        print(message)
        
    conn.close()



Platformer Python Code


import turtle, random,time
map = input('Select a map from 1-8 or press 9 for random map')
max = 8
map = int(map)
if map == max:
  map = random.randint(1,max-1)
if map == 1:
  mapName = "v"
if map == 2:
  mapName = "d"
if map == 3:
  mapName = "m"
if map == 4:
  mapName = "a"
if map == 5:
  mapName = "j"
if map == 6:
  mapName = "e (1)"
if map == 7:
  mapName = "t"
if map == 8:
  mapName = "l"

charlist = ['rainbowbob','Kataniguana','yurp','REEE','Zhane','america','lightning','Goku','Symmetra','Dva','Junkrat2','Mercy','soldier']
print(charlist)
char1 = int(input('Player 1 Choose a character from the list.'))
char2 = int(input('Player 2 Choose a character from the list.'))
char1 = charlist[char1-1]
char2 = charlist[char2-1]

you = turtle.Turtle()
you.penup()
them = turtle.Turtle()
them.penup()
ball = turtle.Turtle()
screen = turtle.Screen()
screen.setup(400, 400)
direction = "up"
screen.bgpic(mapName+".png")
screen.addshape(char1+".png")
you.shape(char1+".png")
screen.addshape(char2+".png")
them.shape(char2+".png")
move_speed = 10


##MOVEMENT CODE FOR SPRITE 1 (YOU)
def up():
  xold = you.xcor()
  yold = you.ycor()
  you.sety(you.ycor()+move_speed)
  if you.ycor()> 200:
    you.sety(-200)
  print(str(you.xcor())+','+str(you.ycor()))
  findbox(xold,yold)
def down():
  xold = you.xcor()
  yold = you.ycor()
  you.sety(you.ycor()-move_speed)
  if you.ycor()< -200:
    you.sety(200)
  print(str(you.xcor())+','+str(you.ycor()))
  findbox(xold,yold)
def left():
  xold = you.xcor()
  yold = you.ycor()
  you.setx(you.xcor()-move_speed)
  if you.xcor()< -200:
    you.setx(200)
  print(str(you.xcor())+','+str(you.ycor()))
  findbox(xold,yold)
def right():
  xold = you.xcor()
  yold = you.ycor()
  you.setx(you.xcor()+move_speed)
  if you.xcor()> 200:
    you.setx(-200)
  print(str(you.xcor())+','+str(you.ycor()))
  findbox(xold,yold)
def jump():
  up()
  up()
  up()
  time.sleep(0.1)
  down()
  down()
  down()
  

##MOVEMENT CODE FOR SPRITE 2 (THEM)
def up2():
  xold2 = them.xcor()
  yold2 = them.ycor()
  them.sety(them.ycor()+move_speed)
  if them.ycor()> 200:
    them.sety(-200)
  print(str(them.xcor())+','+str(them.ycor()))
  findbox(xold2,yold2)
def down2():
  xold2 = them.xcor()
  yold2 = them.ycor()
  them.sety(them.ycor()-move_speed)
  if them.ycor()< -200:
    them.sety(200)
  print(str(them.xcor())+','+str(them.ycor()))
  findbox(xold2,yold2)
def left2():
  xold2 = them.xcor()
  yold2 = them.ycor()
  them.setx(them.xcor()-move_speed)
  if them.xcor()< -200:
    them.setx(200)
  print(str(them.xcor())+','+str(them.ycor()))
  findbox(xold2,yold2)
def right2():
  xold2 = them.xcor()
  yold2 = them.ycor()
  them.setx(them.xcor()+move_speed)
  if them.xcor()> 200:
    them.setx(-200)
  print(str(them.xcor())+','+str(them.ycor()))
  findbox(xold2,yold2)
def jump2():
  up2()
  up2()
  up2()
  time.sleep(0.1)
  down2()
  down2()
  down2()
  
  
  
def findbox(xold, yold):
  if map == 1:
    coords = [
    [30,90,90,180],
    [10,120,30,70],
    [160,200,-10,70],
    [-160,-20,20,70],
    [-200,-180,20,80],
    [-80,-10,100,180],
    [-170,-120,100,200],
    [-190,-100,-80,-30],
    [-40,10,-90,-40]]
  if map == 7:
     coords = [
    [10,180,-110,-70],
    [10,180,-160,-120],
    [10,180,-180,-160],
    [-80,0,-180,-60],
    [-190,-90,-170,-60],
    [120,200,70,200],
    [20,70,80,190],
    [-160,-20,120,190],
    [-170,-120,70,100],
    [-120,-80,70,100],
    [-70,-30,70,100]]


  sprites = [you, them]
  for i in sprites:
    for j in coords:
      if i.xcor() > j[0] and i.xcor() < j[1]: 
        if i.ycor() > j[2] and i.ycor() < j[3]:
          print('you are in the box')
          i.setx(xold)
          i.sety(yold)
   
def fly(ball):
  global direction
  ball.hideturtle()
  ball.setx(you.xcor())
  ball.sety(you.ycor())
  ball.pendown()
  if direction == "up":
    ball.sety(200)
  if direction == "down":
    ball.sety(-200)
  if direction == "left":
    ball.setx(-200)
  if direction == "right":
    ball.setx(200)
  ball.penup()
  ball.showturtle()

you.penup()
you.speed(0)
you.home()
you.left(90)

them.penup()
them.speed(0)
them.home()
them.left(90)

screen.onkey(up, "Up")
screen.onkey(down, "Down")
screen.onkey(left, "Left")
screen.onkey(right, "Right")
screen.onkey(jump,"Space")

screen.onkey(up2, "w")
screen.onkey(down2, "s")
screen.onkey(left2, "a")
screen.onkey(right2, "d")
screen.onkey(jump2,"x")
screen.listen()

GPS Code for USB Receiver

import serial
gpsPort = "/dev/ttyACM0"
gpsSerial = serial.Serial(gpsPort, baudrate = 9600, timeout = 0.5)

def parseGPS(data):
    gps = data

    try:        
        if gps[2:8] == "$GNGGA":
            gps = gps.split(",")

            timeHour = (int(gps[1][0:2]) - 4) % 24
            timeMin = int(gps[1][2:4])
            timeSec = int(gps[1][4:6])
            print("Time: " + str(timeHour) + ":" + str(timeMin) + ":" + str(timeSec))

            latDeg = int(gps[2][0:2])
            latMin = int(gps[2][2:4])
            latSec = float(gps[2][5:9]) * (3/500)
            latNS = gps[3]
            print("Latitude:  " + str(latDeg) + "°" + str(latMin) + "'" + str(latSec) + '" ' + latNS)

            longDeg = int(gps[4][0:3])
            longMin = int(gps[4][3:5])
            longSec = float(gps[4][6:10]) * (3/500)
            longEW = gps[5]
            print("Longitude:  " + str(longDeg) + "°" + str(longMin) + "'" + str(longSec) + '" ' + longEW)

            alt = float(gps[9])
            print("Altitude: " + str(alt) + " m")

            sat = int(gps[7])
            print("Satellites: " + str(sat))
        if gps[2:8] == "$GNRMC":
            gps = gps.split(",")

            speed = float(gps[7]) * 1.852
            print("Speed: " + str(speed) + " km/h")
            
            head = float(gps[8])
            print("Heading: " + str(head))
        else:
            gps = ""
    except Exception as error:
        print(error)

    return gps
while True:
    print(parseGPS(gpsSerial.readline()))

Current Combined Code


import os
import picamera
import sense_hat
import time
import yagmail

camera = picamera.PiCamera()
camera.resolution = (1280, 720)
framerate = 5
camera.framerate = framerate
camera.annotate_text_size = 18

senseHat = sense_hat.SenseHat()

gps = "GPS Data"

def annotate():
    timeNow = "Time: " + str(time.strftime("%a %d %b %Y %H:%M:%S", time.localtime()))
    temperatureNow = "Temperature: " + str(round(senseHat.get_temperature())) + " C"
    humidityNow = "Humidity: " + str(round(senseHat.get_humidity())) + "%"
    locationNow = "Location: " +gps
    
    annotation = timeNow + "\n" + temperatureNow + "\n" + humidityNow + "\n" + locationNow
    return annotation

def getPicture(annotation):
    filename = "/home/pi/Pictures/" + str(time.strftime("%Y-%m-%d@%H:%M:%S", time.localtime())) + ".jpg"

    try:
        camera.start_preview()
        time.sleep(5)
        camera.annotate_text = annotation
        camera.capture(filename)
        camera.stop_preview()
    except Exception as error:
        print(error)

    return filename

def getVideo(length):
    filename = "/home/pi/Videos/" + str(time.strftime("%Y-%m-%d@%H:%M:%S", time.localtime())) + ".mp4"
    
    try:
        camera.start_recording("/home/pi/testVideo.h264")

        for index in range(length):
            camera.annotate_text = (annotate())
            time.sleep(1)
        
        camera.stop_recording()
    except Exception as error:
        print(error)

    os.system("ffmpeg -r " + str(framerate) + " -i /home/pi/testVideo.h264 -vcodec copy " + filename)

    return filename

def sendMail(filename):
    receiver = ["yoimgeorge25@gmail.com", "otheremail@gmail.com"]
    body = "Sent at " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "."

    try:
        gmail = yagmail.SMTP("email@gmail.com", "password")

        gmail.send(
            to = receiver,
            subject = "Paul's Balloon",
            contents = body, 
            attachments = filename
        )
    except Exception as error:
        print(error)

    print("Message sent.")

sendMail(getPicture(annotate()))