【问题标题】:Python Pong Game Using Pygame使用 Pygame 的 Python Pong 游戏
【发布时间】:2021-03-20 20:08:44
【问题描述】:

我一直在制作这款乒乓球游戏,但我不知道如何使击球在击球下方时不会记录到球棒上。有人可以帮我解决吗?

另外,如果你来回移动球棒,你基本上会击中每一个球。

那么有人可以帮我解决这两个问题吗?

代码:


import pygame
import sys
import pygame.freetype

circle_x= 250
circle_y= 250

pygame.init()
pygame.mixer.init()

mp3=pygame.mixer.music.load("nana.mp3")
pygame.mixer.music.play()

font = pygame.freetype.Font("msyh.ttc")

screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("game")

move_x = 2
move_y = 2

score = 0
deaths = 0
level = 1

minus1 = -1
minus2 = -1
plus1 = 1
plus2 = 1
minus3 = -1

while True:

    if score >= 50:
        level = 2
        minus1 = -2
        minus2 = -2
        plus1 = 2
        plus2 = 2
        minus3 = -2

    mouse_x,mouse_y = pygame.mouse.get_pos()
    
    screen.fill((255,255,255))
    pygame.draw.circle(screen,(100,100,100),(circle_x,circle_y),20)
    pygame.draw.rect(screen,(255,0,0),(mouse_x,500,100,10))

    circle_x = circle_x+move_x
    circle_y = circle_y+move_y
    
    font_image,font_rect = font.render('Score: '+str(score),fgcolor=(0,0,0),size=30)
    font_image1,font_rect1 = font.render('Deaths: '+str(deaths),fgcolor=(0,0,0),size=30)
    font_image2,font_rect2 = font.render('Level: '+str(level),fgcolor=(0,0,0),size=30)
    screen.blit(font_image,(20,10))
    screen.blit(font_image1,(600,10))
    screen.blit(font_image2,(300,10))
    
    if circle_x>800:
        move_x = minus1
    if circle_y>600:
        score = 0
        deaths += 1
        move_y = -50
    if circle_y<0:
        move_y= plus1
    if circle_x<0:
        move_x = plus2      

    if circle_y >= 500 and mouse_x <= circle_x <= mouse_x+100:
        if move_y > 0:
            score += 5
        move_y = -1
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
            pygame.quit()
    pygame.display.update()

【问题讨论】:

  • 欢迎来到 StackOverflow。请你把问题隔离开来好吗?阅读如何在stackoverflow.com/help/mcve 创建一个最小、完整和可验证的示例。

标签: python pygame python-2.x


【解决方案1】:

这实际上非常简单,几乎没有不便。查看您的代码的这一部分:

    if circle_y >= 500 and mouse_x <= circle_x <= mouse_x+100:
        if move_y > 0:
            score += 5
        move_y = -1

如果球的y 坐标位于或超过踏板的y 坐标,则您使球反弹。

相反,只有当球的y 坐标位于踏板的y 坐标(包括踏板的宽度)上时,它才会反弹。

你的踏板是10像素宽,所以添加另一个条件500 + 10 &gt;= circle_y

    if 510 >= circle_y >= 500 and mouse_x <= circle_x <= mouse_x+100:
        if move_y > 0:
            score += 5
        move_y = -1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-07
    • 2018-11-04
    • 1970-01-01
    • 2020-07-26
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    相关资源
    最近更新 更多