def __init__(self, resolution): '''Настройка pygame дисплея''' self.resolution = resolution self.background = pygame.Surface(self.resolution) self.background.fill((254, 65, 43)) pygame.init() self.screen = pygame.display.set_mode(self.resolution, pygame.FULLSCREEN) self.init() '''Список хендлеров''' self.keydown_handlers = defaultdict(list) self.keyup_handlers = defaultdict(list) self.mouse_handlers = [] '''Камера и объекты''' self.camera = Camera(self.resolution) self.objects = pygame.sprite.Group() self.mobs = pygame.sprite.Group() '''Создание игрока''' self.player = Player(80, 120, self) self.player.set_controller(self.keydown_handlers, self.keyup_handlers, self.mouse_handlers) self.objects.add(self.player) '''Мировые эффекты и события''' self.action_list = [] '''Добавляю тест-объекты''' for i in range(2): brick = Brick(32 + config.width_brick * i * 2, 360, self) self.objects.add(brick) mob = Mob(32, 180 + config.width_mob * i * 2, self) self.objects.add(mob) self.mobs.add(mob) self.camera.apply(self.objects)
class BackCameraWindow(QMainWindow, blank_window.Ui_BlankWindow): def __init__(self): super(self.__class__, self).__init__() self.setupUi(self) #przypisuje konkretną funkcję do przycisku i sygnał self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.setStyleSheet(open("resources/style.qss", "r").read()) self.show() self.Back.clicked.connect(lambda: self.closeBackCamcorderStream()) #tworze etykiete, w której wyświetlą się ramki QPixmap "pobrane" z kamerki self.VideoLabel = QLabel(self) #ustalam pozycję i wymiary: x, y, szerokość, wysokość self.VideoLabel.setGeometry(QtCore.QRect(0, 0, 840, 540)) #Rysuję przycisk zrób zdjęcie self.TakePhoto=RadioPlayWindow.drawControlFMButton(self,"TakePhoto",860,160,"#26d8fc","camera.png") self.TakePhoto.clicked.connect(lambda: self.takePhoto()) self.TakePhoto.show() #dodaje rysowanie etykiety self.TakePhotoLabel=RadioPlayWindow.drawControlButtonLabel(self,860,320,"Zrób zdjęcie") self.TakePhotoLabel.show() #tworze nowy wątek self.ThreadStream = QThread() #tworzę obiekt, który dziedziczy po QObject #dzięki niemu będzie możliwość obsługi slotów i sygnałów self.WorkerStream = Camera("/dev/BackCamcorder") #jeśli obiekt klasy Camera wyślę sygnał "StreamSignal", który zawiera w sobie obiekt QPixmap #to funkcja streamFromBackWebcam() go obsłuży #czyli "wklei" go do etykiety VideoLabel, a potem tę etykietę wyświetli self.WorkerStream.StreamSignal.connect(self.streamFromBackWebcam) #przenoszę obiekt WorkerStream do nowego wątku self.WorkerStream.moveToThread(self.ThreadStream) #jeśli obiekt klasy Camera, wyślę sygnał FinishedSignal, to wątek, który obsługiwał streamowanie się zakończy self.WorkerStream.FinishedSignal.connect(self.ThreadStream.quit) #jeśli nowy wątek zostanie uruchomiony to #zostanie wykonana funkcja startCamcorderStream() z klasy Camera self.ThreadStream.started.connect(self.WorkerStream.startCamcorderStream) #uruchamiam nowy wątek self.ThreadStream.start() #funkcja zamykająca stream z kamerki def closeBackCamcorderStream(self): os.system("rm temp/stream") self.close() #slot, który wyświetla w etykiecie VideoLabel obiekt QPixmap otrzymany od obiektu klasy Camera def streamFromBackWebcam(self,ResizedFrame): self.VideoLabel.setPixmap(ResizedFrame) self.VideoLabel.show() def takePhoto(self): os.system("touch temp/photo")
def __init__(self, x, y, level, screen, dashboard, sound, gravity=0.75): super(Mario, self).__init__(x, y, gravity) self.spriteCollection = Sprites().spriteCollection self.camera = Camera(self.rect, self) self.sound = sound self.input = Input(self) self.inAir = False self.inJump = False self.animation = Animation( [ self.spriteCollection["mario_run1"].image, self.spriteCollection["mario_run2"].image, self.spriteCollection["mario_run3"].image, ], self.spriteCollection["mario_idle"].image, self.spriteCollection["mario_jump"].image, ) self.traits = { "jumpTrait": jumpTrait(self), "goTrait": goTrait(self.animation, screen, self.camera, self), "bounceTrait": bounceTrait(self), } self.levelObj = level self.collision = Collider(self, level) self.screen = screen self.EntityCollider = EntityCollider(self) self.dashboard = dashboard self.restart = False self.pause = False self.pauseObj = Pause(screen, self, dashboard)
class FrontCamcorderWindow(QMainWindow, blank_window.Ui_BlankWindow): def __init__(self): super(self.__class__, self).__init__() self.setupUi(self) self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.setStyleSheet(open("resources/style.qss", "r").read()) #wyświetlam pusty formularz, na którym się wyświetli stream z kamery self.show() self.Back.clicked.connect(lambda: self.closeFrontCamcorderStream()) #tworze etykiete, w której wyświetlą się ramki QPixmap "pobrane" z kamerki self.VideoLabel = QLabel(self) #ustalam pozycję i wymiary: x, y, szerokość, wysokość self.VideoLabel.setGeometry(QtCore.QRect(0, 0, 840, 540)) #tworze nowy wątek self.ThreadStream = QThread() #tworzę obiekt, który dziedziczy po QObject #dzięki niemu będzie możliwość obsługi slotów i sygnałów self.WorkerStream = Camera("/dev/FrontCamcorder") #jeśli obiekt klasy Camera wyślę sygnał "StreamSignal", który zawiera w sobie obiekt QPixmap #to funkcja streamFromFrontWebcam() go obsłuży #czyli "wklei" go do etykiety VideoLabel, a potem tę etykietę wyświetli self.WorkerStream.StreamSignal.connect(self.streamFromFrontWebcam) #przenoszę obiekt WorkerStream do nowego wątku self.WorkerStream.moveToThread(self.ThreadStream) #jeśli obiekt klasy Camera, wyślę sygnał FinishedSignal, to wątek, który obsługiwał streamowanie się zakończy self.WorkerStream.FinishedSignal.connect(self.ThreadStream.quit) #jeśli nowy wątek zostanie uruchomiony to #zostanie wykonana funkcja startFrontCamcorderStream() z klasy Camera self.ThreadStream.started.connect(self.WorkerStream.startCamcorderStream) #uruchamiam nowy wątek self.ThreadStream.start() #funkcja zamykająca stream z kamerki def closeFrontCamcorderStream(self): os.system("rm temp/stream") self.close() #slot, który wyświetla w etykiecie VideoLabel obiekt QPixmap otrzymany od obiektu klasy Camera def streamFromFrontWebcam(self,ResizedFrame): self.VideoLabel.setPixmap(ResizedFrame) self.VideoLabel.show()
def __init__(self, size, fps, client_name): """ init block """ pygame.init() pygame.font.init() pygame.joystick.init() """ display block """ self.request_list = [] self.resolution = size self.fps = fps self.icon = None self.caption = "Caster-Game" self.screen = pygame.display.set_mode(self.resolution, pygame.RESIZABLE) self.camera = Camera(self.resolution) self.camera_target = None self.is_camera_target = False self.name = client_name self.init() """ input block """ # self.joys = [pygame.joystick.Joystick(i) for i in range(pygame.joystick.get_count())] # for j in self.joys: # j.init() """ handlers block """ self.keydown_handlers = defaultdict(list) self.keyup_handlers = defaultdict(list) self.mouse_handlers = [] self.event_list = [] """ game const block """ self.play = True self.output = [] """ interface block """ self.buttons = ButtonGroup() """ ingame block """ self.objects = GameGroup() self.background = pygame.Surface(self.resolution) self.background.fill((254, 65, 43)) self.session = None
def __init__(self, x, y, level, screen, dashboard, sound, gravity=0.75): super(Mario, self).__init__(x, y, gravity) self.x = x self.spriteCollection = Sprites().spriteCollection self.CT = CollisionTester() self.camera = Camera(self.rect, self) self.sound = sound self.level = level self.OI = Input(self) self.closest_mob = None self.closest_object = None self.output =0 self.inAir = False self.brain = Model().share_memory() self.fitness = 0 self.animation = Animation( [ self.spriteCollection["mario_run1"].image, self.spriteCollection["mario_run2"].image, self.spriteCollection["mario_run3"].image, ], self.spriteCollection["mario_idle"].image, self.spriteCollection["mario_jump"].image, ) self.traits = { "jumpTrait": jumpTrait(self), "goTrait": goTrait(self.animation, screen, self.camera, self), "bounceTrait": bounceTrait(self), } self.levelObj = level self.collision = Collider(self, level) self.screen = screen self.EntityCollider = EntityCollider(self) self.dashboard = dashboard self.restart = False self.pause = False self.pauseObj = Pause(screen, self, dashboard)
def __init__(self, x, y, level, screen, dashboard, sound, gravity=0.75): super(Mario, self).__init__(x, y, gravity) self.camera = Camera(self.rect, self) self.sound = sound self.input = Input(self) self.inAir = False self.inJump = False self.powerUpState = 0 self.invincibilityFrames = 0 self.traits = { "jumpTrait": JumpTrait(self), "goTrait": GoTrait(smallAnimation, screen, self.camera, self), "bounceTrait": bounceTrait(self), } self.levelObj = level self.collision = Collider(self, level) self.screen = screen self.EntityCollider = EntityCollider(self) self.dashboard = dashboard self.restart = False self.pause = False self.pauseObj = Pause(screen, self, dashboard)
def __init__(self, x, y, level, screen, dashboard, gravity=1.25): super(Mario, self).__init__(x, y, gravity) self.spriteCollection = Sprites().spriteCollection self.camera = Camera(self.rect, self) self.sound = Sound() self.animation = Animation([ self.spriteCollection["mario_run1"].image, self.spriteCollection["mario_run2"].image, self.spriteCollection["mario_run3"].image ], self.spriteCollection["mario_idle"].image, self.spriteCollection["mario_jump"].image) self.traits = { "jumpTrait": jumpTrait(self), "goTrait": goTrait(self.animation, screen, self.camera, self), "bounceTrait": bounceTrait(self) } self.levelObj = level self.collision = Collider(self, level) self.screen = screen self.EntityCollider = EntityCollider(self) self.dashboard = dashboard self.restart = False
class Mario(EntityBase): def __init__(self, x, y, level, screen, dashboard, sound, gravity=0.75): super(Mario, self).__init__(x, y, gravity) self.spriteCollection = Sprites().spriteCollection self.camera = Camera(self.rect, self) self.sound = sound self.input = Input(self) self.inAir = False self.inJump = False self.animation = Animation( [ self.spriteCollection["mario_run1"].image, self.spriteCollection["mario_run2"].image, self.spriteCollection["mario_run3"].image, ], self.spriteCollection["mario_idle"].image, self.spriteCollection["mario_jump"].image, ) self.traits = { "jumpTrait": jumpTrait(self), "goTrait": goTrait(self.animation, screen, self.camera, self), "bounceTrait": bounceTrait(self), } self.levelObj = level self.collision = Collider(self, level) self.screen = screen self.EntityCollider = EntityCollider(self) self.dashboard = dashboard self.restart = False self.pause = False self.pauseObj = Pause(screen, self, dashboard) def update(self): self.updateTraits() self.moveMario() self.camera.move() self.applyGravity() self.checkEntityCollision() self.input.checkForInput() def moveMario(self): self.rect.y += self.vel.y self.collision.checkY() self.rect.x += self.vel.x self.collision.checkX() def checkEntityCollision(self): for ent in self.levelObj.entityList: collisionState = self.EntityCollider.check(ent) if collisionState.isColliding: if ent.type == "Item": self._onCollisionWithItem(ent) elif ent.type == "Block": self._onCollisionWithBlock(ent) elif ent.type == "Mob": self._onCollisionWithMob(ent, collisionState) def _onCollisionWithItem(self, item): self.levelObj.entityList.remove(item) self.dashboard.points += 100 self.dashboard.coins += 1 self.sound.play_sfx(self.sound.coin) def _onCollisionWithBlock(self, block): if not block.triggered: self.dashboard.coins += 1 self.sound.play_sfx(self.sound.bump) block.triggered = True def _onCollisionWithMob(self, mob, collisionState): if collisionState.isTop and (mob.alive or mob.alive == "shellBouncing"): self.sound.play_sfx(self.sound.stomp) self.rect.bottom = mob.rect.top self.bounce() self.killEntity(mob) elif collisionState.isTop and mob.alive == "sleeping": self.sound.play_sfx(self.sound.stomp) self.rect.bottom = mob.rect.top mob.timer = 0 self.bounce() mob.alive = False elif collisionState.isColliding and mob.alive == "sleeping": if mob.rect.x < self.rect.x: mob.leftrightTrait.direction = -1 mob.rect.x += -5 else: mob.rect.x += 5 mob.leftrightTrait.direction = 1 mob.alive = "shellBouncing" elif collisionState.isColliding and mob.alive: self.gameOver() def bounce(self): self.traits["bounceTrait"].jump = True def killEntity(self, ent): if ent.__class__.__name__ != "Koopa": ent.alive = False else: ent.timer = 0 ent.alive = "sleeping" self.dashboard.points += 100 def gameOver(self): srf = pygame.Surface((640, 480)) srf.set_colorkey((255, 255, 255), pygame.RLEACCEL) srf.set_alpha(128) self.sound.music_channel.stop() self.sound.music_channel.play(self.sound.death) for i in range(500, 20, -2): srf.fill((0, 0, 0)) pygame.draw.circle( srf, (255, 255, 255), (int(self.camera.x + self.rect.x) + 16, self.rect.y + 16), i, ) self.screen.blit(srf, (0, 0)) pygame.display.update() self.input.checkForInput() while self.sound.music_channel.get_busy(): pygame.display.update() self.input.checkForInput() self.restart = True def getPos(self): return self.camera.x + self.rect.x, self.rect.y def setPos(self, x, y): self.rect.x = x self.rect.y = y
import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from classes.Camera import Camera, PICAMERA, USB import os from time import sleep import cv2 from PIL import Image import numpy as np import io from time import time c = Camera(USB, camera_num=2, resolution=(320, 240), framerate=15, rotation=-1) c.start() framerate = [0, 0] start = time() while True: if c.ready and c.more(): framerate[1] += 1 frame = c.get_frame() if frame is not None: cv2.imshow("camera_r", frame) #stream.seek(0) key = cv2.waitKey(1) & 0xFF if time() - start > 1: framerate = [sum(framerate) / 2, 0] start = time()
class Client: def __init__(self, size, fps, client_name): """ init block """ pygame.init() pygame.font.init() pygame.joystick.init() """ display block """ self.request_list = [] self.resolution = size self.fps = fps self.icon = None self.caption = "Caster-Game" self.screen = pygame.display.set_mode(self.resolution, pygame.RESIZABLE) self.camera = Camera(self.resolution) self.camera_target = None self.is_camera_target = False self.name = client_name self.init() """ input block """ # self.joys = [pygame.joystick.Joystick(i) for i in range(pygame.joystick.get_count())] # for j in self.joys: # j.init() """ handlers block """ self.keydown_handlers = defaultdict(list) self.keyup_handlers = defaultdict(list) self.mouse_handlers = [] self.event_list = [] """ game const block """ self.play = True self.output = [] """ interface block """ self.buttons = ButtonGroup() """ ingame block """ self.objects = GameGroup() self.background = pygame.Surface(self.resolution) self.background.fill((254, 65, 43)) self.session = None def init(self): '''Нужно для загрузки изображений''' gameconsts.image_player = load_image("..//..//resources//green.png") gameconsts.image_brick = load_image("..//..//resources//brick.png") gameconsts.image_mob = load_image("..//..//resources//red.png") gameconsts.image_bullet = load_image("..//..//resources//blue8x8.png") gameconsts.init() self.camera_target = ClientGameObject(0, 0, 3, -1) def set_caption(self, caption): self.caption = caption pygame.display.set_caption(self.caption) def set_icon(self, img): self.icon = img pygame.display.set_icon(img) def load_icon(self, icon): self.icon = pygame.image.load(icon) def set_resolution(self, resolution): self.resolution = resolution self.screen = pygame.display.set_mode(resolution) self.camera.set_size(resolution) def handler(self): for event in pygame.event.get(): if event.type == pygame.MOUSEMOTION: cam_pos = (self.camera.global_rect.x, self.camera.global_rect.y) pos = (cam_pos[0] + event.pos[0], cam_pos[1] + event.pos[1]) packet = [pygame.MOUSEMOTION, pos] self.output.append(packet) elif event.type in {pygame.KEYUP, pygame.KEYDOWN}: packet = [event.type, event.key] self.output.append(packet) elif event.type in {pygame.MOUSEBUTTONUP, pygame.MOUSEBUTTONDOWN}: packet = [event.type, event.button] self.output.append(packet) else: pass def update_display(self): self.screen.blit(self.background, (0, 0)) self.camera.update(self.camera_target) self.camera.apply(self.objects) self.objects.draw(self.screen) self.buttons.draw(self.screen) pygame.display.flip() def connect_to_server(self, host, port): self.session = TCPClientConnection(host, port) self.session.connect() self.session.start() def create_object(self, packet): cl_obj = ClientGameObject(packet[3][0], packet[3][1], packet[1], packet[2]) if (not self.is_camera_target) and (cl_obj.class_id == 3): self.camera_target = cl_obj self.is_camera_target = True self.objects[cl_obj.id] = cl_obj print('Object {} from packet {}'.format(object, packet)) def move_object(self, packet): self.objects[packet[1]].x = packet[2][0] self.objects[packet[1]].y = packet[2][1] def remove_object(self, packet): del self.objects[packet[1]] print('deleted {}'.format(packet[1])) def send(self): """send information to server""" output = copy.copy(self.output) self.session.send(output) self.output.clear() self.request_list.clear() def receive(self): """receive information from server""" data = self.session.get_input() for packet in data: if packet[0] == 0: self.create_object(packet) elif packet[0] == 1: try: self.move_object(packet) except KeyError: request = ['request', packet[1]] '''Проверка на то, что мы еще не отправляли этот запрос на данном тике''' if packet[1] not in self.request_list: self.request_list.append(packet[1]) print('request for {}'.format(packet[1])) self.output.append(request) elif packet[0] == 2: try: self.remove_object(packet) except KeyError: print('Object with id {} doesn\'t exist'.format(packet[1]))
class Mario(EntityBase): def __init__(self, x, y, level, screen, dashboard, sound, gravity=1.25): super(Mario, self).__init__(x, y, gravity) self.spriteCollection = Sprites().spriteCollection self.camera = Camera(self.rect, self) self.sound = sound self.input = Input(self) self.animation = Animation([ self.spriteCollection["mario_run1"].image, self.spriteCollection["mario_run2"].image, self.spriteCollection["mario_run3"].image ], self.spriteCollection["mario_idle"].image, self.spriteCollection["mario_jump"].image) self.traits = { "jumpTrait": jumpTrait(self), "goTrait": goTrait(self.animation, screen, self.camera, self), "bounceTrait": bounceTrait(self) } self.levelObj = level self.collision = Collider(self, level) self.screen = screen self.EntityCollider = EntityCollider(self) self.dashboard = dashboard self.restart = False def update(self): self.updateTraits() self.moveMario() self.camera.move() self.applyGravity() self.checkEntityCollision() self.input.checkForInput() def moveMario(self): self.rect.y += self.vel.y self.collision.checkY() self.rect.x += self.vel.x self.collision.checkX() def checkEntityCollision(self): for ent in self.levelObj.entityList: collisionState = self.EntityCollider.check(ent) if collisionState.isColliding: if (ent.type == "Item"): self._onCollisionWithItem(ent) elif (ent.type == "Block"): self._onCollisionWithBlock(ent) elif (ent.type == "Mob"): self._onCollisionWithMob(ent, collisionState) def _onCollisionWithItem(self, item): self.levelObj.entityList.remove(item) self.dashboard.points += 100 self.dashboard.coins += 1 self.sound.play_sfx(self.sound.coin) def _onCollisionWithBlock(self, block): if (not block.triggered): self.sound.play_sfx(self.sound.bump) block.triggered = True def _onCollisionWithMob(self, mob, collisionState): if collisionState.isTop and (mob.alive is True or mob.alive == "shellBouncing"): self.sound.play_sfx(self.sound.stomp) self.rect.bottom = mob.rect.top self.bounce() self.killEntity(mob) elif collisionState.isTop and mob.alive == "sleeping": self.sound.play_sfx(self.sound.stomp) self.rect.bottom = mob.rect.top mob.timer = 0 self.bounce() mob.alive = False elif collisionState.isTop and mob.alive == "sleeping": if (mob.rect.x < self.rect.x): mob.leftrightTrait.direction = -1 else: mob.leftrightTrait.direction = 1 mob.alive = "shellBouncing" elif collisionState.isColliding and mob.alive == True: self.gameOver() def bounce(self): self.traits['bounceTrait'].jump = True def killEntity(self, ent): if ent.__class__.__name__ != "Koopa": ent.alive = False else: ent.timer = 0 ent.alive = "sleeping" self.dashboard.points += -1000 def gameOver(self): srf = pygame.Surface((640, 480)) srf.set_colorkey((255, 255, 255), pygame.RLEACCEL) srf.set_alpha(128) self.sound.music_channel.stop() self.sound.music_channel.play(self.sound.death) # for i in range(500, 20, -2): # srf.fill((0, 0, 0)) # pygame.draw.circle( # srf, (255, 255, 255), (int( # self.camera.x + self.rect.x) + 2, self.rect.y + 2), i) # self.screen.blit(srf, (0, 0)) # pygame.display.update() # self.input.checkForInput() # while(self.sound.music_channel.get_busy()): # pygame.display.update() # self.input.checkForInput() self.restart = True def getPos(self): return (self.camera.x + self.rect.x, self.rect.y) def doRandomMove(self): moves = ['moveLeft', 'moveRight', 'jump', 'doNothing'] random_move = random.choice(moves) if random_move == 'moveLeft': self.traits['goTrait'].direction = -1 elif random_move == 'moveRight': self.traits['goTrait'].direction = 1 elif random_move == 'jump': self.traits['jumpTrait'].start() elif random_move == 'doNothing': self.traits['goTrait'].direction = 0
if __name__ == "__main__": setup_files_and_folders() screen_width = int(root.winfo_screenwidth()) screen_height = int(root.winfo_screenheight()) root.geometry(f"600x800") # root.geometry(f"{screen_width}x{screen_height}") actions = { "take_pictures": photobooth_workflow, "not_print": reset_ui, "print": print_photo } camera = Camera( root_dir=ROOT_DIR, on_error=show_error ) photobooth_ui = PhotoboothUi(master=root, actions=actions) photobooth_ui.home_screen.pack(expand=True, fill='both') countdown = Countdown(master=root) root.bind("<KeyPress>", photobooth_workflow) root.bind("<KeyPress>", quit_) root.mainloop() sys.exit(0)
class Mario(EntityBase): def __init__(self, x, y, level, screen, dashboard, sound, gravity=0.75): super(Mario, self).__init__(x, y, gravity) self.x = x self.spriteCollection = Sprites().spriteCollection self.CT = CollisionTester() self.camera = Camera(self.rect, self) self.sound = sound self.level = level self.OI = Input(self) self.closest_mob = None self.closest_object = None self.output =0 self.inAir = False self.brain = Model().share_memory() self.fitness = 0 self.animation = Animation( [ self.spriteCollection["mario_run1"].image, self.spriteCollection["mario_run2"].image, self.spriteCollection["mario_run3"].image, ], self.spriteCollection["mario_idle"].image, self.spriteCollection["mario_jump"].image, ) self.traits = { "jumpTrait": jumpTrait(self), "goTrait": goTrait(self.animation, screen, self.camera, self), "bounceTrait": bounceTrait(self), } self.levelObj = level self.collision = Collider(self, level) self.screen = screen self.EntityCollider = EntityCollider(self) self.dashboard = dashboard self.restart = False self.pause = False self.pauseObj = Pause(screen, self, dashboard) def getInputs(self): map = [] input = [] for x in range(60): map.append(self.CT.test(x, 11, self.level, self)) if map[x] == 3: map[x] = 0 for x in range(int(self.rect.x/32), int(self.rect.x/32) + 8): input.append(map[x]) return torch.FloatTensor(input) def update(self): self.updateTraits() self.moveMario() self.camera.move() self.applyGravity() self.checkEntityCollision() self.output = self.brain.forward(self.getInputs()) #print(self.output) self.OI.checkForInput(self.output) def moveMario(self): self.rect.y += self.vel.y self.collision.checkY() self.rect.x += self.vel.x self.collision.checkX() def checkEntityCollision(self): for ent in self.levelObj.entityList: collisionState = self.EntityCollider.check(ent) if collisionState.isColliding: if ent.type == "Item": self._onCollisionWithItem(ent) elif ent.type == "Block": self._onCollisionWithBlock(ent) elif ent.type == "Mob": self._onCollisionWithMob(ent, collisionState) def _onCollisionWithItem(self, item): self.levelObj.entityList.remove(item) self.dashboard.points += 100 self.dashboard.coins += 1 self.sound.play_sfx(self.sound.coin) def _onCollisionWithBlock(self, block): if not block.triggered: self.dashboard.coins += 1 self.sound.play_sfx(self.sound.bump) block.triggered = True def _onCollisionWithMob(self, mob, collisionState): if collisionState.isTop and (mob.alive or mob.alive == "shellBouncing"): self.sound.play_sfx(self.sound.stomp) self.rect.bottom = mob.rect.top self.bounce() self.killEntity(mob) elif collisionState.isTop and mob.alive == "sleeping": self.sound.play_sfx(self.sound.stomp) self.rect.bottom = mob.rect.top mob.timer = 0 self.bounce() mob.alive = False elif collisionState.isColliding and mob.alive == "sleeping": if mob.rect.x < self.rect.x: mob.leftrightTrait.direction = -1 mob.rect.x += -5 else: mob.rect.x += 5 mob.leftrightTrait.direction = 1 mob.alive = "shellBouncing" elif collisionState.isColliding and mob.alive: self.gameOver() def bounce(self): self.traits["bounceTrait"].jump = True def killEntity(self, ent): if ent.__class__.__name__ != "Koopa": ent.alive = False else: ent.timer = 0 ent.alive = "sleeping" self.dashboard.points += 100 def gameOver(self): self.restart = True def getPos(self): return self.camera.x + self.rect.x, self.rect.y def setPos(self,x,y): self.rect.x = x self.rect.y = y
class Mario(EntityBase): def __init__(self, x, y, level, screen, dashboard, gravity=1.25): super(Mario, self).__init__(x, y, gravity) self.spriteCollection = Sprites().spriteCollection self.camera = Camera(self.rect, self) self.sound = Sound() self.animation = Animation([ self.spriteCollection["mario_run1"].image, self.spriteCollection["mario_run2"].image, self.spriteCollection["mario_run3"].image ], self.spriteCollection["mario_idle"].image, self.spriteCollection["mario_jump"].image) self.traits = { "jumpTrait": jumpTrait(self), "goTrait": goTrait(self.animation, screen, self.camera, self), "bounceTrait": bounceTrait(self) } self.levelObj = level self.collision = Collider(self, level) self.screen = screen self.EntityCollider = EntityCollider(self) self.dashboard = dashboard self.restart = False def update(self): self.updateTraits() self.moveMario() self.camera.move() self.applyGravity() self.checkEntityCollision() def moveMario(self): self.rect.y += self.vel.y self.collision.checkY() self.rect.x += self.vel.x self.collision.checkX() def checkEntityCollision(self): for ent in self.levelObj.entityList: collission = self.EntityCollider.check(ent) if (collission != False): if (ent.type == "Item"): self.levelObj.entityList.remove(ent) self.dashboard.points += 100 self.dashboard.coins += 1 self.sound.play_sfx(self.sound.coin) elif (ent.type == "Block"): if (not ent.triggered): self.sound.play_sfx(self.sound.bump) ent.triggered = True elif (ent.type == "Mob"): if (collission == "top"): self.sound.play_sfx(self.sound.bump) if collission == "top" and (ent.alive == True or ent.alive == "shellBouncing"): self.rect.bottom = ent.rect.top self.bounce() self.killEntity(ent) elif collission == "top" and ent.alive == "sleeping": self.rect.bottom = ent.rect.top self.bounce() ent.alive = False elif collission and ent.alive == "sleeping": if (ent.rect.x < self.rect.x): ent.leftrightTrait.direction = -1 else: ent.leftrightTrait.direction = 1 ent.alive = "shellBouncing" elif collission and ent.alive == True: self.gameOver() def bounce(self): self.traits['bounceTrait'].jump = True def killEntity(self, ent): if ent.__class__.__name__ != "Koopa": ent.alive = False else: ent.timer = 0 ent.alive = "sleeping" self.dashboard.points += 100 def gameOver(self): srf = pygame.Surface((640, 480)) srf.set_colorkey((255, 255, 255), pygame.RLEACCEL) for i in range(500, 20, -3): srf.fill((0, 0, 0)) pygame.draw.circle(srf, (255, 255, 255), (int(self.camera.pos.x * 32 + self.rect.x) + 16, self.rect.y + 16), i) self.screen.blit(srf, (0, 0)) pygame.display.update() self.restart = True def getPos(self): return (self.camera.pos.x * 32 + self.rect.x, self.rect.y)
class Mario(EntityBase): def __init__(self, x, y, level, screen, dashboard, sound, gravity=0.8): super(Mario, self).__init__(x, y, gravity) self.camera = Camera(self.rect, self) self.sound = sound self.input = Input(self) self.inAir = False self.inJump = False self.powerUpState = 0 self.invincibilityFrames = 0 self.traits = { "jumpTrait": JumpTrait(self), "goTrait": GoTrait(smallAnimation, screen, self.camera, self), "bounceTrait": bounceTrait(self), } self.levelObj = level self.collision = Collider(self, level) self.screen = screen self.EntityCollider = EntityCollider(self) self.dashboard = dashboard self.restart = False self.pause = False self.pauseObj = Pause(screen, self, dashboard) def update(self): if self.invincibilityFrames > 0: self.invincibilityFrames -= 1 self.updateTraits() self.moveMario() self.camera.move() self.applyGravity() self.checkEntityCollision() self.input.checkForInput() def moveMario(self): self.rect.y += self.vel.y self.collision.checkY() self.rect.x += self.vel.x self.collision.checkX() def checkEntityCollision(self): for ent in self.levelObj.entityList: collisionState = self.EntityCollider.check(ent) if collisionState.isColliding: if ent.type == "Item": self._onCollisionWithItem(ent) elif ent.type == "Block": self._onCollisionWithBlock(ent) elif ent.type == "Mob": self._onCollisionWithMob(ent, collisionState) def _onCollisionWithItem(self, item): self.levelObj.entityList.remove(item) self.dashboard.points += 100 self.dashboard.coins += 1 self.sound.play_sfx(self.sound.coin) def _onCollisionWithBlock(self, block): if not block.triggered: self.dashboard.coins += 1 self.sound.play_sfx(self.sound.bump) block.triggered = True def _onCollisionWithMob(self, mob, collisionState): if isinstance(mob, RedMushroom) and mob.alive: self.powerup(1) self.killEntity(mob) self.sound.play_sfx(self.sound.powerup) elif collisionState.isTop and (mob.alive or mob.bouncing): self.sound.play_sfx(self.sound.stomp) self.rect.bottom = mob.rect.top self.bounce() self.killEntity(mob) elif collisionState.isTop and mob.alive and not mob.active: self.sound.play_sfx(self.sound.stomp) self.rect.bottom = mob.rect.top mob.timer = 0 self.bounce() mob.alive = False elif collisionState.isColliding and mob.alive and not mob.active and not mob.bouncing: mob.bouncing = True if mob.rect.x < self.rect.x: mob.leftrightTrait.direction = -1 mob.rect.x += -5 self.sound.play_sfx(self.sound.kick) else: mob.rect.x += 5 mob.leftrightTrait.direction = 1 self.sound.play_sfx(self.sound.kick) elif collisionState.isColliding and mob.alive and not self.invincibilityFrames: if self.powerUpState == 0: self.gameOver() elif self.powerUpState == 1: self.powerUpState = 0 self.traits['goTrait'].updateAnimation(smallAnimation) x, y = self.rect.x, self.rect.y self.rect = pygame.Rect(x, y + 32, 32, 32) self.invincibilityFrames = 60 self.sound.play_sfx(self.sound.pipe) def bounce(self): self.traits["bounceTrait"].jump = True def killEntity(self, ent): if ent.__class__.__name__ != "Koopa": ent.alive = False else: ent.timer = 0 ent.leftrightTrait.speed = 1 ent.alive = True ent.active = False ent.bouncing = False self.dashboard.points += 100 def gameOver(self): srf = pygame.Surface((640, 480)) srf.set_colorkey((255, 255, 255), pygame.RLEACCEL) srf.set_alpha(128) self.sound.music_channel.stop() self.sound.music_channel.play(self.sound.death) for i in range(500, 20, -2): srf.fill((0, 0, 0)) pygame.draw.circle( srf, (255, 255, 255), (int(self.camera.x + self.rect.x) + 16, self.rect.y + 16), i, ) self.screen.blit(srf, (0, 0)) pygame.display.update() self.input.checkForInput() while self.sound.music_channel.get_busy(): pygame.display.update() self.input.checkForInput() self.restart = True def getPos(self): return self.camera.x + self.rect.x, self.rect.y def setPos(self, x, y): self.rect.x = x self.rect.y = y def powerup(self, powerupID): if self.powerUpState == 0: if powerupID == 1: self.powerUpState = 1 self.traits['goTrait'].updateAnimation(bigAnimation) self.rect = pygame.Rect(self.rect.x, self.rect.y-32, 32, 64) self.invincibilityFrames = 20
import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from classes.Camera import Camera, PICAMERA, USB import os from time import sleep import cv2 from PIL import Image import numpy as np import io from time import time c = Camera(PICAMERA, camera_num=0, resolution=(320, 240), framerate=10, rotation=180) c.start() framerate = [0, 0] start = time() while True: if c.ready and c.more(): framerate[1] += 1 frame = c.get_frame() if frame is not None: cv2.imshow("camera_c", frame) #stream.seek(0) key = cv2.waitKey(1) & 0xFF
class Caster: def __init__(self, resolution): '''Настройка pygame дисплея''' self.resolution = resolution self.background = pygame.Surface(self.resolution) self.background.fill((254, 65, 43)) pygame.init() self.screen = pygame.display.set_mode(self.resolution, pygame.FULLSCREEN) self.init() '''Список хендлеров''' self.keydown_handlers = defaultdict(list) self.keyup_handlers = defaultdict(list) self.mouse_handlers = [] '''Камера и объекты''' self.camera = Camera(self.resolution) self.objects = pygame.sprite.Group() self.mobs = pygame.sprite.Group() '''Создание игрока''' self.player = Player(80, 120, self) self.player.set_controller(self.keydown_handlers, self.keyup_handlers, self.mouse_handlers) self.objects.add(self.player) '''Мировые эффекты и события''' self.action_list = [] '''Добавляю тест-объекты''' for i in range(2): brick = Brick(32 + config.width_brick * i * 2, 360, self) self.objects.add(brick) mob = Mob(32, 180 + config.width_mob * i * 2, self) self.objects.add(mob) self.mobs.add(mob) self.camera.apply(self.objects) def init(self): '''Нужно для загрузки изображений''' config.image_player = load_image("..//resources//green.png") config.image_brick = load_image("..//resources//brick.png") config.image_mob = load_image("..//resources//red.png") config.image_bullet = load_image("..//resources//blue8x8.png") def handler(self): '''Просто хендлер, внутренняя логика игры''' for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() elif event.type == pygame.KEYDOWN: for handler in self.keydown_handlers[event.key]: handler(event.key) elif event.type == pygame.KEYUP: for handler in self.keyup_handlers[event.key]: handler(event.key) elif event.type in {pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP}: for handler in self.mouse_handlers: handler(event.pos, event.button) elif event.type == pygame.MOUSEMOTION: pass elif event.type == config.event_spell: event.spell.cast_spell(self, event.pos) elif event.type == config.event_scroll: event.scroll.use_scroll(self, event.pos) elif event.type == config.event_calculate_behavior: pass def update(self, dt): for action in self.action_list: if not action.is_alive: action.kill(self.action_list) continue action.update(dt) for o in self.objects: collide_objects = collide_sprite(o, self.objects) for obj in collide_objects: obj.on_collision(o) for m in self.mobs: m.calculate_action(target=self.player) for o in self.objects: o.update(dt) self.camera.update(self.player) def render(self): self.screen.blit(self.background, (0, 0)) self.camera.apply(self.objects) self.objects.draw(self.screen) pygame.display.flip() def start(self): clock = pygame.time.Clock() while True: self.handler() self.update(clock.get_time()) self.render() clock.tick(60) print(1000 / clock.get_time())