您好,登錄后才能下訂單哦!
Pygame是跨平臺(tái)Python模塊,專為電子游戲設(shè)計(jì),包含圖像、聲音。建立在SDL基礎(chǔ)上,允許實(shí)時(shí)電子游戲研發(fā)而無需被低級(jí)語言(如機(jī)器語言和匯編語言)束縛。
最近一個(gè)星期學(xué)習(xí)了一下python的pygame模塊,順便做個(gè)小程序鞏固所學(xué)的,運(yùn)行效果如下:
其中,背景圖"highway.jpg"是使用PhotoShop將其分辨率改變?yōu)?40 × 480,而小車"car.png"則是將其轉(zhuǎn)變?yōu)閜ng格式的圖片,并且填充其背景色,讓其擁有透明性。
代碼測(cè)試可用:
# -*- coding: utf-8 -*- # 背景圖以及移動(dòng)小車圖 highway_image_name = "highway.jpg" car_image_name = "car.png" # 導(dǎo)入程序相關(guān)的模塊 import pygame from pygame.locals import * from sys import exit pygame.init() # 生成窗口以及窗口標(biāo)題 screen = pygame.display.set_mode((640, 480), 0, 32) pygame.display.set_caption("Little Case") # 加載并轉(zhuǎn)換圖片 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)) # 主循環(huán) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.display.quit() exit() # 矩形顏色坐標(biāo)等 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(左上角的坐標(biāo),右下角的坐標(biāo)) pygame.display.update()
兩張圖片:
highway.jpg
car.png
路徑自己保存,然后在代碼中修改即可。
總結(jié)
以上就是本文關(guān)于Python編程pygame模塊實(shí)現(xiàn)移動(dòng)的小車示例代碼的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。