Neefektivní kód – Python – Fórum – Programujte.com
 x   TIP: Přetáhni ikonu na hlavní panel pro připnutí webu
Reklama
Reklama

Neefektivní kód – Python – Fórum – Programujte.comNeefektivní kód – Python – Fórum – Programujte.com

 

Spuštěný nový filmový web Filmožrouti.cz — vše o Avengers, Pacific Rim, Thor, Star Wars…
jare Q0
Duch
12. 10. 2018   #1
-
0
-

Zdravím, pokouším se napsat takovou menší hru, problém je, že je můj kód neefektivní, už při vytvoření více jak 500 aut, které se dokážou pohybovat směrem dopředu je problém s výkonem. Ještě nemají implementovanou ani logiku, ani kolize.

Auta jsou vykreslovány pouze pomocí polygonů a úseček. Používám knihovnu pygame.

Mohl by mi někdo poradit, kde je problém?

import pygame
from copy import copy
from math import *



class Camera:

    def __init__(self, zoom):

        pygame.init()
        self.screen = pygame.display.set_mode((1500, 800))
        self.clock = pygame.time.Clock()
        self.fps = 60
        self.zoom = zoom
        self.w, self.h = pygame.display.get_surface().get_size()
        self.mouse = []
        self.min_zoom = 0.5
        self.max_zoom = 8
        self.end_zoom = 1

    def frame(self):
        self.zooming()
        pygame.display.update()
        self.clock.tick(self.fps)
        self.screen.fill((250, 250, 250))
        self.fixMouse()

    def transform(self, points):
        trans_points = []
        for point in points:
            point_0 = ((point[0] - room.car.coordinates[0]) * self.zoom + self.w / 2)
            point_1 = ((point[1] - room.car.coordinates[1]) * self.zoom + self.h / 2)
            trans_points.append([point_0, point_1])

        return trans_points

    def fixMouse(self):
        self.mouse = [(pygame.mouse.get_pos()[0] - self.w / 2) / self.zoom + room.car.coordinates[0],
                      (pygame.mouse.get_pos()[1] - self.h / 2) / self.zoom + room.car.coordinates[1]]

    def mouseRestricted(self):
        for window in room.windows:
            if (window.borders[0] < pygame.mouse.get_pos()[0] < window.borders[0] + window.borders[2] and
                window.borders[1] < pygame.mouse.get_pos()[1] < window.borders[1] + window.borders[3] and
                window.visible):
                    return(True)
        return(False)

    def zoomIn(self):
        if self.end_zoom < self.max_zoom:
            self.end_zoom *= 2

    def zoomOut(self):
        if self.end_zoom > self.min_zoom:
            self.end_zoom /= 2

    def zooming(self):
        if self.zoom < self.end_zoom:
            self.zoom /= 1 + (self.zoom - self.end_zoom) / self.end_zoom /10

        if self.zoom > self.end_zoom:
            self.zoom /= 1 + (self.zoom - self.end_zoom) / self.end_zoom / 10



class Object():

    def __init__(self, coordinates, angle, speed = 0):
        self.coordinates = coordinates
        self.speed = speed


