Python实现小球游戏

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011732358/article/details/86439305

       用python实现小球的游戏,小球不断运动,用挡板接住小球使小球一直运动即可得分,参照着输上的介绍写的,很简易的游戏,只需要导入sys 和 pygame模块。
效果图如下所示:
在这里插入图片描述

# -*- coding: utf-8 -*-: 
import pygame
import sys
# pygame初始化
pygame.init()
# 构建屏幕,分辨率为640x480
screen = pygame.display.set_mode((640, 480))

# 小球 从文件加载图像,并保存在“ball”对象中
ball = pygame.image.load("ball.bmp")
# 挡板 从文件中加载图像,并保存在“bat”对象中
bat = pygame.image.load("bat.bmp")
# 小球位置及速度初始化
ball_x = 100
ball_y = 100
ball_x_speed = 7
ball_y_speed = 7
# 挡板位置初始化
bat_x = 260
bat_y = 430
# 分数初始化
score = 0
# 定义新的字体
font = pygame.font.Font(None, 36)
while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit(1)
    # 计分
    score += 1
    # 小球动起来
    ball_x += ball_x_speed
    ball_y += ball_y_speed
    # 判断是否按照左右键滑动挡板
    pressed = pygame.key.get_pressed()
    # 移动挡板
    if pressed[pygame.K_LEFT] and bat_x > 0:
        bat_x -= 15
    if pressed[pygame.K_RIGHT] and bat_x < 512:
        bat_x += 15
    # 边界检测
    if ball_x > bat_x and ball_x < bat_x + 112 and ball_y > 400:
        ball_y_speed = -7
    if ball_x > 610: ball_x_speed = -7
    if ball_x < 0: ball_x_speed = 7
    if ball_y > 450: break
    if ball_y < 0: ball_y_speed = 7
    # 用RGB颜色元组填充屏幕
    screen.fill((90, 230, 90))
    # 画小球
    screen.blit(ball, (ball_x, ball_y))
    # 画挡板
    screen.blit(bat, (bat_x, bat_y))
    # 显示分数
    score_text = font.render("Score: " + str(score), 1, (10, 10, 10))
    screen.blit(score_text, (10, 10))
    # 刷新屏幕
    pygame.display.flip()
    # 延时
    pygame.time.wait(20)

猜你喜欢

转载自blog.csdn.net/u011732358/article/details/86439305