美文网首页Python第三方库学习
一张图看懂pygame编程 1

一张图看懂pygame编程 1

作者: FreakWill | 来源:发表于2019-12-16 20:48 被阅读0次

    Why pygame?

    最近开始学Python游戏编程,自然选择了pygame。pygame 可以写游戏,也可以做仿真。

    参考 pygame开发自己的游戏 系列文章

    一张图看懂pygame编程

    pygame程序里都是些什么?

    pygame.jpg

    源代码

    一个红色小方块垂直下落,如果和在底下的蓝色大方块碰撞在一起就终止,否则红色小方块重新下落一次。

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    import pygame, sys
    
    # 初始化
    pygame.init()
    SCREEN = pygame.display.set_mode((400, 300))
    pygame.display.set_caption('红蓝大碰撞')
    
    # 蓝色方块固定在最下方,左右移动,y值不变
    blue_rect = pygame.Rect(110, 250, 100, 50)
    red_rect = pygame.Rect(85, 0, 20, 50)
    
    
    goal = False
    while True: 
        for event in pygame.event.get():
            # 处理退出事件
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            # 键盘按下事件
            elif event.type == pygame.KEYDOWN:
                # 'a'键被按下
                if event.key == pygame.K_a:
                    blue_rect.x -= 5
                elif event.key == pygame.K_d:
                    blue_rect.x += 5
        red_rect.y += 5
        if red_rect.y > 300:
            red_rect.y = 0
        red_rect = pygame.Rect(85, red_rect.y, 20, 50)
        if blue_rect.colliderect(red_rect) or goal is True:
            goal = True
        else:
            SCREEN.fill((255, 255, 255))
            # 调用 pygame.display.update() 方法更新整个屏幕的显示
            pygame.draw.rect(SCREEN, (255, 0, 0), red_rect)
            pygame.draw.rect(SCREEN, (0,  0, 255), blue_rect)
            pygame.display.update()
            pygame.time.delay(50)
    

    相关文章

      网友评论

        本文标题:一张图看懂pygame编程 1

        本文链接:https://www.haomeiwen.com/subject/ilxjnctx.html