main.py 1.62 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
import pygame
import serial
import random

from gameobjects import *

ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=0.01)
print(ser)

class AppBreathingGame(AppGame):

    RESOLUTION = [640, 480]
    FRAMERATE = 0

    background_color = (0, 0, 0)

    def on_setup(self):
        self.player = Player(app=self, size=[50, 50], color=[0, 255, 0],
                        pos=[150, 200],
                        vel=[0, 0])

        self.asteroid = Asteroid(app=self, size=[50, 50], color=[255, 0, 0],
                               pos=[400, 300],
                               vel=[-300, 0])

    def on_gameloop(self):
        self.player.update()
        self.asteroid.update()

        self.screen.fill(self.background_color)
        self.player.draw(self.screen)
        self.asteroid.draw(self.screen)


class Player(Sprite):
    si, sf = 500, 600
    H = 480

    def update(self):
        self.run(self.app.dt)
        self.read_serial()

    def read_serial(self):
        try:
            ser.write(b'p')
            n = int(ser.readline())
            self.y = self.H * (1.0 - (self.sf - n)/(self.sf - self.si))
            print(n, self.y)
        except:
            pass


class Asteroid(Sprite):
    def update(self):
        self.run(self.app.dt)
        # print(self.x, self.y, self.pos)
        if self.x < 0:
            self.init_pos()
        if self.rectcollide_with(self.app.player):
            print(self.pos)
            # print('BOOM!')

    def init_pos(self):
        self.x = self.app.RESOLUTION[0]
        self.y = random.randint(0, self.app.RESOLUTION[1] - self.w)


if __name__ == '__main__':
    AppBreathingGame().run()