python pygame實現控制物體移動

本文實例為大傢分享瞭python pygame控制物體移動的具體代碼,供大傢參考,具體內容如下

import pygame
import sys
from pygame.locals import *

pygame.init()

size = width,hight = 600,400
speed = [-2,1]
by = (255,255,255)

screen = pygame.display.set_mode(size)

pygame.display.set_caption("移動皮卡丘")

#這個將圖片路徑,改為自己想要的物體的路徑
pp = pygame.image.load("E:\python\Python練習\imgs\pp.jpg")

position = pp.get_rect()

l_head = pp
r_head = pygame.transform.flip(pp,True,False)

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

        if event.type == KEYDOWN:
            if event.key == K_LEFT:
                speed = [-1,0]
            if event.key == K_RIGHT:
                speed = [1,0]
            if event.key == K_UP:
                speed = [0,-1]
            if event.key == K_DOWN:
                speed = [0,1]

    position = position.move(speed)

    if position.left < 0 or position.right > width:
        pp = pygame.transform.flip(pp,True,False)
        speed[0] = -speed[0]

    if position.top < 0 or position.bottom > hight :
        speed[1] = -speed[1]

    screen.fill(by)

    screen.blit(pp,position)

    pygame.display.flip()

    pygame.time.delay(10)

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: