<Pygame: Game Development> —— A little turtle that hits a wall and turns around

[Introduction to python game development] pygame download and installation tutorial

  • Pygame is a module implemented using SDL.
  • SDL (Simple DirectMedia Layer) is a set of open source code cross-platform multimedia development library written in C language. It is mostly used in the development of multimedia applications such as games, emulators, and media players.
  • Pygame functions: draw graphics, display images, animation effects, interact with peripherals such as keyboard/mouse and gamepad, play sounds, and detect collisions.

insert image description here

# 终端(版本)查看
# python			# python版本查看
# import pygame		# pygame版本查看
# exit()			# 退出并返回路径
####################
import pygame 
# print(pygame.ver)		# 查看pygame版本号
import sys

# 界面初始化设置
pygame.init()  # 初始化pygame
size = width, height = 600, 400  # 制定游戏窗口大小
speed = [-8, 4]  # 每调用一次position.move(), [-2, 1]就相当于水平位置移动-2, 垂直位置移动+1;
bg = (255, 255, 255)  # 背景颜色(0 ~ 255 : 黑 ~ 白)
screen = pygame.display.set_mode(size)  # 创建(指定大小)窗口, 默认(0, 0)
pygame.display.set_caption("初次见面,请大家多多关照!")  # 设置窗口标题
turtle = pygame.image.load("resized_image.jpg")  # 加载当前路径下图像(本地) —— turtle:小乌龟
turtle = pygame.transform.scale(turtle, (width // 4, height // 4))  # 缩放图像
position = turtle.get_rect()  # 获得图像的矩形位置

while True:
    # 迭代获取每个事件消息
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()  # 退出程序
        position = position.move(speed)  # 移动图像

        # 判断移动后的矩形区域是否位于窗口的边界之处(出界)
        if position.left < 0 or position.right > width:
            # 小乌龟每次"撞墙"之后都会"掉头"
            # transform.flip(turtle, True, False): 		# 第二个参数表示水平翻转,第三个参数表示垂直翻转;
            turtle = pygame.transform.flip(turtle, True, False)  # 翻转图像
            speed[0] = -speed[0]  # 反方向移动
        if position.top < 0 or position.bottom > height:
            turtle = pygame.transform.flip(turtle, True, True)  # 翻转图像
            speed[1] = -speed[1]

        # 位置移动后调用screen.fill()将整个背景画布刷白;
        screen.fill(bg)  # 填充背景颜色
        # Surface对象 —— 就是指图像
        # Surface对象的blit():将Surface对象绘制到另一个图像上(指定位置)
        screen.blit(turtle, position)  # 更新图像

        # 由于pygame采用的是双缓冲模式,因此需要调用display.flip()方法将缓冲好的画面一次性刷新到显示器上。
        pygame.display.flip()  # 更新界面
        pygame.time.delay(1)  # 延迟10ms

# 备注:鼠标需要在游戏窗口内一直移动,小乌龟才会保持移动;
		

Guess you like

Origin blog.csdn.net/shinuone/article/details/126221188#comments_28056721