搜索
首页后端开发Python教程python基于pygame实现响应游戏中事件的方法(附源码)

本文实例讲述了python基于pygame实现响应游戏中事件的方法。分享给大家供大家参考,具体如下:

先看一下我做的demo效果:

当玩家按下键盘上的:上,下,左,右键的时候,后台会打印出玩家所按键的数字值,而图形会随之移动

这是客观上面存在的现象。

那么啥是事件呢?

你叫我做出定义,我不知道,我只能举个例子说明,例如接下来的代码中,列出来一些关于游戏中的事件

'''
  事件             产生途径              参数
  QUIT            用户按下关闭按钮          none
  ATIVEEVENT         Pygame被激活或者隐藏          gain, state
  KEYDOWN          键盘被按下              unicode, key, mod
  KEYUP           键盘被放开              key, mod
  MOUSEMOTION        鼠标移动              pos, rel, buttons
  MOUSEBUTTONDOWN      鼠标按下              pos, button
  MOUSEBUTTONUP       鼠标放开              pos, button
  JOYAXISMOTION       游戏手柄(Joystick or pad)移动      joy, axis, value
  JOYBALLMOTION       游戏球(Joy ball)?移动      joy, axis, value
  JOYHATMOTION        游戏手柄(Joystick)?移动      joy, axis, value
  JOYBUTTONDOWN       游戏手柄按下              joy, button
  JOYBUTTONUP        游戏手柄放开              joy, button
  VIDEORESIZE        Pygame窗口缩放          size, w, h
  VIDEOEXPOSE        Pygame窗口部分公开(expose)      none
  USEREVENT         触发了一个用户事件          code
'''

如鼠标按下事件,鼠标放开事件,键盘按下事件.....

这些事件的发生都伴随着一个动作的发生,正是因为有动作的发生,所以我们才可以扑捉到这些动作,从而做出相应的反应

如,我们按下键盘的左键,图片就向左移动一段距离...

代码部分如下:

#handle the key event
import pygame
from pygame.locals import *
from sys import exit
'''
  事件             产生途径              参数
  QUIT         用户按下关闭按钮          none
  ATIVEEVENT         Pygame被激活或者隐藏          gain, state
  KEYDOWN         键盘被按下              unicode, key, mod
  KEYUP         键盘被放开              key, mod
  MOUSEMOTION         鼠标移动              pos, rel, buttons
  MOUSEBUTTONDOWN     鼠标按下              pos, button
  MOUSEBUTTONUP     鼠标放开              pos, button
  JOYAXISMOTION     游戏手柄(Joystick or pad)移动      joy, axis, value
  JOYBALLMOTION     游戏球(Joy ball)?移动      joy, axis, value
  JOYHATMOTION     游戏手柄(Joystick)?移动      joy, axis, value
  JOYBUTTONDOWN     游戏手柄按下              joy, button
  JOYBUTTONUP         游戏手柄放开              joy, button
  VIDEORESIZE         Pygame窗口缩放          size, w, h
  VIDEOEXPOSE         Pygame窗口部分公开(expose)      none
  USEREVENT         触发了一个用户事件          code
'''
__author__ = {'name' : 'Hongten',
       'mail' : 'hongtenzone@foxmail.com',
       'QQ'  : '648719819',
       'Version' : '1.0'}
BG_IMAGE = 'C:\\py\\ball.png'
pygame.init()
screen = pygame.display.set_mode((500, 500), 0, 32)
bg = pygame.image.load(BG_IMAGE).convert()
x, y = 0, 0
move_x, move_y = 0, 0
while 1:
  for event in pygame.event.get():
    #print(event.type)
    if event.type == QUIT:
      exit()
    if event.type == KEYDOWN:
      print(event.key)
      #event.key返回的是一个数字值,而K_LEFT,K_UP,K_RIGHT,K_DOWN等都是常量,
      #他们代表的也是一个数字值,这些数字值可以用:print(event.key)获取到
      #如:K_LEFT = 276
      #  K_UP = 273
      #所以下面的代码可以替换为:
      #if event.key == 276:
      #  move_x = -10
      if event.key == K_LEFT:
        move_x = -10
      elif event.key == K_UP:
        move_y = -10
      elif event.key == K_RIGHT:
        move_x = 10
      elif event.key == K_DOWN:
        move_y = 10
    elif event.type == KEYUP:
      move_x = 0
      move_y = 0
    x += move_x
    y += move_y
    #print(x, y)
    screen.fill((0, 0, 0))
    screen.blit(bg, (x, y))
    pygame.display.update()

完整实例代码代码点击此处本站下载。

希望本文所述对大家Python程序设计有所帮助。

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python:深入研究汇编和解释Python:深入研究汇编和解释May 12, 2025 am 12:14 AM

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

Python是一种解释或编译语言,为什么重要?Python是一种解释或编译语言,为什么重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

对于python中的循环时循环与循环:解释了关键差异对于python中的循环时循环与循环:解释了关键差异May 12, 2025 am 12:08 AM

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

循环时:实用指南循环时:实用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

Python:它是真正的解释吗?揭穿神话Python:它是真正的解释吗?揭穿神话May 12, 2025 am 12:05 AM

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

与同一元素的Python串联列表与同一元素的Python串联列表May 11, 2025 am 12:08 AM

concateNateListsinpythonwithTheSamelements,使用:1)operatototakeepduplicates,2)asettoremavelemavphicates,or3)listCompreanspearensionforcontroloverduplicates,每个methodhasdhasdifferentperferentperferentperforentperforentperforentperfortenceandordormplications。

解释与编译语言:Python的位置解释与编译语言:Python的位置May 11, 2025 am 12:07 AM

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允许ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

循环时:您什么时候在Python中使用?循环时:您什么时候在Python中使用?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境