pygame中使用事件扫描实现对按键的检测以及小游戏的编写
生活随笔
收集整理的這篇文章主要介紹了
pygame中使用事件扫描实现对按键的检测以及小游戏的编写
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
確保你的python環境已經安裝了pygame的庫
import pygame, sys, random import pygame.locals as GAME_GLOBALS import pygame.event as GAME_EVENTSpygame.init()windowWidth = 800 windowHeigh = 800surface = pygame.display.set_mode((windowWidth, windowHeigh))pygame.display.set_caption('Pygame Keyboard')playerSize = 20 playerX = (windowWidth / 2) - (playerSize / 2) playerY = windowHeigh - playerSize playerVX = 1.0 playerVY = 0.0 jumpHeight = 25.0 moveSpeed = 1.0 maxSpeed = 10.0 gravity = 1.0leftDown = False rightdOWN = False haveJumped = Falsedef move():global playerX, playerY, playerVX, playerVY, haveJumped,gravityif leftDown:if playerVX > 0.0:playerVX = moveSpeedplayerVX = -playerVXif playerX > 0:playerX += playerVXif rightdOWN:if playerVX < 0.0:playerVX = moveSpeedif playerX + playerSize < windowWidth:playerX += playerVXif playerVY > 1.0:playerVY = playerVY * 0.9else:playerVY = 0.0haveJumped = Falseif playerY < windowHeigh - playerSize:playerY += gravitygravity = gravity * 1.1else:playerY = windowHeigh - playerSizegravity = 1.0playerY -= playerVYif(playerVX > 0.0 and playerVX < maxSpeed) or (playerVX < 0.0 and playerVX > -maxSpeed):if not haveJumped and (leftDown or rightdOWN):playerVX = playerVX * 1.1#how to quit our program def quitGame():pygame.quit()sys.exit()while True:surface.fill((0, 0, 0))pygame.draw.rect(surface, (255, 0, 0), (playerX, playerY, playerSize, playerSize))for event in GAME_EVENTS.get():if event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:leftDown = Trueif event.key == pygame.K_RIGHT:rightdOWN = Trueif event.key == pygame.K_UP:if not haveJumped:haveJumped = TrueplayerVY += jumpHeightif event.key == pygame.K_ESCAPE:quitGame()if event.type == pygame.KEYUP:if event.key == pygame.K_LEFT:leftDown = FalseplayerVX = moveSpeedif event.key == pygame.K_RIGHT:rightDowm = FalseplayerVX = moveSpeedif event.type == GAME_GLOBALS.QUIT:quitGame()move()pygame.display.update()函數說明
pygame.display.set_mode()函數;
初始化一個準備顯示的窗口或者屏幕。
pygame.display.set_caption(‘Pygame Keyboard’)設置窗口的標題
global playerX, playerY, playerVX, playerVY, haveJumped,gravity 由于python的變量是不用聲明直接可以使用的,所以在函數內部要是想使用全局變量并且想在函數內部更改全局變量的數值,必須進行全局變量的聲明之后才能夠使用,這樣 在函數的內部也能夠輕易的更改全局變量的數值。
def move():函數用于檢測按鍵的事件并對相應的按鍵做出相應的動作
def quitGame():pygame.quit()sys.exit()退出游戲的函數
總結
以上是生活随笔為你收集整理的pygame中使用事件扫描实现对按键的检测以及小游戏的编写的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 作者:贺田田(1985-),男,香港理工
- 下一篇: 作者:胡晓惠(1960-),男,中国科学