创建一个矩形,用方向键控制移动,但是总是移动不了
import pygame
import sys
screen=pygame.display.set_mode((800,600))
pygame.display.set_caption("弹弹球")
pygame.init()
# 窗口大小
WIDTH, HEIGHT = 800, 600
# 颜色定义
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 类定义
class Ball:
def __init__(self, x, y, dx, dy):
self.x = x
self.y = y
self.dx = dx
self.dy = dy
def move(self):
self.x += self.dx
self.y += self.dy
def draw(self, screen):
pygame.draw.circle(screen, RED, (int(self.x), int(self.y)), 15)
class My_rectang:
def __init__ (self, x, y):
self.x=int(x)
self.y=int(y)
self.rec=pygame.Rect(self.x,self.y,100,40)
def move(self,dx): #传参,dx为正,向右移动,dx为负数向左移动
self.x+=dx
def draw(self,screen):
pygame.draw.rect(screen,(255,0,0),self.rec)
![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/992861591796110.png "#left")
def main():
#pygame.init()
#screen = pygame.display.set_mode((WIDTH, HEIGHT))
rec=My_rectang(400,300)
clock = pygame.time.Clock()
ball = Ball(WIDTH / 2, HEIGHT /2, 1, 1) # 初始化小球,位置在窗口中心,速度为2像素/帧
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE: # 按ESC退出游戏
pygame.quit()
sys.exit()
elif event.key == pygame.K_LEFT: # 按左箭头,小球向左移动
ball.dx -= 5
rec.move(-50)
elif event.key == pygame.K_RIGHT: # 按右箭头,小球向右移动
ball.dx += 5
rec.move(50)
elif event.key == pygame.K_UP: # 按上箭头,小球向上移动
ball.dy -= 5
elif event.key == pygame.K_DOWN: # 按下箭头,小球向下移动
ball.dy += 5
ball.move() # 根据速度更新小球的位置
screen.fill(WHITE) # 清空屏幕
ball.draw(screen) # 在屏幕上绘制小球
rec.draw(screen)
pygame.display.update() # 更新屏幕显示内容
clock.tick(60) # 控制帧率,这里设置为60帧/秒
if __name__ == "__main__":
main()