Pygame window не отвечает

Пайгейм не отвечает, вот код:

from superwires import games, color
games.init(screen_width = 530, screen_height = 600, fps = 60)

#Car sprite
class Car(games.Sprite):
    image = games.load_image("C:/python/car.bmp")
    def __init__(self):
        super(Car, self).__init__(image = Car.image,
                                  x = games.mouse.x,
                                  bottom = games.screen.height - 10)
        self.score = games.Text(value = 0, size = 25, color = color.yellow,
                                top = 5, right = games.screen.width/2)
        games.screen.add(self.score)
    def update(self):
        self.x = games.mouse.x
        if self.left < 65:
            self.left = 65
        if self.right > games.screen.width - 65:
            self.right = games.screen.width - 65

#Bush sprite
class Bush(games.Sprite):
    image = games.load_image("C:/python/bush.bmp")
    speed = 1
    def __init__(self, x = 20, y = 100):
        super(Bush, self).__init__(image = Bush.image,
                                   x = x, y = y,
                                   dy = Bush.speed)
    #Bush spawn algorithm
    def update(self):
        bushes_list = [Bush()]
        while True:
            for bush in bushes_list:
                if bushes_list[0].bottom > games.screen.height/2 and len(bushes_list) < 3:
                    bushes_list.append(Bush(), Bush(515, -100))
                if bushes_list[0].bottom > games.screen.height:
                    bushes_list.pop(0)

#Start
def main(): 
    road = games.load_image("road.jpg", transparent = False)
    games.screen.background = road
    bush1 = Bush()
    bush2 = Bush(515, 100)
    car = Car()
    games.screen.add(bush1)
    games.screen.add(bush2)
    games.screen.add(car)
    games.mouse.is_visible = False
    games.screen.event_grab = True
    games.screen.mainloop()

main()

Ответы (2 шт):

Автор решения: S. Nick

Я совсем не знаю модуля superwires.py, но я точно знаю, что использовать просто так цикл while True в в графическом интерфейсе НЕЛЬЗЯ.

from superwires import games, color                  #  pip install SuperWires
games.init(screen_width = 530, screen_height = 600, fps = 60)

#Car sprite
class Car(games.Sprite):
    image = games.load_image("lena3.png")
    def __init__(self):
        super(Car, self).__init__(image = Car.image,
                                  x = games.mouse.x,
                                  bottom = games.screen.height - 10)
        self.score = games.Text(value = 0, size = 25, color = color.yellow,
                                top = 5, right = games.screen.width/2)
        games.screen.add(self.score)
    def update(self):
        self.x = games.mouse.x
        if self.left < 65:
            self.left = 65
        if self.right > games.screen.width - 65:
            self.right = games.screen.width - 65

#Bush sprite
class Bush(games.Sprite):
    image = games.load_image("Ok.png")
    speed = 1
    def __init__(self, x = 20, y = 100):
        super(Bush, self).__init__(image = Bush.image,
                                   x = x, y = y,
                                   dy = Bush.speed)
    #Bush spawn algorithm
    def update(self):
        bushes_list = [Bush()]
#        while True:
        for bush in bushes_list:
            if bushes_list[0].bottom > games.screen.height/2 and len(bushes_list) < 3:
                bushes_list.append(Bush(), Bush(515, -100))
            if bushes_list[0].bottom > games.screen.height:
                bushes_list.pop(0)

#Start
def main(): 
    road = games.load_image("im.png", transparent = False)
    games.screen.background = road
    bush1 = Bush()
    bush2 = Bush(515, 100)
    car = Car()
    games.screen.add(bush1)
    games.screen.add(bush2)
    games.screen.add(car)
    games.mouse.is_visible = False
    games.screen.event_grab = True
    games.screen.mainloop()

main()

введите сюда описание изображения

→ Ссылка
Автор решения: Александр

Не много подумав я понял что дорога, уходит из под колёс автомобиля в зависимости от скорости... Осталось объекту автомобиль научиться, сообщать о своей скорости, другим объектам. Я думал прикрутить multiproccesing с его трубами, но всё оказалось гораздо проще.

import os
import sys
from random import randint
from superwires import games
import pygame
from pathlib import Path


# Отловить ошибки
def log_uncaught_exceptions(ex_cls, ex, tb):
    text = '{}: {}:\n'.format(ex_cls.__name__, ex)
    import traceback
    text += ''.join(traceback.format_tb(tb))
    print(text)

