Why pygame?
最近開(kāi)始學(xué)Python游戲編程,自然選擇了pygame竿刁。pygame 可以寫(xiě)游戲,也可以做仿真食拜。
參考 pygame開(kāi)發(fā)自己的游戲 系列文章
一張圖看懂pygame編程
pygame程序里都是些什么?
pygame.jpg
源代碼
一個(gè)紅色小方塊垂直下落流强,如果和在底下的藍(lán)色大方塊碰撞在一起就終止打月,否則紅色小方塊重新下落一次蚕捉。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pygame, sys
# 初始化
pygame.init()
SCREEN = pygame.display.set_mode((400, 300))
pygame.display.set_caption('紅藍(lán)大碰撞')
# 藍(lán)色方塊固定在最下方,左右移動(dòng)迫淹,y值不變
blue_rect = pygame.Rect(110, 250, 100, 50)
red_rect = pygame.Rect(85, 0, 20, 50)
goal = False
while True:
for event in pygame.event.get():
# 處理退出事件
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 鍵盤按下事件
elif event.type == pygame.KEYDOWN:
# 'a'鍵被按下
if event.key == pygame.K_a:
blue_rect.x -= 5
elif event.key == pygame.K_d:
blue_rect.x += 5
red_rect.y += 5
if red_rect.y > 300:
red_rect.y = 0
red_rect = pygame.Rect(85, red_rect.y, 20, 50)
if blue_rect.colliderect(red_rect) or goal is True:
goal = True
else:
SCREEN.fill((255, 255, 255))
# 調(diào)用 pygame.display.update() 方法更新整個(gè)屏幕的顯示
pygame.draw.rect(SCREEN, (255, 0, 0), red_rect)
pygame.draw.rect(SCREEN, (0, 0, 255), blue_rect)
pygame.display.update()
pygame.time.delay(50)