您当前的位置:首页 > IT编程 > python
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:pygame实现滑块接小球游戏

51自学网 2021-10-30 22:27:47
  python
这篇教程pygame实现滑块接小球游戏写得很实用,希望能帮到您。

用pygame做一个滑块接小球的游戏,供大家参考,具体内容如下

先上图

游戏很简单也很弱智,主要用到了pygame画圆,画方块,随机数等,可以锻炼基本的鼠标控制,游戏设计思维,简单地碰撞判断等,废话不多说,上代码

写之前,先思考能用到哪些参数

pygame.init()screen = pygame.display.set_mode((800, 600))# 生命和得分lives = 3score = 0# 设置颜色white = 255, 255, 255yellow = 255, 255, 0black = 0, 0, 0red = 220, 50, 50# 设置字体font = pygame.font.Font(None, 38)pygame.mouse.set_visible(False)game_over = True# 设置鼠标坐标及鼠标事件参数# 鼠标坐标mouse_x = mouse_y = 0# 滑板坐标pos_x = 300pos_y = 580# 球坐标ball_x = random.randint(0, 500)ball_y = -50# 球半径radius = 30# 下落速度vel = 0.5def 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)是让鼠标不可见

然后是游戏主体部分

# 主循环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坐标数值使球从顶部落下        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精灵类的时候,才是常规的用法,也会有更加严禁的碰撞计算方法。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持51zixue.net。


Python源码学习之PyType_Type和PyBaseObject_Type详解
Python中jieba库的使用方法
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。