程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python中利用pygame做彈球游戲

編輯:Python

Windows的開發環境

 1.Python3.8

 2.pygame-2.0.1-cp38-cp38-win_amd64.whl  Pygame的安裝方法

 

學習Python時,看到了朱紅慶的【Python核心編程從入門到開發實戰】,

驚訝的是13章的彈球游戲的代碼居然是不完整的,按書上的是不能正常運行的。

下面的代碼簡單的調通了,希望後學者節省點時間。

import sys,random,time
import pygame
import pygame as game
#背景(任意圖片,和該程序同目錄)
background_image_filename = 'snow1.jpg'
#球
ball_color = (255,0,0)
paddle_color = (255,140,0)
ball_x = random.randint(10,590)
ball_y = 10
speed_x = 1
speed_y = 1
count = 0
score = 0
#計分牌
def drawText(content):
pygame.font.init()
#字體大小(任意字體,和該程序同目錄)
font = pygame.font.Font("sans.ttf",28)
text = font.render(content,True,(255,0,0),(255,255,255))
return text
#球運行的方向
ball_left = False
ball_up =False
#
game.init()
game.display.init()
game_window = game.display.set_mode((600,500))
game.display.set_caption('彈彈球')
while True:
background = game.image.load(background_image_filename).convert()
mouse_x,mouse_y = game.mouse.get_pos()
#球
game.draw.circle(game_window,ball_color,(ball_x,ball_y),10)
#球拍
game.draw.rect(game_window,paddle_color,(mouse_x,470,100,10))
#球運行的方向
if ball_left == True:
ball_x -=1
if ball_left == False:
ball_x += 1
if ball_up == True:
ball_y -=1
if ball_up == False:
ball_y += 1
#
for event in game.event.get():
if event.type == game.QUIT:
game.quit()
sys.exit()
game.display.update()
game_window.blit(background,(0,0))#背景
#計分器
game_window.blit(drawText(str(score)),(260,40))#
ball_x += speed_x
ball_y += speed_y
#反方向運動
if (ball_x <= 10):
speed_x = -speed_x
ball_left = False
if (ball_x >= 580):
speed_x = -speed_x
ball_left = True
if ball_y <= 10:
speed_y = -speed_y
ball_up = False
if (ball_y >= 480):
speed_y = -speed_y
ball_up = True
#判斷球拍接住彈球
if ((mouse_x - 10 < ball_x < mouse_x +110) and (ball_y >= 460)):
speed_y = -speed_y
ball_up = True
print("ball_y ",ball_y)
score += 1 #成功接住球後次數+1
count +=1
#
if count ==3 :
count =0
if speed_x >0 :
speed_x += 1
speed_y -=1
if ball_y >= 470 :
print("ball_y ",ball_y)
game_window.blit(drawText("Game Over " +str(score)),(220,40))#
game.display.update()
break

 

 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved