Привет, я делаю игру, похожую на ретро-игру «Утиная охота», но вместо этого по экрану летают самолеты. Первоначально я начал программировать с использованием функций, главным образом потому, что это проще, но я хочу преобразовать его в класс, чтобы было проще создавать экземпляры плоскостей и т. д., но я не понимаю, как это сделать? Я создал две функции для рисования и обновления плоскостей, которые работают как функции, но я не уверен, как перевести их в код класса/ООП? Предыдущий код (код показан здесь) заставлял самолеты появляться на экране и летать случайным образом слева направо, справа налево и т. д. по разным координатам Y (по 3 на экране одновременно).
current_planes = []
def spawn_plane():
# chooses a random y position for the plane to spawn
plane_limit = 37
plane_deck = 250
plane_y = random.randint(plane_limit, plane_deck)
direction = random.choice(["left", "right"])
# decides randomly whether the plane will start on the left/right
if direction == "right":
plane_x = -103
velocity = plane_vel
flipped_plane = pygame.transform.flip(plane, True, False)
else:
plane_x = screen_width
velocity = -plane_vel
flipped_plane = pygame.transform.flip(plane, False, False)
# add plane's data to current_planes list
current_planes.append({
"x": plane_x,
"y": plane_y,
"velocity": velocity,
"image": flipped_plane,
})
# moves planes and deletes when leave screen
def update_planes():
global current_planes
for plane in current_planes[:]:
plane["x"] += plane["velocity"]
# remove planes
if plane["x"] > screen_width or plane["x"] < -103:
current_planes.remove(plane)
# draw planes
for plane in current_planes:
screen.blit(plane["image"], (plane["x"], plane["y"]))
hitbox_plane = (plane["x"] + 5, plane["y"] + 2, 103, 37)
pygame.draw.rect(screen, ("green"), hitbox_plane, 2)
# (in the main game loop)
# spawn planes every 60 frames
if frame_count % 60 == 0:
spawn_plane()
# draws and updates screen
draw_main_game()
update_planes()
pygame.display.update()
clock.tick(60)
frame_count += 1
Я пытался просто скопировать этот код в класс, не ожидая, что он сработает (не сработало), но я просто не совсем понимаю классы? Я не уверен, что я хотел указать в качестве параметров и т. д. и как это вызвать в игровом цикле. этот код ->
class planes:
def __init__(self, plane_x, plane_y, width, height, plane):
self.plane_x = plane_x
self.plane_y = plane_y
self.width = width
self.height = height
self.plane = plane
self.vel = \[0,0\]
# func to spawn new plane
def spawn_plane():
# chooses a random y position for the plane to spawn
plane_limit = 37
plane_deck = 250
plane_y = random.randint(plane_limit, plane_deck)
direction = random.choice(["left", "right"])
# decides randomly whether the plane will start on the left/right
if direction == "right":
plane_x = -103
velocity = plane_vel
flipped_plane = pygame.transform.flip(plane, True, False)
else:
plane_x = screen_width
velocity = -plane_vel
flipped_plane = pygame.transform.flip(plane, False, False)
# add plane's data to current_planes list
current_planes.append({
"x": plane_x,
"y": plane_y,
"velocity": velocity,
"image": flipped_plane,
})
# moves planes and deletes when leave screen
def update_planes():
global current_planes
for plane in current_planes[:]:
plane["x"] += plane["velocity"]
# remove planes
if plane["x"] > screen_width or plane["x"] < -103:
current_planes.remove(plane)
# draw planes
for plane in current_planes:
screen.blit(plane["image"], (plane["x"], plane["y"]))
hitbox_plane = (plane["x"] + 5, plane["y"] + 2, 103, 37)
pygame.draw.rect(screen, ("green"), hitbox_plane, 2)`
Будем благодарны за любую помощь. (Я сократил код программы, чтобы показать материал, имеющий отношение к моему вопросу, но если это не имеет смысла, дайте мне знать) С уважением
Подробнее здесь: https://stackoverflow.com/questions/792 ... to-a-class
Как преобразовать ряд функций в класс ⇐ Python
Программы на Python
1733152189
Anonymous
Привет, я делаю игру, похожую на ретро-игру «Утиная охота», но вместо этого по экрану летают самолеты. Первоначально я начал программировать с использованием функций, главным образом потому, что это проще, но я хочу преобразовать его в класс, чтобы было проще создавать экземпляры плоскостей и т. д., но я не понимаю, как это сделать? Я создал две функции для рисования и обновления плоскостей, которые работают как функции, но я не уверен, как перевести их в код класса/ООП? Предыдущий код (код показан здесь) заставлял самолеты появляться на экране и летать случайным образом слева направо, справа налево и т. д. по разным координатам Y (по 3 на экране одновременно).
current_planes = []
def spawn_plane():
# chooses a random y position for the plane to spawn
plane_limit = 37
plane_deck = 250
plane_y = random.randint(plane_limit, plane_deck)
direction = random.choice(["left", "right"])
# decides randomly whether the plane will start on the left/right
if direction == "right":
plane_x = -103
velocity = plane_vel
flipped_plane = pygame.transform.flip(plane, True, False)
else:
plane_x = screen_width
velocity = -plane_vel
flipped_plane = pygame.transform.flip(plane, False, False)
# add plane's data to current_planes list
current_planes.append({
"x": plane_x,
"y": plane_y,
"velocity": velocity,
"image": flipped_plane,
})
# moves planes and deletes when leave screen
def update_planes():
global current_planes
for plane in current_planes[:]:
plane["x"] += plane["velocity"]
# remove planes
if plane["x"] > screen_width or plane["x"] < -103:
current_planes.remove(plane)
# draw planes
for plane in current_planes:
screen.blit(plane["image"], (plane["x"], plane["y"]))
hitbox_plane = (plane["x"] + 5, plane["y"] + 2, 103, 37)
pygame.draw.rect(screen, ("green"), hitbox_plane, 2)
# (in the main game loop)
# spawn planes every 60 frames
if frame_count % 60 == 0:
spawn_plane()
# draws and updates screen
draw_main_game()
update_planes()
pygame.display.update()
clock.tick(60)
frame_count += 1
Я пытался просто скопировать этот код в класс, не ожидая, что он сработает (не сработало), но я просто не совсем понимаю классы? Я не уверен, что я хотел указать в качестве параметров и т. д. и как это вызвать в игровом цикле. этот код ->
class planes:
def __init__(self, plane_x, plane_y, width, height, plane):
self.plane_x = plane_x
self.plane_y = plane_y
self.width = width
self.height = height
self.plane = plane
self.vel = \[0,0\]
# func to spawn new plane
def spawn_plane():
# chooses a random y position for the plane to spawn
plane_limit = 37
plane_deck = 250
plane_y = random.randint(plane_limit, plane_deck)
direction = random.choice(["left", "right"])
# decides randomly whether the plane will start on the left/right
if direction == "right":
plane_x = -103
velocity = plane_vel
flipped_plane = pygame.transform.flip(plane, True, False)
else:
plane_x = screen_width
velocity = -plane_vel
flipped_plane = pygame.transform.flip(plane, False, False)
# add plane's data to current_planes list
current_planes.append({
"x": plane_x,
"y": plane_y,
"velocity": velocity,
"image": flipped_plane,
})
# moves planes and deletes when leave screen
def update_planes():
global current_planes
for plane in current_planes[:]:
plane["x"] += plane["velocity"]
# remove planes
if plane["x"] > screen_width or plane["x"] < -103:
current_planes.remove(plane)
# draw planes
for plane in current_planes:
screen.blit(plane["image"], (plane["x"], plane["y"]))
hitbox_plane = (plane["x"] + 5, plane["y"] + 2, 103, 37)
pygame.draw.rect(screen, ("green"), hitbox_plane, 2)`
Будем благодарны за любую помощь. (Я сократил код программы, чтобы показать материал, имеющий отношение к моему вопросу, но если это не имеет смысла, дайте мне знать) С уважением
Подробнее здесь: [url]https://stackoverflow.com/questions/79244580/how-to-convert-a-series-of-functions-into-a-class[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия