使用pygame直接移动图像

时间:2014-07-11 17:24:55

标签: python pygame pygame-surface

我必须将矩形对象直接移动到pygame窗口。我用pygame尝试了一些代码。代码是

import pygame
from itertools import cycle

pygame.init() 
screen = pygame.display.set_mode((300, 300)) 
s_r = screen.get_rect()
player = pygame.Rect((100, 100, 50, 50))

timer = pygame.time.Clock()

movement = "straight"

x = 0

while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            raise

    if movement == 'straight':
      x += 50

    screen.fill(pygame.color.Color('Black'))
    pygame.draw.rect(screen, pygame.color.Color('Grey'), player)

    pygame.display.flip()
    timer.tick(25)

这里的图像没有移动。我需要的是图像必须以直线方式移动。

3 个答案:

答案 0 :(得分:1)

x正在添加,但这不会影响player,这实际上会影响矩形的绘制。

import pygame
from itertools import cycle

pygame.init() 
screen = pygame.display.set_mode((300, 300)) 
s_r = screen.get_rect()


timer = pygame.time.Clock()

movement = "straight"

x = 0
player = pygame.Rect((x, 100, 50, 50))

while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            raise

    if movement == 'straight':
      x += 10
      player = pygame.Rect((x, 100, 50, 50))

    if x >= 300:
      x = 0





    screen.fill(pygame.color.Color('Black'))
    pygame.draw.rect(screen, pygame.color.Color('Grey'), player)

    pygame.display.flip()
    timer.tick(25)

答案 1 :(得分:0)

每次更改player时,都需要调整x矩形。从http://www.pygame.org/docs/ref/rect.html开始,您可以看到前两个参数是“left”和“top”。所以,如果你想让矩形从左向右移动,你会想要这样的东西:

player = pygame.Rect((100 + x, 100, 50, 50))
pygame.draw.rect(screen, pygame.color.Color('Grey'), player)

答案 2 :(得分:0)

import pygame

BLACK = pygame.color.Color('Black')
GREY  = pygame.color.Color('Grey')

pygame.init() 

screen = pygame.display.set_mode((300, 300)) 
screen_rect = screen.get_rect()

timer = pygame.time.Clock()

movement = "straight"

player = pygame.Rect(0, 100, 50, 50) # four aguments in place of tuple (,,,)

running = True

while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    if movement == 'straight':
        player.x += 10
        if player.x >= 300: # check only when `player.x` was changed 
            player.x = 0

    screen.fill(BLACK)
    pygame.draw.rect(screen, GREY, player)

    pygame.display.flip()

    timer.tick(25)

BTW:

  • 不要使用raise退出程序。
  • 使用可读变量 - 不是s_r而是screen_rect
  • 您不需要x - 您有player.x
  • 您只能创建一次矩形
  • 在向问题
  • 添加代码时删除重复的空行