class Component():


    connection_radius = 6
    part_size = 0

    def __init__(self, owner, coordinates):
        self.owner = owner
        self.coordinates = coordinates
        self.create = True
        self.next_component = ''

    def startCreate(self):
        room.marked.components.append(copy(self))

    def round_to_squares(self):
        x, y = pygame.mouse.get_pos()
        result = [self.coordinates[0], self.coordinates[1]]
        if (room.windows[0].circuit_window.mount[0] < x - Component.part_size * floor(self.w / 2) and
            x + Component.part_size * floor(self.w / 2) < room.windows[0].circuit_window.mount[2]):
                result[0] = int(round((x - room.windows[0].circuit_window.mount[0] - Component.part_size / 2) / self.part_size)
                                * self.part_size + room.windows[0].circuit_window.mount[0] + Component.part_size / 2)
        if (room.windows[0].circuit_window.mount[1] < y - Component.part_size * floor(self.h / 2) and
            y + Component.part_size * floor(self.h / 2) < room.windows[0].circuit_window.mount[3]):
                result[1] = int(round((y - room.windows[0].circuit_window.mount[2] - Component.part_size / 2) / self.part_size)
                                * self.part_size + room.windows[0].circuit_window.mount[2] + Component.part_size / 2)
        return result

    def move(self):
        self.coordinates = self.round_to_squares()

    
    def drawBase(self):
        pygame.draw.polygon(room.cam.screen, (50, 205, 50), [
            [self.coordinates[0] - self.w / 2 * self.part_size, self.coordinates[1] - self.h / 2 * self.part_size],
            [self.coordinates[0] - self.w / 2 * self.part_size, self.coordinates[1] + self.h / 2 * self.part_size],
            [self.coordinates[0] + self.w / 2 * self.part_size, self.coordinates[1] + self.h / 2 * self.part_size],
            [self.coordinates[0] + self.w / 2 * self.part_size, self.coordinates[1] - self.h / 2 * self.part_size]])
        pygame.draw.polygon(room.cam.screen, (100, 100, 100), [
            [self.coordinates[0] - self.w / 2 * self.part_size, self.coordinates[1] - self.h / 2 * self.part_size],
            [self.coordinates[0] - self.w / 2 * self.part_size, self.coordinates[1] + self.h / 2 * self.part_size],
            [self.coordinates[0] + self.w / 2 * self.part_size, self.coordinates[1] + self.h / 2 * self.part_size],
            [self.coordinates[0] + self.w / 2 * self.part_size, self.coordinates[1] - self.h / 2 * self.part_size]], 2)

        for connection in self.connections:
            pygame.draw.circle(
                room.cam.screen, (255, 255, 255), [
                    int(self.coordinates[0] + connection[0] * self.part_size),
                    int(self.coordinates[1] + connection[1] * self.part_size)],
                self.connection_radius)
            pygame.draw.circle(
                room.cam.screen, (0, 0, 0), [
                    int(self.coordinates[0] + connection[0] * self.part_size),
                    int(self.coordinates[1] + connection[1] * self.part_size)],
                self.connection_radius, 2)


    def remove(self):
        room.marked.components.remove(self)

class Cable(Component):
    w = 1
    h = 1
    width = 2
    connections = []
    connection_distance = 20

    def __init__(self, owner, coordinates):
        super().__init__(owner, coordinates)
        self.end_point = [0, 0]
        from_component = ''

    def testConnections(self):
        for component in room.marked.components:
            for connection in component.connections:
                x = connection[0] * self.part_size + component.coordinates[0]
                y = connection[1] * self.part_size + component.coordinates[1]
                m_x, m_y = pygame.mouse.get_pos()
                if sqrt((x - m_x) ** 2 + (y - m_y) ** 2) < self.connection_distance:
                    return([x, y], component)
        return(False)

    def startCreate(self):
        if self.testConnections():
            position, component = self.testConnections()
            self.coordinates = position
            self.create = True
            self.from_component = component
            room.marked.components.append(copy(self))
                

    def move(self):
        self.coordinates = pygame.mouse.get_pos()

    def end_create(self):
        if self.testConnections() != False:
            position, component = self.testConnections()
            self.end_point = position
            self.from_component.next_component = component
            room.windows[0].choosen = Cable(room.marked, [0, 0])
        else:
            self.remove()

    def drawBase(self):
        pygame.draw.lines(
            room.cam.screen, (0, 0, 0), True, [
            [self.coordinates[0] - self.w / 2 * self.part_size, self.coordinates[1] - self.h / 2 * self.part_size],
            [self.coordinates[0] + self.w / 2 * self.part_size, self.coordinates[1] - self.h / 2 * self.part_size],
            [self.coordinates[0] - self.w / 2 * self.part_size, self.coordinates[1] + self.h / 2 * self.part_size],
            [self.coordinates[0] + self.w / 2 * self.part_size, self.coordinates[1] + self.h / 2 * self.part_size]],
            self.width)

    def draw(self):
        pygame.draw.line(room.cam.screen, (0, 0, 0), self.coordinates, self.end_point, self.width)


    def creating(self):
        self.end_point = pygame.mouse.get_pos()


class D_Obstacle(Component):

    w = 3
    h = 3
    connections = [[w / 2 , 0]]

    def __init__(self, owner, coordinates):
        super().__init__(owner, coordinates)

    def draw(self):
        self.drawBase()

class O_Go(Component):

    w = 1
    h = 1
    connections = [[- w / 2, 0]]

    def __init__(self, owner, coordinates):
        super().__init__(owner, coordinates)

    def draw(self):
        self.drawBase()

