在Pygame中跨屏幕移动对象

时间:2011-12-09 22:11:50

标签: python pygame

所以我试图在屏幕上任意方向移动这两个多边形,一个圆圈和一条线的随机混乱,当它到达屏幕的末端时,它被放回到屏幕上并再次移动。简单地说,我想在屏幕上移动这些形状。我无法弄清楚如何,我是pygame的新手所以这一切都有点令人困惑但这是我到目前为止所做的。

import pygame, sys, time, random
from pygame.locals import *

pygame.init()

windowSurface = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption("Paint")

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

windowSurface.fill(WHITE)

info = pygame.display.Info()
sw = info.current_w
sh = info.current_h

x = y = 0

dx = 5
dy = 2


while True:

    pygame.draw.polygon(windowSurface,BLUE,((0+x,250+y),(120+x,120+y),(55+x,55+y)))
    pygame.draw.polygon(windowSurface,RED,((0+x,150+y),(85+x,85+y),(100+x,175+y),(0+x,150+y)))
    pygame.draw.line(windowSurface,BLACK,(60+x,85+y), (120+x, 110+x), 6)
    pygame.draw.circle(windowSurface, GREEN , (75+x,100+y), 13, 0)

    x += dx
    y += dy

    if x - dx < 0 or x + dx > sw:
        dx = -dx
    if y - dy < 0 or y + dy > sh:
        dy = -dy


    pygame.display.update()

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

1 个答案:

答案 0 :(得分:2)

您可能希望每次重绘时都清除屏幕。

while True:
    windowSurface.fill(WHITE) #This clears the screen on each redraw
    pygame.draw.polygon(windowSurface,BLUE,((0+x,250+y),(120+x,120+y),(55+x,55+y)))
    pygame.draw.polygon(windowSurface,RED,((0+x,150+y),(85+x,85+y),(100+x,175+y),(0+x,150+y)))
    pygame.draw.line(windowSurface,BLACK,(60+x,85+y), (120+x, 110+y), 6)
    pygame.draw.circle(windowSurface, GREEN , (75+x,100+y), 13, 0)

另外,查看该行的坐标。我已将端点更改为     (120 + x,110 + y)

如果你将边缘检测改为此,你的形状将主要留在窗口

if x < 0 or x > sw-120:
    dx = -dx
    x += dx
if y < -85 or y > sh-175:
    dy = -dy
    y += dy