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

相关文章

关于pytorch中全连接神经网络搭建两种模式详解

pytorch搭建神经网络是很简单明了的,这里介绍两种自己常用的搭建模式: import torch import torch.nn as nn first: class NN...

python实现电子产品商店

python实现电子产品商店

利用python实现以下功能:基于python下的电子产品商店 电子产品商店 v0.1 请选择商品: ============================= 1  &nbs...

python同义词替换的实现(jieba分词)

python同义词替换的实现(jieba分词)

TihuanWords.txt文档格式注意:同一行的词用单个空格隔开,每行第一个词为同行词的替换词。年休假 年假 年休究竟 到底回家场景 我回来了代码import jieba...

Python实现的三层BP神经网络算法示例

Python实现的三层BP神经网络算法示例

本文实例讲述了Python实现的三层BP神经网络算法。分享给大家供大家参考,具体如下: 这是一个非常漂亮的三层反向传播神经网络的python实现,下一步我准备试着将其修改为多层BP神经网...

详解使用PyInstaller将Pygame库编写的小游戏程序打包为exe文件

详解使用PyInstaller将Pygame库编写的小游戏程序打包为exe文件

一、安装Pyinstaller 环境:python3.6、window10 注意事项: python64位版本打包的exe,只能在64位操作系统使用 打包文件夹和文件的名称不能用中文 p...