class Car(Object):

    car_height = 10
    car_width = 5
    max_speed = 1
    power = 0.01

    def __init__(self, coordinates, speed, angle):
        self.points = [[coordinates[0] - self.car_width, coordinates[1] - self.car_height],
                       [coordinates[0] - self.car_width, coordinates[1] + self.car_height],
                       [coordinates[0] + self.car_width, coordinates[1] + self.car_height],
                       [coordinates[0] + self.car_width, coordinates[1] - self.car_height]]

        self.coordinates = coordinates
        self.speed = speed
        self.angle = - pi / 2
        self.radius = 0
        self.s = False
        self.w = False
        self.a = False
        self.d = False
        self.rot_point = [0, 0]
        self.a_speed = 0.02

    def update(self):
        self.accelerate()
        self.turning()
        self.rotPoint()
        self.move() if self.radius == 0 else self.rotate()
        self.draw()
        self.isMouse()

    def move(self):
        for point in self.points:
            point[0] += self.speed * cos(self.angle)
            point[1] += self.speed * sin(self.angle)
        self.coordinates[0] += self.speed * cos(self.angle)
        self.coordinates[1] += self.speed * sin(self.angle)


    def accelerate(self):
        if self.s:
            if self.speed > - self.max_speed:
                self.speed -= self.power
        elif self.w:
            if self.speed < self.max_speed:
                self.speed += self.power
        else:
            if -self.power > self.speed or self.speed > self.power:
                self.speed -= copysign(1, self.speed) * self.power
            else:
                self.speed = 0

    def aSpeed(self):
        self.a_speed = self.speed / self.radius / self.car_width / 2
        self.angle += self.a_speed

    def rotPoint(self):
        coe = 0
        if self.d:
            coe = 0.5
        elif self.a:
            coe = -0.5
        self.rot_point = ((self.points[2][0] - self.points[1][0]) * self.radius + self.points[int(1.5 + coe)][0],
                        (self.points[2][1] - self.points[1][1]) * self.radius + self.points[int(1.5 + coe)][1])

    def rotate(self):
        self.aSpeed()
        for point in self.points:
            x = ((point[0] - self.rot_point[0]) * cos(self.a_speed) -
                 (point[1] - self.rot_point[1]) * sin(self.a_speed) + self.rot_point[0])
            point[1] = ((point[0] - self.rot_point[0]) * sin(self.a_speed) +
                        (point[1] - self.rot_point[1]) * cos(self.a_speed) + self.rot_point[1])
            point[0] = x
        x = ((self.coordinates[0] - self.rot_point[0]) * cos(self.a_speed) -
             (self.coordinates[1] - self.rot_point[1]) * sin(self.a_speed) + self.rot_point[0])
        self.coordinates[1] = ((self.coordinates[0] - self.rot_point[0]) * sin(self.a_speed)
                               + (self.coordinates[1] - self.rot_point[1]) * cos(self.a_speed) + self.rot_point[1])
        self.coordinates[0] = x

    def isMouse(self):
        
        x, y = room.cam.mouse
        if -self.car_height < (x - self.coordinates[0]) * cos(self.angle) - (y - self.coordinates[1]) * sin(-self.angle) < self.car_height:
            if - self.car_width < (x - self.coordinates[0]) * sin(-self.angle) + (y - self.coordinates[1]) * cos(self.angle) < self.car_width:
                self.drawContour()
                if pygame.mouse.get_pressed()[0] and not room.cam.mouseRestricted():
                    self.mark()

    def mark(self):
        room.marked = self

    def draw(self):
        pygame.draw.polygon(room.cam.screen, self.color, room.cam.transform(self.points))

    def drawContour(self):
        pygame.draw.aalines(room.cam.screen,(0, 0, 0), True, room.cam.transform(self.points), 2)

    def inventory(self):
        pass



class MyCar(Car):
    color = (250, 0, 20)
    steer = 1.3
    min_rad = 2
    max_rad = 20

    def __init__(self, coordinates, speed, angle):
        super().__init__(coordinates, speed, angle)

    def turning(self):
        if self.a and self.radius <= 0:
            if self.radius < -self.min_rad:
                self.radius /= self.steer
            elif self.radius == 0:
                self.radius -= self.max_rad
        elif self.d and self.radius >= 0:
            if self.radius > self.min_rad:
                self.radius /= self.steer
            elif self.radius == 0:
                self.radius += self.max_rad
        else:
            if abs(self.radius) < self.max_rad and self.radius != 0:
                self.radius *= self.steer
            else:
                self.radius = 0


