溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在python3中利用pygame實現(xiàn)一個接小球游戲

發(fā)布時間:2021-04-20 16:15:51 來源:億速云 閱讀:139 作者:Leah 欄目:開發(fā)技術(shù)

怎么在python3中利用pygame實現(xiàn)一個接小球游戲?針對這個問題,這篇文章詳細介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

# -*- coding:utf-8 -*-
import sys,pygame,random #導(dǎo)入庫
from pygame.locals import *
 
def print_text(font,x,y,text,color=(255,255,255)):
 imgText = font.render(text,True,color) # 創(chuàng)建字體,三個參數(shù)是文本.抗鋸齒.顏色
 screen.blit(imgText,(x,y)) #built screen 創(chuàng)建文本窗口
 
pygame.init() #init 初始化
 
#窗口設(shè)置
screen = pygame.display.set_mode((600,500))#screen-size 窗口大小設(shè)置
pygame.display.set_caption('BallFall') #title 窗口標(biāo)題
font1 = pygame.font.Font(None,24) #font,size 字體類型(None為pygame默認字體).字體大小
pygame.mouse.set_visible(False) #mouse-visible 光標(biāo)可視
 
#顏色設(shè)置
white = 255,255,255 #rgb 
red = 220,50,50
yellow = 230,230,50
blue = 0,0,100
 
#計數(shù)設(shè)置
lives = 3 #初始生命
score = 0 #初始分數(shù)
 
#初始化設(shè)置
game_over = True #游戲結(jié)束判斷
mouse_x = mouse_y = 0 #光標(biāo)初始化
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: #鼠標(biāo)運動
 mouse_x,mouse_y = event.pos 
 elif event.type == MOUSEBUTTONUP: #鼠標(biāo)抬起
 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) #小球隨機出現(xiàn)
 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) #繪制圓形 五個參數(shù)為屏幕.顏色.位置.實心半徑.空心半徑
 
 pos_x = mouse_x #擋板位置變化設(shè)置
 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) #繪制矩形 參數(shù)跟圓形一樣
 
 print_text(font1,0,0,'Lives:' + str(lives)) #文字顯示
 print_text(font1,500,0,'Score:' + str(score))
 
 pygame.display.update() #更新

關(guān)于怎么在python3中利用pygame實現(xiàn)一個接小球游戲問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI