乒乓球游戏中的移动球-Pygame



我是Pygame的新手,刚开始开发Pong Game。以下代码尚未完成,但由于某种原因,球无法移动。只有当我设置";ball_draw=pygame"在";draw_ball";方法,而不是初始化方法。然而,如果我这样做,我就不能使用";wallCollision;方法,因为";ball_draw";将是一个局部变量,而不是整个类的属性,因此在其他方法中不可访问。我该怎么解决这个问题?我感谢你的帮助。

import pygame, sys
pygame.init()
clock = pygame.time.Clock()
screen_width = 1280
screen_height = 960
bgColor = pygame.Color("grey12")
lightGrey = (200, 200, 200)
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Pong Game")
class BALL:
def __init__(self):
self.ball_width = 30
self.ball_height = 30
self.ball_x = screen_width/2 - self.ball_width
self.ball_y = screen_height/2 - self.ball_height
self.ball_speed_x = 7
self.ball_speed_y = 7
self.ball_draw = pygame.Rect(self.ball_x, self.ball_y, self.ball_width, self.ball_height)
def draw_ball(self):
pygame.draw.ellipse(screen, lightGrey, self.ball_draw)
def move_ball(self):
self.ball_x += self.ball_speed_x
self.ball_y += self.ball_speed_y
def wallCollision(self):
if self.ball_draw.bottom >= screen_height:
self.ball_speed_y *= -1
if self.ball_draw.top <= 0:
self.ball_speed_y *= -1
if self.ball_draw.left <= 0:
self.ball_speed_x *= -1
if self.ball_draw.right >= screen_width:
self.ball_speed_x *= -1
class PLAYER1:
def __init__(self):
self.player1_width = 10
self.player1_height = 140
self.player1_x = screen_width - 20
self.player1_y = screen_height/2 - 70
def draw_player1(self):
player1_draw = pygame.Rect(self.player1_x, self.player1_y, self.player1_width, self.player1_height)
pygame.draw.rect(screen, lightGrey, player1_draw)
def move_player1(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_UP] and self.player1_y >= 0:
self.player1_y -= 5
if keys[pygame.K_DOWN] and self.player1_y <= screen_height:
self.player1_y += 5
ball = BALL()
player1 = PLAYER1()
while True:
# Checking for events
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Drawing on screen
screen.fill(bgColor)
ball.draw_ball()
player1.draw_player1()
# Movement and Collisions
ball.move_ball()
player1.move_player1()
ball.wallCollision()
# Updating screen
pygame.display.flip()
# Defining 60 frames per second (FPS)
clock.tick(60)

使用矩形属性self.ball_draw来绘制球。因此,如果移动球并更改self.ball_xself.ball_y属性,则需要更新矩形:

class BALL:
# [...]
def draw_ball(self):
pygame.draw.ellipse(screen, lightGrey, self.ball_draw)
def move_ball(self):
self.ball_x += self.ball_speed_x
self.ball_y += self.ball_speed_y
self.ball_draw.topleft = (self.ball_x, self.ball_y)

相关内容

  • 没有找到相关文章

最新更新