class RoboCar(Car):

    color = (0, 250, 0)
    def __init__(self, coordinates, speed, angle):
        super().__init__(coordinates, speed, angle)
        self.w = True
        self.d = False
        self.components = []

    def turning(self):
        if self.a:
            self.radius = -4.5
        if self.d:
            self.radius = 2.5

class BookMark():

    def __init__(self, colors, text, borders = [0, 0]):
        self.difference = 15
        self.contour = 5
        self.indent = 20
        self.color_0 = colors[0]
        self.colors = colors
        self.text = text
        self.text_width, self.text_height = self.text.get_width(), self.text.get_height()
        self.points = []
        self.countPoints(borders)
        self.is_mouse = False

    def countPoints(self, borders):
        self.points = [[borders[0], borders[1]],
                       [borders[0] - 2 * self.contour - self.text_width, borders[1] + self.difference],
                       [borders[0] - 2 * self.contour - self.text_width, borders[1] + self.difference + 4 * self.contour + self.text_height],
                       [borders[0], borders[1] + 2 * self.difference + 4 * self.contour + self.text_height]]

    def update(self):
        self.mouse()
        self.draw()

    def draw(self):
        if room.windows[0].top_book_mark == self:
            color = self.colors[1]
        else:
            color = self.colors[0]
        pygame.draw.polygon(room.cam.screen, color, self.points)
        pygame.draw.lines(room.cam.screen, self.colors[0], False,  self.points, 4)
        room.cam.screen.blit(self.text,(self.points[1][0] + self.contour, self.points[1][1] + 2 * self.contour))

    def special_draw(self):
        self.draw()
        pygame.draw.line(room.cam.screen, self.colors[1], [self.points[0][0] + 1, self.points[0][1] + 3], [self.points[3][0] + 1, self.points[3][1] - 2])
        pygame.draw.line(room.cam.screen, self.colors[1], [self.points[0][0] + 2, self.points[0][1] + 2], [self.points[3][0] + 2, self.points[3][1] - 2])

    def mouse(self):
        x, y = pygame.mouse.get_pos()
        if self.points[0][0] > x > self.points[1][0]:
            if (x * (self.points[1][1] - self.points[0][1]) - self.points[0][0] * self.points[1][1] + self.points[0][1] * self.points[1][0]) / (self.points[1][0] - self.points[0][0]) < y:
                if (x * (self.points[3][1] - self.points[2][1]) - self.points[2][0] * self.points[3][1] + self.points[2][1] * self.points[3][0]) / (self.points[3][0] - self.points[2][0]) > y:
                    if pygame.mouse.get_pressed()[0]:
                        room.windows[0].top_book_mark = self


class Window():

    def __init__(self,a, b, c, d, color, width = 0, visible = True):
        self.borders = [a, b, c, d]
        self.visible = visible
        self.color = color
        self.width = width

    def draw(self):
        pygame.draw.rect(room.cam.screen, self.color[0], self.borders)
        pygame.draw.rect(room.cam.screen, self.color[1], self.borders, self.width)

class ButtonWindow(Window):

    def __init__(self, a, b, c, d, color, buttons, width, visible = True):
        super().__init__(a, b, c, d, color, width, visible)
        self.buttons = buttons

