Pygame,制作乒乓球

时间:2020-06-23 15:55:54

标签: pygame

任何人都可以帮助我,我不知道为什么代码无法运行。我觉得这是一个愚蠢的错误,也许更好,第二双眼睛可以帮我忙吗? 就是说我的帖子主要是代码,因此我需要添加一些“描述”,因此您不必阅读此信息,我只是在这样做,这样我就可以发布它。

#my pong game

import pygame, sys
pygame.init()

#global variables
screen_width = 1000
screen_height = 800
game_over = False
ball_speed_x = 15
ball_speed_y = 15
ball_width = 15
ball_height = 15
ball_color = (255,0,0)
ball_posx = int(screen_width/2 - (ball_width / 2))
ball_posy = int(screen_height/2 - (ball_width / 2))





screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('PONG')

#player blueprint
class Player:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.height = 100
        self.width = 20
        self.vel = 15
        self.color = (255,0,0)
        self.player = pygame.Rect(self.x, self.y, self.width, self.height)
    def draw(self):
        pygame.draw.rect(screen, self.color, self.player)

#creating objects
player1 = Player(10, int(screen_height/2 - 5))
player2 = Player(screen_width - 30, int(screen_height/2 - 5))
ball = pygame.Rect(ball_posx, ball_posy, ball_height, ball_width)

        
def player_animation():  
    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        player2.y -= player2.vel
    if keys[pygame.K_DOWN]:
        player2.y += player2.vel
    if keys[pygame.K_w]:
        player1.y -= player1.vel
    if keys[pygame.K_s]:
        player1.y += player1.vel

def ball_animation():
    global ball_posx, ball_width, ball_height, ball_posy, ball_posx, ball_speed_x, ball_speed_y, screen_width, screen_height
    if ball.right >= screen_width - 5:
        ball_speed_x *= -1
    if ball.left <= 10:
        ball_speed_x *= -1
    if ball.bottom >= screen_height - 5:
        ball_speed_y *= -1
    if ball.top <= 5:
        ball_speed_y *= -1
    if player1.player.colliderect(ball):
        ball_speed_x *= -1
    if player2.player.colliderect(ball):
        ball_speed_x *= -1
    
    ball_posx += ball_speed_x
    ball_posy += ball_speed_y
    
    
    
    
while not game_over:
    pygame.time.delay(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True

    screen.fill((0,0,0))
    ball_animation()
    player_animation()
    pygame.draw.ellipse(screen, (255,0,0), ball)
    player1.draw()
    player2.draw()
    pygame.display.update()

pygame.quit()
sys.exit()

1 个答案:

答案 0 :(得分:1)

您的代码中的所有内容都可以正常工作,而绘制功能除外。在玩家类中,您在开始时创建了玩家的矩形,并且在整个游戏中它的x和y值没有更改,您只是在更改用于创建矩形的变量,而应该更改矩形的实际值。 x和y变量。可以通过在播放器类中添加以下两行来解决此问题:

    def draw(self):
        self.player.y = self.y
        self.player.x = self.x
        pygame.draw.rect(screen, self.color, self.player)

self.player.y会将矩形的y值更新为玩家的当前值,以便在正确的位置绘制矩形。

球也有同样的问题,蚀只创建了一次,但是它的x和y值从未更改。 不用写:

ball_posx += ball_speed_x
ball_posy += ball_speed_y

做:

ball.x += ball_speed_x
ball.y += ball_speed_y

直接访问Eclipse的x和y值,因此可以在正确的位置重绘。我进行了此处所述的更改,一切开始正常。