【问题标题】:Pong Game Score Keeping in PygamePygame中的乒乓球比赛得分保持
【发布时间】:2016-06-02 05:26:23
【问题描述】:

这是我的程序中控制记分的代码段。问题是它每次碰到右墙和左桨时都会给分数加 1,而且每当它碰到左墙时它也会减一分。当它应该做的就是每次碰到右墙时添加一个。

    FRAMECLOCK = pygame.time.Clock() #set frame rate
    SURFACEDISPLAY = pygame.display.set_mode((WIDTH,HEIGHT)) #Clear the surface on refresh
    pygame.display.set_caption ('Pong') #title of window 

    ballX = WIDTH/2 - PLACEMENTMARKER/2 #ball position on X axis at the start
    ballY = HEIGHT/2 - PLACEMENTMARKER/2 #ball position on Y axis at the start
    playerOnePosition = (HEIGHT - PADDLESIZE) /2 #paddle one position at the start
    playerTwoPosition = (HEIGHT - PADDLESIZE) /2 #paddle two position at the start
    score = 0

    #Sets starting position movement
    ballDirX = -1 #-1 = left 1 = right
    ballDirY = -1 # -1 = up 1 = down

    paddle1 = pygame.Rect(PADDLEDISTANCE,playerOnePosition, PLACEMENTMARKER,PADDLESIZE) #paddle one drawing 
    paddle2 = pygame.Rect(WIDTH - PADDLEDISTANCE - PLACEMENTMARKER, playerTwoPosition, PLACEMENTMARKER,PADDLESIZE) #paddle two drawing 
    ball = pygame.Rect(ballX, ballY, PLACEMENTMARKER, PLACEMENTMARKER)#ball drawing

    Pong() #calling the game surface in main function
    paddles(paddle1) #calling paddle 1 main function
    paddles(paddle2) #calling paddle 2 in main function
    pongball(ball) #calling ball in main function 

    while True: #game Loop
        for event in pygame.event.get(): #Checks to see if program is quit
            if event.type == QUIT:
                pygame.quit()
                sys.exit() #system quit

        Pong() #Otherwise it performs these functions 
        paddles(paddle1)
        paddles(paddle2)
        pongball(ball)

        displayScore(str(score))

【问题讨论】:

  • 您是否在运行 checkscore 后设置分数?调用checkscore的代码在哪里?
  • 我只用这个来调用显示分数 - displayScore(str(score))
  • 不是 displayScore - 你在哪里调用 checkscore?
  • 您能否发布一个最小化的示例,我们可以运行它来复制错误?
  • 我已经编辑了问题。您可以运行该代码并准确查看我遇到的问题

标签: function python-3.x count pygame


【解决方案1】:

checkscore 函数正在重置分数,而不是减去它。当你用桨敲击它时,它也会显式添加一个。

我已经修改了这个函数,只在撞到右边墙时才加,撞到左边时不减:

def checkscore (paddle1, ball, score, ballDirX):
    #this is where the program resets after a point is scored 
    if ball.right == WIDTH - PLACEMENTMARKER:
        score += 1
        return score
    #no points scored, return score unchanged 
    else: return score 

只需将此函数替换为当前的 checkscore() 即可,一切正常

我假设您至少复制了大部分内容,请确保您通读所有内容并尝试理解每一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多