/ 猿问

在Pygame中每隔几秒钟移动一个对象

2019-12-06 15:20:23

3 回答

pygame.time.set_timer（）

set_timer(eventid, milliseconds) -> None

import pygame

# you'll be able to shoot every 450ms

# the foes move every 1000ms sideways and every 3500ms down

MOVE_SIDE = 1000

MOVE_DOWN = 3500

screen = pygame.display.set_mode((300, 200))

clock = pygame.time.Clock()

# create a bunch of events

move_side_event = pygame.USEREVENT + 1

move_down_event = pygame.USEREVENT + 2

invaders, colors, shots = [], [] ,[]

for x in range(15, 300, 15):

for y in range(10, 100, 15):

colors.append(((x * 0.7) % 256, (y * 2.4) % 256))

# set timer for the movement events

pygame.time.set_timer(move_side_event, MOVE_SIDE)

pygame.time.set_timer(move_down_event, MOVE_DOWN)

player = pygame.Rect(150, 180, 10, 7)

while True:

clock.tick(40)

if pygame.event.get(pygame.QUIT): break

for e in pygame.event.get():

if e.type == move_side_event:

invader.move_ip((-10 if move_left else 10, 0))

move_left = not move_left

elif e.type == move_down_event:

# when the reload timer runs out, reset it

for shot in shots[:]:

shot.move_ip((0, -4))

if not screen.get_rect().contains(shot):

shots.remove(shot)

else:

hit = False

hit = True

del colors[i]

if hit:

shots.remove(shot)

pressed = pygame.key.get_pressed()

if pressed[pygame.K_LEFT]: player.move_ip((-4, 0))

if pressed[pygame.K_RIGHT]: player.move_ip((4, 0))

if pressed[pygame.K_SPACE]:

shots.append(player.copy())

# when shooting, create a timeout of RELOAD_SPEED

player.clamp_ip(screen.get_rect())

screen.fill((0, 0, 0))

for shot in shots:

pygame.draw.rect(screen, (255, 180, 0), shot)

pygame.draw.rect(screen, (180, 180, 180), player)

pygame.display.flip()

var = 0

while True:

event_handling()

game_logic()

if var == 5:

sprite.update.position()

var = 0

pygame.display.flip()

var += 1

aluckdog

• 3 回答
• 0 关注
• 679 浏览

0/150