1.Python3.8
2.pygame-2.0.1-cp38-cp38-win_amd64.whl Pygame Method of installation
Study Python when , I saw Zhu Hongqing's 【Python Core programming from entry to development practice 】,
To my surprise 13 The code of Zhang's pinball game is actually incomplete , According to the book, it doesn't work properly .
The following code is simply adjusted , I hope later scholars can save some time .
import sys,random,time
import pygame
import pygame as game
# background ( Any picture , The same directory as this program )
background_image_filename = 'snow1.jpg'
# The ball
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
# Scoreboard
def drawText(content):
pygame.font.init()
# font size ( Any font , The same directory as this program )
font = pygame.font.Font("sans.ttf",28)
text = font.render(content,True,(255,0,0),(255,255,255))
return text
# The direction of the ball
ball_left = False
ball_up =False
#
game.init()
game.display.init()
game_window = game.display.set_mode((600,500))
game.display.set_caption(' Play Pinball ')
while True:
background = game.image.load(background_image_filename).convert()
mouse_x,mouse_y = game.mouse.get_pos()
# The ball
game.draw.circle(game_window,ball_color,(ball_x,ball_y),10)
# Racket
game.draw.rect(game_window,paddle_color,(mouse_x,470,100,10))
# The direction of the ball
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))# background
# score indicator
game_window.blit(drawText(str(score)),(260,40))#
ball_x += speed_x
ball_y += speed_y
# Move in the opposite direction
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
# Judge whether the racket catches the pinball
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 # The number of times after successfully catching the ball +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