Python編程pygame模組實現移動的小車範例程式碼,pythonpygame

來源:互聯網
上載者:User

Python編程pygame模組實現移動的小車範例程式碼,pythonpygame

Pygame是跨平台Python模組,專為電子遊戲設計,包含映像、聲音。建立在SDL基礎上,允許即時電子遊戲研發而無需被低級語言(如機器語言和組合語言)束縛。

最近一個星期學習了一下python的pygame模組,順便做個小程式鞏固所學的,運行效果如下:

其中,背景圖"highway.jpg"是使用PhotoShop將其解析度改變為640 × 480,而小車"car.png"則是將其轉變為png格式的圖片,並且填充其背景色,讓其擁有透明性。

代碼測試可用:

# -*- coding: utf-8 -*-# 背景圖以及移動小車圖highway_image_name = "highway.jpg"car_image_name = "car.png"# 匯入程式相關的模組import pygamefrom pygame.locals import *from sys import exitpygame.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 = 0y = 300z = 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

路徑自己儲存,然後在代碼中修改即可。

總結

以上就是本文關於Python編程pygame模組實現移動的小車範例程式碼的全部內容,希望對大家有所協助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.