0

I have to move the rectangular object straight through the pygame window. I have tried some code with pygame. The code is

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)

Here the image didnt moves. What I need is that the image must be moved in a straight way.

4

3 回答 3

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)
于 2014-07-11T17:30:01.333 回答
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)

顺便提一句:

  • 不要raise用于退出程序。
  • 使用可读变量 - 不是s_rscreen_rect
  • 你不需要x- 你有player.x
  • 您只能创建一次矩形
  • 向问题添加代码时删除重复的空行
于 2014-07-11T18:09:39.863 回答
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)
于 2014-07-11T17:34:47.707 回答