class CircuitWindow():

    def __init__(self, a, b, c, d, color):
        self.borders = [a, b, c, d]
        self.color = color
        self.b_frame_click = (0, 0, 0)
        self.mount = [0, 0, 0, 0]
        self.mount_lenght = 100
        Component.part_size = floor(self.borders[2] / 23)
        self.borders[1] = pygame.display.get_surface().get_size()[1] / 2 - self.borders[2] / 23 * 6.5
        self.borders[3] = self.borders[2] / 23 * 13
        self.createMount()

    def createMount(self):
        self.mount = [self.borders[0] + (self.borders[2] - Component.part_size * 22) / 2,
                      self.borders[1] + (self.borders[3] - Component.part_size * 12) / 2,
                      self.borders[0] + self.borders[2] - (self.borders[2] - Component.part_size * 22) / 2,
                      self.borders[1] + self.borders[3] - (self.borders[3] - Component.part_size * 12) / 2]

    def draw(self):
        pygame.draw.rect(room.cam.screen, self.color[0], self.borders)
        pygame.draw.lines(room.cam.screen, (0, 0, 0), False,
                          [[self.mount[0] + self.mount_lenght, self.mount[1]],
                           [self.mount[0], self.mount[1]], [self.mount[0], self.mount[1] + self.mount_lenght]], 1)
        pygame.draw.lines(room.cam.screen, (0, 0, 0), False,
                          [[self.mount[2] - self.mount_lenght, self.mount[1]],
                           [self.mount[2], self.mount[1]], [self.mount[2], self.mount[1] + self.mount_lenght]], 1)
        pygame.draw.lines(room.cam.screen, (0, 0, 0), False,
                          [[self.mount[0] + self.mount_lenght, self.mount[3]],
                           [self.mount[0], self.mount[3]], [self.mount[0], self.mount[3] - self.mount_lenght]], 1)
        pygame.draw.lines(room.cam.screen, (0, 0, 0), False,
                          [[self.mount[2] - self.mount_lenght, self.mount[3]],
                           [self.mount[2], self.mount[3]], [self.mount[2], self.mount[3] - self.mount_lenght]], 1)
    def mouse(self):
        if self.b_frame_click == (0, 0, 0) and pygame.mouse.get_pressed() == (1, 0, 0):
            room.windows[0].choosen.startCreate()

        if self.b_frame_click == (1, 0, 0) and pygame.mouse.get_pressed() == (0, 0, 0):
            if len(room.marked.components) > 0:
                room.marked.components[-1].create = False
                room.marked.components[-1].end_create()
        self.b_frame_click = pygame.mouse.get_pressed()

class CarMenu(Window):

    def __init__(self,a, b, c, d, color, width, visible = True):
        super().__init__(a, b, c, d, color, width, visible)
        self.text_size = 15
        self.inner_window_space = 15
        self.inner_window_width = 130
        self.button_w = 100
        self.button_h = 30
        self.component_names = ['Kabel', 'Detektor překážek', 'Plyn', 'Udělátko', 'Blikátko', 'Tentononc']
        self.component_classes = [Cable, D_Obstacle, O_Go, D_Obstacle, D_Obstacle, D_Obstacle]
        self.buttons = []
        self.choosen = ''

        self.circuit_window = CircuitWindow(self.borders[0] + self.inner_window_width, self.borders[1] + self.inner_window_space, self.borders[2] - 3 * self.inner_window_space - self.button_w,
                                          self.borders[3] - 2 * self.inner_window_space, [(240, 240, 240), (0, 0, 0)])
        self.borders[1] = self.circuit_window.borders[1] - self.inner_window_space
        self.borders[3] = self.circuit_window.borders[3] + 2 * self.inner_window_space
        self.createComponents()

        self.button_window = ButtonWindow(self.borders[0] + self.inner_window_space, self.borders[1] + self.inner_window_space, self.inner_window_width,
                                          self.borders[3] - 2 * self.inner_window_space, [(220, 220, 220), (0, 0, 0)], self.buttons, 1)

        self.categories = ['Vše', 'Detektory', 'Logika', 'Outputy', 'Vlastní']
        self.category_components = [[1], [], [2], []]
        self.book_marks = []
        self.createBookMarks()
        self.top_book_mark = self.book_marks[0]

    def update(self):
        self.draw()
        self.mouse()

    def mouse(self):
        if (self.circuit_window.borders[0] < pygame.mouse.get_pos()[0] < self.circuit_window.borders[0] + self.circuit_window.borders[2] and
            self.circuit_window.borders[1] < pygame.mouse.get_pos()[1] < self.circuit_window.borders[1] + self.circuit_window.borders[3]):
                self.is_mouse = True
                self.circuit_window.mouse()
        else:
            self.is_mouse = False

    def createComponents(self):
        colors = [(160, 160, 160), (100, 100, 100), (250, 250, 250), (160, 100, 250), (100, 100, 100), (0, 0, 250)]
        for i in range(len(self.component_names)):
            self.buttons.append(ComponentButton(colors, [self.borders[0] + self.inner_window_space + self.button_w / 2, self.borders[1] +
                                                self.inner_window_space + self.button_h * (0.5 + i)],[self.button_w, self.button_h],
                                       self.component_names[i],self.text_size, self.component_classes[i], 2))


    def borec(self):
        print('borec')

    def createBookMarks(self):
        for i in range(len(self.categories)):
            text = (pygame.transform.rotate(pygame.font.SysFont("arial", self.text_size).render(self.categories[i], True, (0, 0, 0)), 90))
            if self.book_marks == []:
                base = self.borders[1]
            else:
                base = self.book_marks[-1].points[2][1]
            self.book_marks.append(BookMark([(160, 160, 160), (220, 220, 220)], text, [self.borders[0], base]))


