用pygame做一個滑塊接小球的游戲,供大家參考,具體內容如下
先上圖
游戲很簡單也很弱智,主要用到了pygame畫圓,畫方塊,隨機數(shù)等,可以鍛煉基本的鼠標控制,游戲設計思維,簡單地碰撞判斷等,廢話不多說,上代碼
寫之前,先思考能用到哪些參數(shù)
pygame.init() screen = pygame.display.set_mode((800, 600)) # 生命和得分 lives = 3 score = 0 # 設置顏色 white = 255, 255, 255 yellow = 255, 255, 0 black = 0, 0, 0 red = 220, 50, 50 # 設置字體 font = pygame.font.Font(None, 38) pygame.mouse.set_visible(False) game_over = True # 設置鼠標坐標及鼠標事件參數(shù) # 鼠標坐標 mouse_x = mouse_y = 0 # 滑板坐標 pos_x = 300 pos_y = 580 # 球坐標 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一開始設置為True 是因為開局先停止,等鼠標點擊后再開始,這也用到當死了以后,從新開始游戲
pygame.mouse.set_visible(False)是讓鼠標不可見
然后是游戲主體部分
# 主循環(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) # 既沒有落地上也沒被接住的時候,則不斷增加y坐標數(shù)值使球從頂部落下 else: ball_y += vel ball_pos = int(ball_x), int(ball_y) pygame.draw.circle(screen, yellow, ball_pos, radius, 0) # 滑板不要劃出邊界 pos_x = mouse_x if pos_x 0: pos_x = 0 elif pos_x > 700: pos_x = 700 # 畫滑板并跟隨鼠標左右移動 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()
基本思路是,當球落到屏幕最下邊,或者碰到了滑塊,則通過給球的y坐標賦值,讓球重新回到最上邊去。
當球的y坐標大于滑塊的y坐標,即球下落到滑塊的高度,同時球的x坐標又在滑塊的x坐標范圍內,則視為碰撞,球依然回到頂上去。
游戲很簡單,邏輯也很簡單。
這是基本思路,以后用到sprite精靈類的時候,才是常規(guī)的用法,也會有更加嚴禁的碰撞計算方法。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。