python方向键控制上下左右代码

yipeiwu_com6年前Python基础

本文所示代码实现python编程方向键控制图片上下左右,我们首先看下演示结果。

演示:

实例代码:

bif="1.jpg" 
mif="2.jpg" 
import pygame,sys 
from pygame.locals import * 
 
pygame.init() 
 
screen=pygame.display.set_mode((640,360),0,32) 
background=pygame.image.load(bif).convert() 
mouse_c=pygame.image.load(mif).convert_alpha() 
 
x,y=0,0 
movex,movey=0,0 
 
while True: 
  for event in pygame.event.get(): 
    if event.type ==QUIT: 
      pygame.quit() 
      sys.exit() 
    if event.type==KEYDOWN: 
      if event.key==K_LEFT: 
        movex=-1 
      if event.key==K_RIGHT: 
        movex=+1 
      elif event.key==K_UP: 
        movey=-1 
      elif event.key==K_DOWN: 
        movey=+1 
    if event.type==KEYUP: 
      if event.key==K_LEFT: 
        movex=0 
      if event.key==K_RIGHT: 
        movex=0 
      elif event.key==K_UP: 
        movey=0 
      elif event.key==K_DOWN: 
        movey=0 
 
  x+=movex 
  y+=movey 
   
  screen.blit(background,(0,0)) 
  screen.blit(mouse_c,(x,y)) 
   
  pygame.display.update() 

总结

我觉得游戏编程最基础的功能就是鼠标键盘控制物品移动,还有就是物体的碰撞检测。

以上就是本文关于python方向键控制上下左右代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

Linux中安装Python的交互式解释器IPython的教程

IPython是Python的交互式Shell,提供了代码自动补完,自动缩进,高亮显示,执行Shell命令等非常有用的特性。特别是它的代码补完功能,例如:在输入zlib.之后按下Tab键...

Spring Cloud Feign高级应用实例详解

这篇文章主要介绍了Spring Cloud Feign高级应用实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.使用feig...

python3.8与pyinstaller冲突问题的快速解决方法

python3.8与pyinstaller冲突问题的快速解决方法

安装pyinstaller 安装的时候 进入cmd pip install pyinstaller 发现安装报错! 解决办法: # 自主下载pyinstaller包,进行手动安装...

python实现猜数字游戏(无重复数字)示例分享

复制代码 代码如下:import time, random class GuessNum:    def __init__(self): &nbs...

使用Python的Django框架结合jQuery实现AJAX购物车页面

使用Python的Django框架结合jQuery实现AJAX购物车页面

Django中集成jquery 首先,静态的资源通常放入static文件夹中: static/ css/ djquery.css samples/...