Python3 - pygame. Создание границ карты

Я создаю игру по типу Doors Kickers или SWAT. Это 2D шутер с видом сверху про спецназ. Я столкнулся с проблемой, когда начал добавлять коллизию краям карты: при соприкосновении со стеной (а иногда и с воздухом) игра просто блокирует любые передвижения персонажа. Я уже понял где находится баг (он будет подсвечен комментариями), но никак не могу придумать как его пофиксить. Код будет ниже, но для запуска игры нужны будут спрайты, они будут доступны по ссылке. Код:

import pygame
import sys
import math

# -------------Colors-------------
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
TEXTCOLOR = (0, 0, 0)

# -------------Window settings-------------

pygame.init()
win_dim = (1080, 720)
print(win_dim[0] - 5)
win = pygame.display.set_mode(win_dim)
pygame.display.set_caption("Game")

# -------------Sprite settings-------------

rifle1 = pygame.image.load("sprites/weapons/rifle.png")
rifle = pygame.image.load("sprites/weapons/rifle.png")
bg = pygame.image.load("sprites/locations/training/training.png")

# -------------Main character settings-------------

x = 60
y = 70
radius = 65 // 2
width = 65
height = 65

speed = 10

bullets = []

facing = 0


# -------------Triggers settings-------------
class TriggerList:
    def __init__(self):
        self.initialized = True

    def teleport(self, pos):  # [x, y]
        mc.pos[0] = pos[0]
        mc.pos[1] = pos[1]
        print("teleported")


triggerList = TriggerList()

# -------------General border settings-------------

borders_x_min = 15
borders_x_max = win_dim[0] - 40
borders_y_min = 15
borders_y_max = win_dim[1] - 40


def reduction(num):
    ostNum = num % 1
    if ostNum < 0.5:
        num = num - ostNum
    elif ostNum >= 0.5:
        num = num + 1 - ostNum
    return num


def cosBetweenVectors(pos1, pos2):
    x1, y1 = pos1[0], pos1[1]
    x2, y2 = pos2[0], pos2[1]
    module1 = reduction(math.sqrt(x1 ** 2 + y1 ** 2))
    module2 = reduction(math.sqrt(x2 ** 2 + y2 ** 2))
    try:
        return (x1 * x2 + y1 * y2) / (module1 * module2)
    except:
        return 0


class Trigger:
    def __init__(self, x1, x2, y1, y2):
        self.x1 = x1
        self.x2 = x2
        self.y1 = y1
        self.y2 = y2

    def isTriggered(self):
        if self.x1 < mc.pos[0] < self.x2 and self.y1 < mc.pos[1] < self.y2:
            return True


def whereAmImLooking():
    print("Im looking at", pygame.mouse.get_pos())


def getMousePos(xy=2):  # 0 - x; 1 - y; 2 - (x, y)
    ret = pygame.mouse.get_pos()
    try:
        return ret[xy]
    except:
        return ret


def drawTestCircle(pos):
    print(pos)
    pygame.draw.circle(
        win, (0, 0, 0), pos, 20
    )


def bordersLock(posretur=False):
    ret = 0
    x = mc.pos[0]
    y = mc.pos[1]
    pos = 1

    if (400 - 65 // 2 - 10 > x > 10 + 65 // 2 + 15) and (15 + 65 // 2 + 10 < y < 120 - 65 // 2):
        ret += 1
        pos = 1
    if (230 + 65 // 2 + 10 < x < 400 - 65 // 2 - 10) and (70 < y < 350):
        ret += 1
        pos = 2
    if (10 + 65 // 2 + 10 < x < 970 - 65 // 2 - 10) and (300 + 65 // 2 + 10 < y < 410 - 65 // 2):
        ret += 1
        pos = 3
    if (840 + 65 // 2 + 10 < x < 970 - 65 // 2 - 10) and (15 + 65 // 2 + 10 < y < 310):
        ret += 1
        pos = 4

    if posretur:
        return pos
    if ret > 0:
        return True
    return False


class Character:
    pos = [0, 0]
    weaponPos = [pos[0] - 615 // 2, pos[1] - 65 // 2]
    vector = [0, 1]
    angle = 180

    def __init__(self, side, type, speed, pos=None):
        if pos is None:
            pos = [x, y]
        self.side = side
        self.type = type
        self.speed = speed
        self.pos = pos

    def weaponDown(self):
        self.angle = 180
        self.vector = [0, 1]
        win.blit(rifle1, (mc.weaponPos[0], mc.weaponPos[1]))

      """Ошибка начинается отсюда"""

    def isMove(self):
        if keys[pygame.K_a] and mc.pos[0] > borders_x_min and bordersLock() == True:  # left Ошибка здесь
            self.pos[0] -= self.speed
            self.weaponPos[0] -= self.speed
        elif keys[pygame.K_d] and self.pos[0] < borders_x_max - width and bordersLock() == True:  # right Здесь
            self.pos[0] += self.speed
            self.weaponPos[0] += self.speed
        if keys[pygame.K_w] and self.pos[1] > borders_y_min and bordersLock() == True:  # up Здесь
            self.pos[1] -= self.speed
            self.weaponPos[1] -= self.speed
        elif keys[pygame.K_s] and self.pos[1] < borders_y_max - height and bordersLock() == True:  # down И здесь
            self.pos[1] += self.speed
            self.weaponPos[1] += self.speed
        self.weaponPos = [self.pos[0] + 65 // 2, self.pos[1] + 65 // 2]

       """И кончается вот здесь"""

    def aim(self):
        global rifle
        pass

    def shoot(self):
        pass


teleport = Trigger(50, 200, 50, 100)
mc = Character("friendly", "solider", speed)
while True:

    pygame.time.delay(100)

    win.fill((0, 128, 128))
    win.blit(bg, (0, 0))

    win.blit(rifle, (mc.weaponPos[0], mc.weaponPos[1]))
    pygame.draw.circle(win, BLUE, (mc.pos[0], mc.pos[1]), radius)

    keys = pygame.key.get_pressed()

    # whereAmImLooking()
    mc.isMove()
    mc.aim()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                drawTestCircle(getMousePos())
    if keys[pygame.K_ESCAPE]:
        sys.exit()
    if keys[pygame.K_SPACE] and keys[pygame.K_p]:
        speed += 50

    pygame.display.update()

sys.exit()

Так же в коде возможно присутствуют элементы, не использующиеся в коде или другие ошибки. Они не критичны и я их собираюсь исправлять позже, так что прошу не говорить мне о них. Прошу помочь и указать как это исправить. Заранее спасибо за помощь.


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