не понимаю почему не работает функция автоматического движения влево-вправо
в функции avto
from pygame import *
mixer.init()
mixer.music.load("jungles.ogg")
mixer.music.play()
window = display.set_mode((1000,700)) #oкнo
display.set_caption('Догонялки')
clock = time.Clock()
bg = transform.scale(image.load('background.jpg'),(1000,700)) #фон
treasure = transform.scale(image.load('treasure.png'),(100,70))
class Hero:
def __init__(self,x,y):
self.x=x
self.y=y
self.hero = transform.scale(image.load('hero.png'),(100, 70))
global rect1
rect1 = self.hero.get_rect()
def upravlenie(self):
k_s = key.get_pressed()
if k_s[K_LEFT] and self.x > 0:
self.x -= 10
elif k_s[K_RIGHT] and self.x < 900:
self.x += 10
if k_s[K_UP] and self.y > 0:
self.y -= 10
elif k_s[K_DOWN] and self.y < 600:
self.y += 10
def render(self):
window.blit(self.hero, (self.x,self.y))
class Cyborg:
def __init__(self,x,y):
self.x = x + 23
self.y = y
self.cyborg = transform.scale(image.load('cyborg.png'),(100, 70))
global rect2
rect2 = self.cyborg.get_rect()
def avto(self):
if self.x > 700 and self.x <= 850:
self.x -= 5
if self.x == 700:
if self.x != 850:
self.x += 5
print(self.x)
def render(self):
window.blit(self.cyborg, (self.x, self.y))
hero = Hero(0, 600)
cyborg = Cyborg(777,500)
game = True #переключатель для завершения цикла игры
while game != False:
window.blit(bg,(0,0))
window.blit(treasure,(850, 600))
hero.render()
hero.upravlenie()
cyborg.render()
cyborg.avto()
for e in event.get():
if e.type == QUIT:
game = False
display.update()
clock.tick(60)
Ответы (1 шт):
Автор решения: gil9red
→ Ссылка
Добавил перечисление для описания состояния
Оно используется, чтобы определить в какое направление движется робот
Пример:
import enum
...
class StateEnum(enum.Enum):
NONE = enum.auto()
MOVE_RIGHT = enum.auto()
MOVE_LEFT = enum.auto()
class Cyborg:
def __init__(self, x, y):
self.x = x + 23
self.y = y
self.state = StateEnum.MOVE_RIGHT
self.cyborg = transform.scale(image.load('cyborg.png'), (100, 70))
global rect2
rect2 = self.cyborg.get_rect()
def update_state(self):
if self.x >= 850:
self.state = StateEnum.MOVE_LEFT
elif self.x <= 700:
self.state = StateEnum.MOVE_RIGHT
def avto(self):
if self.state == StateEnum.MOVE_LEFT:
self.x -= 5
elif self.state == StateEnum.MOVE_RIGHT:
self.x += 5
self.update_state()
print(self.state, self.x)
def render(self):
window.blit(self.cyborg, (self.x, self.y))