как сделать столкновение в flappybird? - PullRequest
0 голосов
/ 08 ноября 2019

Хорошо, мне нужно сделать столкновение между двумя колоннами с птицей-игроком. Извините, если код сложный, я новичок в программировании.

В коде есть два столпа, которые перемещаются влево и повторяются. Я сделал xpos2, ypos2, xpos, ypos, потому что в один момент есть 2 столпа. Разрыв между ними составляет 670, потому что изображение столбов очень большое, поэтому я нарисовал их очень высоко или низко - вы не можете видеть все столбы. Что мне нужно, чтобы сделать столкновение между каждой колонной (сверху или снизу) с птицей. Я попытался с Colliderect и другим функционалом Pygame без успеха.

Спасибо.

код

import pygame
import random

size = [900, 504]
wait = pygame.time.Clock()
red = (255, 0, 0)
pygame.init()


class game:
    def __init__(self):
        self.screen = pygame.display.set_mode((size[0], size[1])) 
        pygame.display.set_caption("Flappy Bird @yuv")
        self.background = pygame.image.load(r"d:\Users\Student\Desktop\background.png").convert()  
        self.top_pillar = pygame.image.load(r"d:\Users\Student\Desktop\top.png").convert()
        self.bottom_pillar = pygame.image.load(r"d:\Users\Student\Desktop\bottom.png").convert()
        self.done = False
        self.xpos = 400  # XPOS OF THE PILLARS
        self.xpos2 = 800 # 
        self.ypos_top = random.randint(-400, -200)  # ypos of the pillar - top
        self.ypos_bottom = self.ypos_top + 670  # ypos of the pillar - bottom
        self.ypos2_top = random.randint(-400, -200)  # ypos of the pillar - bottom
        self.ypos2_bottom = self.ypos2_top + 670  # ypos of the pillar - bottom
        self.score = 0

    def pillars(self):
        for i in range(5):
            self.xpos -= 1
            self.xpos2 -= 1
        if self.xpos <= 0:
            self.xpos = 800
            self.ypos_top = random.randint(-400, -200)  # ypos of the pillar - top
            self.ypos_bottom = self.ypos_top + 670  # ypos of the pillar - bottom
        if self.xpos2 <= 0:
            self.xpos2 = 800
            self.ypos2_top = random.randint(-400, -200)  # ypos of the pillar - bottom
            self.ypos2_bottom = self.ypos2_top + 670  # ypos of the pillar - bottom

   # def collide(self):
            ## how the hell i do it ! ? ?! ?! ?! ?!

    def scoregame(self):
        if bird().x > self.xpos or bird().x > self.xpos2:  
            self.score += 1
        myfont = pygame.font.SysFont('Comic Sans MS', 30)
        textsurface = myfont.render('score : ' + str(int(self.score / 39)), True, red)
        self.screen.blit(textsurface, (0, 0))

    def gameover(self):
        font = pygame.font.SysFont(None, 55)
        text = font.render("Game Over!", False, red)
        self.screen.blit(text, [100, 250])
        self.done = True  


class bird:
    def __init__(self):
        self.x = 200
        self.y = 350
        self.bird = pygame.image.load(r"d:\Users\Student\Desktop\player.png").convert_alpha()

    def move_bird(self):
        wait.tick(20)
        for i in range(3):
            self.y += 2
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    for i in range(50):
                        self.y -= 1

    def check_obstacle(self):
        if self.y > 478 or self.y < -10:  # check if the player touch the top or the bottom of the screen
            print('3')
            Game.gameover()


Game = game()
birdfunc = bird()
while Game.done == False:
    Game.screen.blit(Game.background, (0, 0))
    Game.screen.blit(birdfunc.bird, (birdfunc.x, birdfunc.y))
    birdfunc.move_bird()
    birdfunc.check_obstacle()
    Game.screen.blit(Game.top_pillar, (
    Game.xpos, Game.ypos_bottom))  # ypos -500 is the start of the top between -400 to -200 XXXXX gap- 200

    Game.screen.blit(Game.bottom_pillar, (Game.xpos, Game.ypos_top))  # ypos 500 is the start of the bottom

    Game.screen.blit(Game.top_pillar, (Game.xpos2, Game.ypos2_bottom))  # ypos -500 is the start of the top between -400 to -200 XXXXX gap- 200

    Game.screen.blit(Game.bottom_pillar, (Game.xpos2, Game.ypos2_top))  # ypos 500 is the start of the bottom
    Game.scoregame()
    Game.pillars()
    pygame.display.flip()
while Game.done == True:
    Game.screen.blit(Game.background, (0, 0))
    Game.gameover() 

1 Ответ

0 голосов
/ 09 ноября 2019

Вы уже довольно близко ... Я вижу, что у вас есть код для столкновений с уже написанными верхом и низом экрана. Вам также не нужна библиотека для простой обработки столкновений между объектами, в этом случае вы, вероятно, можете написать свой собственный алгоритм.

def check_obstacle(self):
    if self.y > 478 or self.y < -10:  # check if the player touch the top or the bottom of the screen
        print('3')
        Game.gameover()

Как вы можете изменить это, чтобы птица сталкивалась с колоннами?

Вот моя первоначальная мысль: края столбов можно было бы упростить до различных значений self.y, поэтому, если птица находится вне диапазона действительных значений y между столбами, когда столб проходит мимо (есть ли у васpillar.x?), оно должно называться Game.gameover(). Рисование рисунка и маркировка его координатами на бумаге может помочь вам в математике.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...