1. 程式人生 > >自我記錄:python3 pygame 接小球遊戲

自我記錄:python3 pygame 接小球遊戲

接小球遊戲:

操作方法:滑鼠操作

截圖:



直接放程式碼:


# -*- coding:utf-8 -*-
import sys,pygame,random #匯入庫
from pygame.locals import *

def print_text(font,x,y,text,color=(255,255,255)):
	imgText = font.render(text,True,color) # 建立字型,三個引數是文字.抗鋸齒.顏色
	screen.blit(imgText,(x,y)) #built screen 建立文字視窗

pygame.init() #init 初始化

#視窗設定
screen = pygame.display.set_mode((600,500))#screen-size 視窗大小設定
pygame.display.set_caption('BallFall') #title 視窗標題
font1 = pygame.font.Font(None,24) #font,size 字型型別(None為pygame預設字型).字型大小
pygame.mouse.set_visible(False) #mouse-visible 游標可視

#顏色設定
white = 255,255,255 #rgb 
red = 220,50,50
yellow = 230,230,50
blue = 0,0,100

#計數設定
lives = 3 #初始生命
score = 0 #初始分數

#初始化設定
game_over = True #遊戲結束判斷
mouse_x = mouse_y = 0 #游標初始化
pos_x = 300	#擋板位置初始化
pos_y = 460 
bomb_x = random.randint(0,500) #小球位置隨機初始化
bomb_y = -50 #小球下落高度初始化
vel_y = 0.3 #小球下落速度

while True:
	for event in pygame.event.get(): #事件判斷
		if event.type == QUIT:
			pygame.quit()
			sys.exit()
		elif event.type == MOUSEMOTION: #滑鼠運動
			mouse_x,mouse_y = event.pos 
		elif event.type == MOUSEBUTTONUP: #滑鼠擡起
			if game_over:
				game_over = False
				lives = 3
				score = 0

	keys = pygame.key.get_pressed() #獲取鍵盤
	if keys[K_ESCAPE]: #鍵盤右上角esc鍵
		pygame.quit()
		sys.exit()

	screen.fill(blue) #背景顏色

	if game_over:
		print_text(font1,100,200,'click to play')
	else: #判斷小球執行軌跡
		bomb_y += vel_y
		if bomb_y > 500: #fallen
			bomb_x = random.randint(0,500) #小球隨機出現
			bomb_y = -50
			lives -= 1
			if lives == 0:
				game_over = True
		elif bomb_y > pos_y:
			if bomb_x > pos_x and bomb_x < pos_x + 120:
				score += 1
				bomb_x = random.randint(0,500)
				bomb_y = -50	

	pygame.draw.circle(screen,yellow,(bomb_x,int(bomb_y)),30,0) #繪製圓形 五個引數為螢幕.顏色.位置.實心半徑.空心半徑

	pos_x = mouse_x #擋板位置變化設定
	if pos_x < 0:
		pos_x = 0
	elif pos_x > 500:
		pos_x = 500

	pygame.draw.rect(screen,red,(pos_x,pos_y,120,40),0) #繪製矩形 引數跟圓形一樣

	print_text(font1,0,0,'Lives:' + str(lives)) #文字顯示
	print_text(font1,500,0,'Score:' + str(score))

	pygame.display.update() #更新