<Pygame:游戏开发> —— 撞墙会掉头的小乌龟

【python游戏开发入门】pygame下载与安装教程

Pygame 是一个利用SDL实现的模块。
SDL(Simple DirectMedia Layer)是一套开源代码的跨平台多媒体开发库,使用C语言写成。
Pygame功能:绘制图形、显示图像、动画效果、与键盘/鼠标和游戏手柄等外设交互、播放声音、碰撞检测。
SDL多用于开发游戏、模拟器、媒体播放器等多媒体应用领域。

# 终端(版本)查看
# 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("turtle.png")	# 加载当前路径下图像(本地) —— turtle:小乌龟
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

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

你可能感兴趣的:(pygame,pycharm,python)