用pygame做一個(gè)滑塊接小球的游戲,供大家參考,具體內(nèi)容如下
先上圖
游戲很簡(jiǎn)單也很弱智,主要用到了pygame畫(huà)圓,畫(huà)方塊,隨機(jī)數(shù)等,可以鍛煉基本的鼠標(biāo)控制,游戲設(shè)計(jì)思維,簡(jiǎn)單地碰撞判斷等,廢話不多說(shuō),上代碼
寫(xiě)之前,先思考能用到哪些參數(shù)
pygame.init()
screen = pygame.display.set_mode((800, 600))
# 生命和得分
lives = 3
score = 0
# 設(shè)置顏色
white = 255, 255, 255
yellow = 255, 255, 0
black = 0, 0, 0
red = 220, 50, 50
# 設(shè)置字體
font = pygame.font.Font(None, 38)
pygame.mouse.set_visible(False)
game_over = True
# 設(shè)置鼠標(biāo)坐標(biāo)及鼠標(biāo)事件參數(shù)
# 鼠標(biāo)坐標(biāo)
mouse_x = mouse_y = 0
# 滑板坐標(biāo)
pos_x = 300
pos_y = 580
# 球坐標(biāo)
ball_x = random.randint(0, 500)
ball_y = -50
# 球半徑
radius = 30
# 下落速度
vel = 0.5
def print_text(font, x, y, text, color=white):
imgText = font.render(text, True, color)
screen.blit(imgText, (x, y))
解釋下:
game_over一開(kāi)始設(shè)置為T(mén)rue 是因?yàn)殚_(kāi)局先停止,等鼠標(biāo)點(diǎn)擊后再開(kāi)始,這也用到當(dāng)死了以后,從新開(kāi)始游戲
pygame.mouse.set_visible(False)是讓鼠標(biāo)不可見(jiàn)
然后是游戲主體部分
# 主循環(huán)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
elif event.type == pygame.MOUSEMOTION:
mouse_x, mouse_y = event.pos
move_x, move_y = event.rel
elif event.type == pygame.MOUSEBUTTONDOWN:
lives = 3
score = 0
game_over = False
keys = pygame.key.get_pressed()
if keys[K_ESCAPE]:
exit()
screen.fill((0, 0, 10))
if game_over:
print_text(font, 220, 300, "Press MouseButton To Start", white)
else:
# 球落到了地上
if ball_y > 600:
ball_y = -50
ball_x = random.randint(0, 800)
lives -= 1
if lives == 0:
game_over = True
# 球被滑板接住了
elif pos_y ball_y and pos_x ball_x pos_x + 120:
score += 10
ball_y = -50
ball_x = random.randint(0, 800)
# 既沒(méi)有落地上也沒(méi)被接住的時(shí)候,則不斷增加y坐標(biāo)數(shù)值使球從頂部落下
else:
ball_y += vel
ball_pos = int(ball_x), int(ball_y)
pygame.draw.circle(screen, yellow, ball_pos, radius, 0)
# 滑板不要?jiǎng)澇鲞吔?
pos_x = mouse_x
if pos_x 0:
pos_x = 0
elif pos_x > 700:
pos_x = 700
# 畫(huà)滑板并跟隨鼠標(biāo)左右移動(dòng)
pygame.draw.rect(screen, white, (pos_x, 580, 100, 20), 0)
print_text(font, 50, 0, "Score: " + str(score), red)
print_text(font, 650, 0, "Lives:" + str(lives), red)
pygame.display.update()
基本思路是,當(dāng)球落到屏幕最下邊,或者碰到了滑塊,則通過(guò)給球的y坐標(biāo)賦值,讓球重新回到最上邊去。
當(dāng)球的y坐標(biāo)大于滑塊的y坐標(biāo),即球下落到滑塊的高度,同時(shí)球的x坐標(biāo)又在滑塊的x坐標(biāo)范圍內(nèi),則視為碰撞,球依然回到頂上去。
游戲很簡(jiǎn)單,邏輯也很簡(jiǎn)單。
這是基本思路,以后用到sprite精靈類(lèi)的時(shí)候,才是常規(guī)的用法,也會(huì)有更加嚴(yán)禁的碰撞計(jì)算方法。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- python3 pygame實(shí)現(xiàn)接小球游戲
- 基于pygame實(shí)現(xiàn)童年掌機(jī)打磚塊游戲
- python實(shí)現(xiàn)打磚塊游戲
- Python實(shí)現(xiàn)打磚塊小游戲代碼實(shí)例