pygame 小记

前言

部分因为兴趣,部分因为找工作。 最近接触了一些python的知识。 通读了《笨方法学python》,对python的基础有了些了解。 但自己感觉还是没有找到一套学习新语言的最佳实践。但又试问,比完美还完美的是何种状态呢。 更适合,满足当前需求或者是蛮不错的一种状态。 接下来的文章更多的偏向于技术每日归纳总结。。

今天的收获

pygame 是因为turtle才接触的。 今天的学习集中于界面的事件响应。

  1. 鼠标的事件响应。 集中于鼠标事件的几个函数。
  • 鼠标得到位置:
x,y = pygame.mouse.get_pos()

x,y 表示的横纵坐标。同时注意turtle 和 pygame的坐标系不一样。

隐藏鼠标箭头
pygame.mouse.set_visible(False)

在编程中,感觉函数的名称比较人性化,较之自己之前所接触的一些编程语言,更加易用。

  1. 键盘的事件响应
    python 中没有switch语法。 可以使用字典来替代相近的功能。 例如,对于键盘上的上下左右,按键的识别,捕获事件后,通过多个if-elif 语句可以实现,但略嫌麻烦,可以通过如下代码进行精简:
offset = {pygame.K_LEFT:0, pygame.K_RIGHT:0, pygame.K_UP:0, pygame.K_DOWN:0}
for i in pygame.event.get():       
 	if i.type == pygame.QUIT:            
 		sys.exit()        
 	elif i.type == pygame.KEYDOWN:            
 		if i.key in offset:                
 			offset[i.key] = 3      

代码展示

图片可以选择800*600 的进行尝试。

# 加载图片并且实现缩放
import pygame,sys
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
GREEN = (0,255,0)
offset = {pygame.K_LEFT:0, pygame.K_RIGHT:0, pygame.K_UP:0, pygame.K_DOWN:0}
pygame.init()
screen = pygame.display.set_mode([SCREEN_WIDTH,SCREEN_HEIGHT])pygame.display.set_caption("wow")
background = pygame.image.load('space.png').convert_alpha()
shoot_img = pygame.image.load('freelance.png').convert_alpha()
width, height = shoot_img.get_size()
shoot_img = pygame.transform.smoothscale(shoot_img,(width//2,height//2))
shoot_pos = [100,100]
while True:    
	screen.blit(background,(0,0))        
	for i in pygame.event.get():       
		if i.type == pygame.QUIT:            
			sys.exit()        
		elif i.type == pygame.KEYDOWN:            
			if i.key in offset:                
				offset[i.key] = 3        
		elif i.type == pygame.KEYUP:           
			if i.key in offset:               
				 offset[i.key] = 0    
	offset_x = offset[pygame.K_RIGHT] - offset[pygame.K_LEFT]    
	offset_y = offset[pygame.K_DOWN] - offset[pygame.K_UP]        
	# x,y = pygame.mouse.get_pos()    
	# pygame.mouse.set_visible(False)    
	# x -= shoot_img.get_width() /2     
	# y -= shoot_img.get_height() /2    
	shoot_pos[0] += offset_x    
	shoot_pos[1] += offset_y     
	if shoot_pos[0] <= 0:       
		shoot_pos[0] = 0    
	elif shoot_pos[0] > SCREEN_WIDTH - shoot_img.get_width():        
		shoot_pos[0] = SCREEN_WIDTH - shoot_img.get_width()    
	if shoot_pos[1] <= 0:        
		shoot_pos[1] = 0    
	elif shoot_pos[1] > SCREEN_HEIGHT - shoot_img.get_height():        
		shoot_pos[1] = SCREEN_HEIGHT - shoot_img.get_height()
	screen.blit(shoot_img,(shoot_pos[0], shoot_pos[1]))    
	pygame.display.update()
pygame.quit()        

借鉴了几位csdn博客的文章。 若文中有不当之处,恳请指教。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值