class Menu():
    colors = [(100, 100, 120), (245, 240, 240), (250, 250, 250)]
    def __init__(self, buttons):
        self.buttons = buttons

class Button():

    def __init__(self, colors, coordinates, size, text, text_size, width, visible = True):
        self.coordinates = coordinates
        self.size = size
        self.borders = [coordinates[0] - size[0] / 2, coordinates[1] - size[1] / 2, size[0], size[1]]
        self.text = pygame.font.SysFont("arial", text_size).render(text, True, colors[2])
        self.text_width, self.text_height = self.text.get_width(), self.text.get_height()
        self.colors = colors
        self.width = width
        self.is_mouse = False
        self.visible = visible
        self.b_frame_click = False


    def draw(self):
        if self.is_mouse == True:
            col = 3
        else:
            col = 0
        if self.visible:
            pygame.draw.rect(room.cam.screen, self.colors[0 + col], self.borders)
            pygame.draw.rect(room.cam.screen, self.colors[1 + col], self.borders, self.width)
            room.cam.screen.blit(self.text,(self.coordinates[0] - self.text_width / 2, self.coordinates[1] - self.text_height / 2))

    def mouse(self):
        x, y = pygame.mouse.get_pos()
        if (self.borders[0] < x < self.borders[0] + self.size[0] and
            self.borders[1] < y < self.borders[1] + self.size[1]):
            self.is_mouse = True
            self.do_task()

        else:
            self.is_mouse = False

    def update(self):
        self.mouse()
        self.draw()

class MenuButton(Button):

    def __init__(self, colors, coordinates, size, text, text_size, task, visible = True):
        super().__init__(colors, coordinates, size, text, text_size, 4, visible)
        self.task = task

    def do_task(self):
        if not pygame.mouse.get_pressed()[0]:
            if self.b_frame_click:
                self.task()
        self.b_frame_click = pygame.mouse.get_pressed()[0]

class ComponentButton(Button):

    def __init__(self, colors, coordinates, size, text, text_size, obj, width, visible = True):
        super().__init__(colors, coordinates, size, text, text_size, width, visible)
        self.object = obj

    def do_task(self):
        if not pygame.mouse.get_pressed()[0]:
            if self.b_frame_click:
                room.windows[0].choosen = self.object(room.marked, pygame.mouse.get_pos())
        self.b_frame_click = pygame.mouse.get_pressed()[0]