sys.excepthook = log_uncaught_exceptions



def get_all_files(path, file_format):
    paths = [path for path in [*Path(path).rglob(f'*.{file_format}')]]
    for path in paths:
        yield path

def resource_path(relative):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative)
    else:
        return os.path.join(os.path.abspath("."), relative)


class Car(games.Sprite):
    def __init__(self, call_back):
         super().__init__(games.load_image(resource_path("Images/carx.png")), x=400, y=650, dx=0, dy=0)#normal super init
        self.speed = 0
        self.function = call_back
    def update(self):
        pressed = pygame.key.get_pressed()
        self.angle = 0
        if pressed[pygame.K_LEFT]:
            if self.speed == 0:
                self.angle = -10
                return
            else:
                if self.speed <= 50:
                    self.x -= 1.5
                    self.angle = -10
                elif self.speed <= 75:
                    self.x -= 2.5
                    self.angle = -10
                else:
                    self.x -= 5
                    self.angle = -10
        if pressed[pygame.K_RIGHT]:
            if self.speed == 0:
                self.angle = +10
                return
            else:
                if self.speed <= 50:
                    self.x += 1.5
                    self.angle = + 10
                elif self.speed <= 75:
                    self.x += 2.5
                    self.angle = + 10
                elif self.speed <= 125:
                    self.x += 5
                    self.angle = +10
        if self.left < 80:
            self.left = 80
            self.angle = 0
        if self.right > games.screen.width - 65:
            self.right = games.screen.width - 65
            self.angle = 0

        if pressed[pygame.K_UP]:
            self.speed += 0.1
            if self.speed >= 110:
                self.speed = 110
        if pressed[pygame.K_DOWN]:
            self.speed -= 0.1
            if self.speed > 75:
                self.angle =+ 15
                self.x += 0.1
            if self.speed <= 0:
                self.speed = 0
        self.send_signal(self.function)

    def send_signal(self, call_back):
        call_back(self.speed)


class Road(games.Sprite):
    def __init__(self, x=0, y=0, bottom=0, dy=5):
        self.road = games.load_image(resource_path("Images/roadxx.png"))
        super().__init__(self.road, x=x, y=y, left=5, bottom=bottom, dx=0, dy=dy)#normal super init
    def update(self):
        if self.dy > 25:
            self.dy = 25
        if self.bottom > 1600:
            self.bottom = 800


class Bush(games.Sprite):
    def __init__(self, x=-100, y=-100):

        self.bush = games.load_image(resource_path("Images/bush.png"))
        super().__init__(self.bush, x=x, y=y, dx=0, dy=0, is_collideable=False)#normal super init
    def update(self):
        if self.bottom >= 900:
            if self.x < 110:
                self.x = randint(0, 150)
                self.y = randint(-500, -100)
            else:
                self.x = randint(680, 800)
                self.y = randint(-500, -100)

class Game:
    def __init__(self):
        pygame.display.set_caption("Car racing")
        games.init(screen_width=800, screen_height=800, fps=150)
        #pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        games.screen.background=games.load_image(resource_path('Images/bg.png'), transparent=False)

        self.road = Road(bottom=800, dy=0)
        player = Car(call_back=self.handler)

        games.screen.add(self.road)
        games.screen.add(player)


        self.list_bush_left = [Bush(randint(0, 150), randint(0, 800)) for _ in range(4)]
        map(games.screen.add, list(iter(self.list_bush_left)))
        """
        for bush in self.list_bush_left:
            games.screen.add(bush)
        """

        self.list_bush_right = [Bush(randint(680, 800), randint(0, 800)) for _ in range(3)]
        """
        for bush in self.list_bush_right:
            games.screen.add(bush)
        """

    def handler(self, value):
        print(value)
        self.road.dy = value / 9
        for bush in self.list_bush_left:
            bush.dy = value / 9
        for bush in self.list_bush_right:
            bush.dy = value / 9

    def mainloop(self):
        return games.screen.mainloop()

def main():
    game = Game()
    game.mainloop()

main()
input("Что-бы закрыть консоль, нажмите Enter...")

P.S изображение с дорогой (800, 2400) введите сюда описание изображения введите сюда описание изображения введите сюда описание изображения введите сюда описание изображения введите сюда описание изображения

→ Ссылка