1 回答

TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超11個(gè)贊
當(dāng)您更改屬性x和時(shí)y,列表的內(nèi)容pad不會(huì)神奇地改變。
在繪圖之前,您必須更新.pad。例如:
class paddle(object):
# [...]
def draw(self, win):
self.pad = (self.x, self.y, self.width, self.height)
pygame.draw.rect(win, (255,255,255), self.pad)
無(wú)論如何,我建議使用對(duì)象而pygame.Rect不是屬性x、y和width:height
class paddle(object):
def __init__(self, x, y, width, height):
self.rect = pygame.Rect(x, y, width, height)
def draw(self, win):
pygame.draw.rect(win, (255,255,255), self.rect)
class ball(object):
def __init__(self, x, y, side):
self.rect = pygame.Rect(x, y, side, side)
def draw(self, win):
pygame.draw.rect(win, (255,255,255), self.rect)
完整示例:
import pygame
import time
pygame.init()
screenW = 800
screenH = 600
win = pygame.display.set_mode((screenW, screenH))
pygame.display.set_caption("Pong")
clock = pygame.time.Clock()
font = pygame.font.SysFont("comicsans", 20)
paddleW = 20
paddleH = 100
ballSpeed = 15
class paddle(object):
def __init__(self, x, y, width, height):
self.rect = pygame.Rect(x, y, width, height)
def draw(self, win):
pygame.draw.rect(win, (255,255,255), self.rect)
class ball(object):
def __init__(self, x, y, side):
self.rect = pygame.Rect(x, y, side, side)
def draw(self, win):
pygame.draw.rect(win, (255,255,255), self.rect)
def redrawGameWindow():
win.fill((0,0,0))
paddleLeft.draw(win)
paddleRight.draw(win)
theBall.draw(win)
pygame.display.update()
#Main Loop:
paddleLeft = paddle(10, screenH//2, paddleW, paddleH)
paddleRight = paddle(screenW - 10 - paddleW, screenH//2, paddleW, paddleH)
theBall = ball(screenW//2, screenH//2, 30)
run = True
while run:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
print("left up")
print(paddleRight.rect.y)
paddleRight.rect.y -= ballSpeed
elif keys[pygame.K_DOWN]:
print("left down")
print(paddleRight.rect.y)
paddleRight.rect.y += ballSpeed
elif keys[pygame.K_w]:
print("right up")
print(paddleLeft.rect.y)
paddleLeft.rect.y -= ballSpeed
elif keys[pygame.K_s]:
print("right down")
print(paddleLeft.rect.y)
paddleLeft.rect.y += ballSpeed
redrawGameWindow()
pygame.quit()
添加回答
舉報(bào)