如何为flappy Bird制作记分牌?

发布于 01-16 18:52 字数 3900 浏览 1 评论 0 原文

我正在为 Flappy Bird 制作一款游戏,我需要制作一个计分器,它就在那里,但它是歪的。它会在第一个管道之后计算一大堆点,并且在死亡后不会重置它们。下面我将附上代码本身和点的代码。

如果你能写出代码,那就是正确的。

import pygame#импортирование модуля pygame
import random#Добавляет возможность спавнить разные трубы
pygame.init()

WIDTH, HEIGHT = 800, 600#FPS и размеры окна
FPS = 60

window = pygame.display.set_mode((WIDTH, HEIGHT))#Создание окна
clock = pygame.time.Clock()

font1 = pygame.font.Font(None, 35)#шрифты
font2 = pygame.font.Font(None, 80)

imgBG = pygame.image.load('images/fon.png')#Добавление картинок
imgBIRD = pygame.image.load('images/bird.png')
imgPB = pygame.image.load('images/PB.png')
imgPT = pygame.image.load('images/PT.png')
py, sy, ay = HEIGHT // 2, 0, 0 #Значение по py, sy, ay
player = pygame.Rect(HEIGHT // 3, py, 50, 50) #расположение игрока по центру


state = 'start'#состояние старта
timer = 10 #Задержка


pipes = [] #Список труб
bges = [] #Список заднего фона

bges.append(pygame.Rect(0, 0, 288, 600)) #Отображение заднего фона

lives = 3 #Жизни
scores = 0 #Очки

play = True
while play:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            play = False

    press = pygame.mouse.get_pressed() #Нажатие мыши 
    keys = pygame.key.get_pressed() #Нажатие пробела
    click = press[0] or keys[pygame.K_SPACE]

    if timer > 0:
        timer -= 1


    
    for i in range(len(bges)-1, -1, -1): #Проверка на удаление и добавление фона 
        fon = bges[i]
        fon.x -= 1

        if fon.right < 0:
            bges.remove(fon)

        if bges[len(bges)-1].right <= WIDTH:
            bges.append(pygame.Rect(bges[len(bges)-1].right, 0, 288, 512))##########


    for i in range(len(pipes)-1, -1, -1): #Добавление и удаление труб 
        pipe = pipes[i]
        pipe.x -= 3

        if pipe.right < 0:
            pipes.remove(pipe)###################

    if state == 'start':#Состояние статического 
        if click and timer == 0 and len(pipes) == 0:
            state = 'play'

        py += (HEIGHT // 2 - py) * 0.1
        player.y = py

    elif state == 'play': #Состояние если игрок нажимает на кнопку то оно переходит в состояние игры
        if click:
            ay = -2
        else:
            ay = 0

        py += sy
        sy = (sy + ay + 1) * 0.98
        player.y = py 

        if len(pipes) == 0 or pipes[len(pipes)-1].x < WIDTH - 200: #отображение труб
            pipes.append(pygame.Rect(WIDTH, 0, 52, 200))
            pipes.append(pygame.Rect(WIDTH, 400, 52, 200))


        if player.top < 0 or player.bottom > HEIGHT:#Проверка столкновение с трубами
            state = 'fall'

        for pipe in pipes:
            if player.colliderect(pipe):
                state = 'fall'                
        for pipe in pipes:
            if player > pipe:
                scores += 1



    elif state == 'fall':####Состояние когда игрок не может ничего делать 
        sy, ay = 0, 0
        state = 'start'
        timer = 60
    else:
        pass

                

    for fon in bges: #Отображение заднего фона
        window.blit(imgBG, fon)##########
    for pipe in pipes:#Рисовка труб
        if pipe.y == 0:
            rect = imgPB.get_rect(bottomleft = pipe.bottomleft)
            window.blit(imgPB, rect)
        else:
            rect = imgPT.get_rect(topleft = pipe.topleft)
            window.blit(imgPT, rect)##########

    window.blit(imgBIRD, player)#Рисовка игрока

    text = font1.render('Очки: ' + str(scores), 1, pygame.Color('White')) #Текст очки 
    window.blit(text, (10, 10))

    text = font1.render('Жизни: ' + str(lives), 1, pygame.Color('White'))#Текст жизни 
    window.blit(text, (110, 10))

    pygame.display.update()#Обновление экрана 
    clock.tick(FPS)

 pygame.quit()

代码分数

for pipe in pipes:
    if player > pipe:
        scores += 1

I'm making a game for Flappy Bird, I need to make a score counter, it's there, but it's crooked. It counts a whole bunch of points after the first pipe and does not reset them after death. Below I will attach the code itself and the code of the points.

If you can write the code as it will be correct.

import pygame#импортирование модуля pygame
import random#Добавляет возможность спавнить разные трубы
pygame.init()

WIDTH, HEIGHT = 800, 600#FPS и размеры окна
FPS = 60

window = pygame.display.set_mode((WIDTH, HEIGHT))#Создание окна
clock = pygame.time.Clock()

font1 = pygame.font.Font(None, 35)#шрифты
font2 = pygame.font.Font(None, 80)

imgBG = pygame.image.load('images/fon.png')#Добавление картинок
imgBIRD = pygame.image.load('images/bird.png')
imgPB = pygame.image.load('images/PB.png')
imgPT = pygame.image.load('images/PT.png')
py, sy, ay = HEIGHT // 2, 0, 0 #Значение по py, sy, ay
player = pygame.Rect(HEIGHT // 3, py, 50, 50) #расположение игрока по центру


state = 'start'#состояние старта
timer = 10 #Задержка


pipes = [] #Список труб
bges = [] #Список заднего фона

bges.append(pygame.Rect(0, 0, 288, 600)) #Отображение заднего фона

lives = 3 #Жизни
scores = 0 #Очки

play = True
while play:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            play = False

    press = pygame.mouse.get_pressed() #Нажатие мыши 
    keys = pygame.key.get_pressed() #Нажатие пробела
    click = press[0] or keys[pygame.K_SPACE]

    if timer > 0:
        timer -= 1


    
    for i in range(len(bges)-1, -1, -1): #Проверка на удаление и добавление фона 
        fon = bges[i]
        fon.x -= 1

        if fon.right < 0:
            bges.remove(fon)

        if bges[len(bges)-1].right <= WIDTH:
            bges.append(pygame.Rect(bges[len(bges)-1].right, 0, 288, 512))##########


    for i in range(len(pipes)-1, -1, -1): #Добавление и удаление труб 
        pipe = pipes[i]
        pipe.x -= 3

        if pipe.right < 0:
            pipes.remove(pipe)###################

    if state == 'start':#Состояние статического 
        if click and timer == 0 and len(pipes) == 0:
            state = 'play'

        py += (HEIGHT // 2 - py) * 0.1
        player.y = py

    elif state == 'play': #Состояние если игрок нажимает на кнопку то оно переходит в состояние игры
        if click:
            ay = -2
        else:
            ay = 0

        py += sy
        sy = (sy + ay + 1) * 0.98
        player.y = py 

        if len(pipes) == 0 or pipes[len(pipes)-1].x < WIDTH - 200: #отображение труб
            pipes.append(pygame.Rect(WIDTH, 0, 52, 200))
            pipes.append(pygame.Rect(WIDTH, 400, 52, 200))


        if player.top < 0 or player.bottom > HEIGHT:#Проверка столкновение с трубами
            state = 'fall'

        for pipe in pipes:
            if player.colliderect(pipe):
                state = 'fall'                
        for pipe in pipes:
            if player > pipe:
                scores += 1



    elif state == 'fall':####Состояние когда игрок не может ничего делать 
        sy, ay = 0, 0
        state = 'start'
        timer = 60
    else:
        pass

                

    for fon in bges: #Отображение заднего фона
        window.blit(imgBG, fon)##########
    for pipe in pipes:#Рисовка труб
        if pipe.y == 0:
            rect = imgPB.get_rect(bottomleft = pipe.bottomleft)
            window.blit(imgPB, rect)
        else:
            rect = imgPT.get_rect(topleft = pipe.topleft)
            window.blit(imgPT, rect)##########

    window.blit(imgBIRD, player)#Рисовка игрока

    text = font1.render('Очки: ' + str(scores), 1, pygame.Color('White')) #Текст очки 
    window.blit(text, (10, 10))

    text = font1.render('Жизни: ' + str(lives), 1, pygame.Color('White'))#Текст жизни 
    window.blit(text, (110, 10))

    pygame.display.update()#Обновление экрана 
    clock.tick(FPS)

 pygame.quit()

Code scores

for pipe in pipes:
    if player > pipe:
        scores += 1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦幻的味道 2025-01-23 18:52:34

您应该替换 if player >管道:if pipeline.x player <= (pipe.x + 3): 来修复游戏,添加一堆分数(而不是为到目前为止通过的每个管道的分数加 1,如果您,它会加 1在管道中)。
根据管道的速度更改 pipe + 33(在您的程序中,它是 3,所以我输入 3)。

对于未重置的分数,我建议将其替换

elif state == 'fall'
        sy, ay = 0, 0
        state = 'start'
        timer = 60

elif state == 'fall'
        sy, ay = 0, 0
        state = 'start'
        timer = 60
        scores = 0

假设这是在“死亡”时执行操作的部分。

不确定它会起作用,但可能会。

编辑:
对于诸如 TypeError 之类的任何问题,请将之前测试中的 pipe 替换为 pipe.xif pipeline <="(pipe" +="" 3):<="" code="">) 因此它给出 if pipeline.x 玩家 <= (pipe.x + 3):。现在应该可以工作了...

You should replace if player > pipe: with if pipe.x < player <= (pipe.x + 3): to fix the game adding a bunch of points (instead of adding 1 to the score for each pipe passed so far, it adds 1 if you're in a pipe).
Change the 3 of pipe + 3 by the speed of your pipes (in case of your program it's 3 so I put 3).

For the score not resetting, I suggest replacing this

elif state == 'fall'
        sy, ay = 0, 0
        state = 'start'
        timer = 60

by this

elif state == 'fall'
        sy, ay = 0, 0
        state = 'start'
        timer = 60
        scores = 0

assuming this is the part that does stuff upon 'death'.

Not sure it'll work, but it may.

EDIT:
For any problems like TypeError, replace the pipe by pipe.x in the previous test (if pipe < player <= (pipe + 3):) so it gives if pipe.x < player <= (pipe.x + 3):. It should work now...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文