【pygame游戲編程】第二篇-----移動圖像


 Learning From Here

 

import pygame
import sys

pygame.init()

screen_width = 640
screen_high = 480

screen = pygame.display.set_mode((screen_width, screen_high))
screen_rect = screen.get_rect()

pygame.display.set_caption("Moving Fish")

background_image_filename = 'sushiplate.png'
mouse_image_fliename = 'fugu.png'

background_image = pygame.image.load(background_image_filename).convert()
mouse_image = pygame.image.load(mouse_image_fliename).convert_alpha()

mouse_image_rect = mouse_image.get_rect()

clock = pygame.time.Clock()

while True:

    #限制每秒循環100次,防止大量占用cpu
    clock.tick(100)

    for event in pygame.event.get():

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

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                pygame.quit()
                sys.exit()

    screen.blit(background_image, (0, 0))

    #獲取鼠標位置
    x, y = pygame.mouse.get_pos()

    mouse_image_rect.center = (x, y)

    #設置圖片移動邊界
    if mouse_image_rect.left < 0:
        mouse_image_rect.left = 0
    if mouse_image_rect.right > screen_rect.right:
        mouse_image_rect.right = screen_rect.right
    if mouse_image_rect.top < 0:
        mouse_image_rect.top = 0
    if mouse_image_rect.bottom > screen_rect.bottom:
        mouse_image_rect.bottom = screen_rect.bottom

    screen.blit(mouse_image, mouse_image_rect)

    pygame.display.update()

 

運行截圖:

 

 

本次使用的兩張圖片資源:

背景:sushiplate.jpg

光標:fugu.png


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM