最近一個星期學習了一下python的pygame模塊,順便做個小程序鞏固所學的,運行效果如下:
其中,背景圖"highway.jpg"是使用PhotoShop將其分辨率改變為640 × 480,而小車"car.png"則是將其轉變為png格式的圖片,並且填充其背景色,讓其擁有透明性。
==========================================
代碼
==========================================
# -*- coding: utf-8 -*- # 背景圖以及移動小車圖 highway_image_name = "highway.jpg" car_image_name = "car.png" # 導入程序相關的模塊 import pygame from pygame.locals import * from sys import exit pygame.init() # 生成窗口以及窗口標題 screen = pygame.display.set_mode((640, 480), 0, 32) pygame.display.set_caption("Little Case") # 加載並轉換圖片 highway = pygame.image.load(highway_image_name).convert() car = pygame.image.load(car_image_name).convert_alpha() x = 0 y = 300 z = 1 # 加載以及渲染字體 my_font = pygame.font.SysFont("arial", 16) text_surface = my_font.render(("%d car" % (z)), True, (0, 0, 255)) # 主循環 while True: for event in pygame.event.get(): if event.type == QUIT: pygame.display.quit() exit() # 矩形顏色坐標等 rc = (0, 250, 0) rp = (560, 0) rs = (639, 60) x += 0.2 if x > 640 + car.get_width(): x = -car.get_width() z += 1 text_surface = my_font.render(("%d cars" % z), True, (0, 0, 255)) screen.blit(highway, (0, 0)) screen.blit(text_surface, (620 - text_surface.get_width(), text_surface.get_height())) screen.blit(car, (x, y)) pygame.draw.rect(screen, rc, Rect(rp, rs), 1) # Rect(左上角的坐標,右下角的坐標) pygame.display.update()
兩張圖片:
highway.jpg
car.png