class Room():

    def __init__(self):
        self.cam = Camera(1)
        Component.part_size = int(self.cam.w  / 33)
        self.robocars = []
        self.marked = 'none'
        self.windows = [CarMenu(self.cam.w / 6, self.cam.h / 2 - self.cam.w / 11 * 2, self.cam.w * 2 / 3, 4 * self.cam.w / 11, [(220, 220, 220), (160, 160, 160)], 4, False)]
        self.k = 2000

    def control(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                loop.crashed = True

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_ESCAPE:
                    if not loop.new_game:
                        loop.menu = not loop.menu
                        loop.pause = not loop.pause
                if event.key == pygame.K_SPACE:
                    if not loop.menu:
                        loop.pause = not loop.pause
            if not loop.pause:

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_s:
                        self.car.s = True
                    if event.key == pygame.K_w:
                        self.car.w = True
                    if event.key == pygame.K_a:
                        self.car.a = True
                    if event.key == pygame.K_d:
                        self.car.d = True

                if event.type == pygame.KEYUP:
                    if event.key == pygame.K_s:
                        self.car.s = False
                    if event.key == pygame.K_w:
                        self.car.w = False
                    if event.key == pygame.K_a:
                        self.car.a = False
                    if event.key == pygame.K_d:
                        self.car.d = False

                    if event.key == pygame.K_n:
                        self.newCar()
                    if event.key == pygame.K_e:
                        if room.marked != 'none' and not isinstance(room.marked, MyCar):
                            room.windows[0].visible = not room.windows[0].visible

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 4:
                        self.cam.zoomIn()
                    elif event.button == 5:
                        self.cam.zoomOut()


    def do_stuff(self):
        if loop.menu:
                for button in self.menu.buttons:
                    button.update()
        if not loop.menu:
            if not loop.pause:
                self.car.update()
                for robocar in self.robocars:
                    robocar.update()
                self.pokus()
            else:
                self.car.draw()
                for robocar in self.robocars:
                    robocar.draw()
            if self.marked != 'none':
                self.marked.drawContour()
                if self.windows[0].visible:
                    for book_mark in self.windows[0].book_marks:
                        book_mark.update()
                    self.windows[0].update()
                    self.windows[0].top_book_mark.special_draw()
                    self.windows[0].circuit_window.draw()
                    for component in self.marked.components:
                        if component.create:
                            component.creating()
                        component.draw()
                    if self.windows[0].choosen != '':
                        self.windows[0].choosen.move()
                        if self.windows[0].is_mouse:
                            self.windows[0].choosen.drawBase()
                    for button in self.windows[0].button_window.buttons:
                        button.update()

    def pokus(self):
        if self.k > 0:
            self.newCar([40000 - self.k * 20, 0])
        self.k -= 1
        for j in range(20):
            pygame.draw.line(self.cam.screen, (0, 0, 0), self.cam.transform([[0, j * self.car.car_height * 3]])[0],
                             self.cam.transform([[200, j * self.car.car_height * 3]])[0])
        for i in range(5):
            pygame.draw.line(self.cam.screen, (0, 0, 0), self.cam.transform([[i * self.car.car_height * 3, -200]])[0],
                             self.cam.transform([[i * self.car.car_height * 3, 200]])[0])

    def newCar(self, coords=[0, 0], speed=0, angle=pi / 2):
        self.robocars.append(RoboCar(coords, speed, angle))


class GameLoop():

    def __init__(self):
        pygame.init()
        self.crashed = False
        self.menu = True
        self.pause = True
        self.new_game = True

    def quit(self):
        self.crashed = True

    def play(self):
        self.new_game = False
        self.menu = False
        self.pause = False
        room.menu.buttons[0].visible = False
        room.menu.buttons[1].visible = True

    def run(self):
        self.creator()
        while not self.crashed:
            room.cam.frame()
            room.control()
            room.do_stuff()
        pygame.quit()
        quit()

    def creator(self):
        room.car = MyCar([0, 0], 0, 0)
        colors = [(160, 160, 160), (100, 100, 100), (250, 250, 250), (160, 100, 250), (100, 100, 100), (0, 0, 250)]
        text_size = 32
        w, h = room.cam.w, room.cam.h
        room.menu = Menu([MenuButton(colors, [w / 2, h / 2 - 70], [400, 60], 'Nová hra', text_size, loop.play),
                          MenuButton(colors, [w / 2, h / 2 - 70], [400, 60], 'Pokračovat', text_size, loop.play, False),
                          MenuButton(colors, [w / 2, h / 2], [400, 60], 'Nastavení', text_size, loop.play),
                          MenuButton(colors, [w / 2, h / 2 + 70], [400, 60], 'Konec', text_size, loop.quit)])

room = Room()
loop = GameLoop()
loop.run()
Nahlásit jako SPAM
IP: 213.192.2.–
gna
~ Anonymní uživatel
716 příspěvků
13. 10. 2018   #2
-
+1
-
Zajímavé
Kit +

Nechce se mi to moc studovat, ale za ten sin/cos bych lámal prsty. Samozřejmě začneš tím, že budeš používat vektory (a matice).

Nahlásit jako SPAM
IP: 213.211.51.–
Kit+14
Guru
13. 10. 2018   #3
-
+1
-
Zajímavé

#1 jare Q
Začíná to už při 

self.w, self.h = pygame.display.get_surface().get_size()

// které bych nahradil
self.surfaceSize = pygame.display.get_surface().get_size()

Potom se dá spousta dvojitých zápisů zjednodušit.

Ještě lepšího výsledku však dosáhneš, pokud všechny souřadnice [x, y] nahradíš komplexním číslem. Posun se pak dělá obyčejným sčítáním, rychlost a otáčení násobením. Parametry speed a angle jsou pak také jen jedno číslo. Zcela odpadnou potíže s pomalými funkcemi sin() a cos().

Nahlásit jako SPAM
IP: 2a00:1028:83a0:37a6:7116:e8b9:1364:29bc...–
Komentáře označují místa, kde programátor udělal chybu nebo něco nedodělal.
jare Q0
Duch
14. 10. 2018   #4
-
0
-

#2 gna
Dobrá, takže používat sin/cos není kvůli jejich pomalosti dobrý nápad, chápu. Ale jak mám použít vektory a matice na rotaci a přitom nevyužít goniometrické funkce? S komplexními čísly, jako psal Kit, je mi to jasné, ale vektory ne.

Nahlásit jako SPAM
IP: 213.192.2.–
Kit+14
Guru
14. 10. 2018   #5
-
0
-

#4 jare Q
Pokud používáš otáčení o 90 stupňů, tak stačí jen zaměňovat souřadnice a měnit jim znaménko. Ušetří se tím dost výkonu.

Nahlásit jako SPAM
IP: 2a00:1028:83a0:37a6:7116:e8b9:1364:29bc...–
Komentáře označují místa, kde programátor udělal chybu nebo něco nedodělal.
jare Q0
Duch
14. 10. 2018   #6
-
0
-

#5 Kit
Jenže já otáčím plynule. Dokonce kontroluji rychlost rychlosti otáčení.

Nahlásit jako SPAM
IP: 213.192.2.–
Kit+14
Guru
14. 10. 2018   #7
-
0
-
Nahlásit jako SPAM
IP: 2a00:1028:83a0:37a6:7116:e8b9:1364:29bc...–
Komentáře označují místa, kde programátor udělal chybu nebo něco nedodělal.
Jerry
~ Anonymní uživatel
223 příspěvků
15. 10. 2018   #8
-
+1
-
Zajímavé

#1 jare Q
ten tvuj zdroják mi připomíná python :) možná to aj bude python, ale hry se v pythonu obvykle nepíšou :) protože sou pomalý. pokud budeš trvat na tak velkém počtu objektů v obraze t.j. 500 aut, tak možná budeš muset použít klasické metody k tomu určené t.j. C++ a DirectX nebo C++ a OpenGL a podobně, tedy vše co podporuje přímo HW akceleraci. Jinak jestli chceš vědět jak se píšou hry tak si stáhni zdroják DOOM 1.

http://doom.wikia.com/wiki/Doom_source_code_files

jo a přímý výpočet sin/cos se taky nepoužívá jak je napsáno výše, protože je to pomalé, místo toho se používaj tabulky pro sin po 5 stupních nebo po 2 stupních a pod.

Nahlásit jako SPAM
IP: 2a00:1028:83be:235a:7c9e:2620:83ed:576d...–
Zjistit počet nových příspěvků

Přidej příspěvek

×Vložení zdrojáku

×Vložení obrázku

Vložit URL obrázku Vybrat obrázek na disku
Vlož URL adresu obrázku:
Klikni a vyber obrázek z počítače:

×Vložení videa

Aktuálně jsou podporována videa ze serverů YouTube, Vimeo a Dailymotion.
×
 
Podporujeme Gravatara.
Zadej URL adresu Avatara (40 x 40 px) nebo emailovou adresu pro použití Gravatara.
Email nikam neukládáme, po získání Gravatara je zahozen.
-
Pravidla pro psaní příspěvků, používej diakritiku. ENTER pro nový odstavec, SHIFT + ENTER pro nový řádek.
Sledovat nové příspěvky (pouze pro přihlášené)
Sleduj vlákno a v případě přidání nového příspěvku o tom budeš vědět mezi prvními.
Reaguješ na příspěvek:

Uživatelé prohlížející si toto vlákno

Uživatelé on-line: 0 registrovaných, 12 hostů

Podobná vlákna

C++ kod chyba? — založil uGo

Čárový kód — založil Pebble

Zdrojový kód — založil jurinecko

Z textu kód — založil Polarski

 

Hostujeme u Českého hostingu       ISSN 1801-1586       ⇡ Nahoru Webtea.cz logo © 20032018 Programujte.com
Zasadilo a pěstuje Webtea.cz, šéfredaktor Lukáš Churý