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

yipeiwu_com7年前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方向键控制上下左右代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

Python求两个圆的交点坐标或三个圆的交点坐标方法

计算两个圆的交点 代码如下: # -*- coding: utf-8 -*- import math import numpy as np def insec(p1,r1,p2,r2...

Python数据结构与算法之使用队列解决小猫钓鱼问题

Python数据结构与算法之使用队列解决小猫钓鱼问题

本文实例讲述了Python数据结构与算法之使用队列解决小猫钓鱼问题。分享给大家供大家参考,具体如下: 按照《啊哈》里的思路实现这道题目,但是和结果不一样,我自己用一幅牌试了一下,发现是我...

Python验证码识别处理实例

Python验证码识别处理实例

一、准备工作与代码实例 (1)安装PIL:下载后是一个exe,直接双击安装,它会自动安装到C:\Python27\Lib\site-packages中去, (2)pytesser:下载解...

python删除特定文件的方法

本文实例讲述了python删除特定文件的方法。分享给大家供大家参考。具体如下: #!/usr/bin/python # -*- coding: utf-8 -*- import os...

浅谈Python中的bs4基础

安装 在命令提示符框中直接输入pip install beautifulsoup4 介绍 beautifulsoup是python的一个第三方库,和xpath一样,都是用来解析html数...