日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python pygame模块按键延迟_pygame模块中键控命令不能实现方块移动,求解

發(fā)布時(shí)間:2024/8/5 python 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python pygame模块按键延迟_pygame模块中键控命令不能实现方块移动,求解 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

# 導(dǎo)入pygame和sys模塊

import pygame,sys

# 初始化pygame、生成屏幕對(duì)象screen、顯示標(biāo)題字幕

pygame.init()

screen = pygame.display.set_mode((500,500))

pygame.display.set_caption('hello world')

# 在屏幕(0, 0)的位置上繪制一個(gè)(50*50)大小的矩形

# 獲取屏幕對(duì)象的矩形坐標(biāo)

# 然后把矩形移動(dòng)到屏幕指定的初始位置(屏幕正中央)

player = pygame.Rect(0, 0, 50, 50)

screen_rect = screen.get_rect()

player.centerx = screen_rect.centerx

player.centery = screen_rect.centery

# 設(shè)置上下左右移動(dòng)標(biāo)記,實(shí)現(xiàn)方塊在按鍵以后持續(xù)移動(dòng)

# 移動(dòng)速度為 0.1 [否則移動(dòng)太快無法看清楚方塊的移動(dòng)]

# 設(shè)置顏色值

moveLeft = False

moveRight = False

moveUp = False

moveDown = False

MOVESPEED = 0.1

BLACK=(0,0,0)

WHITE=(255,255,255)

# 因?yàn)閏enterx和centery不能存儲(chǔ)小數(shù),所以要設(shè)置中間變量

player_x = float(player.centerx)

player_y = float(player.centery)

# 進(jìn)入游戲大循環(huán)

while True:

# 偵聽事件,響應(yīng)退出操作

for event in pygame.event.get():

if event.type==pygame.QUIT:

pygame.quit()

sys.exit()

# 偵聽事件,響應(yīng)按鍵操作

# 如果按下 鍵,則修改移動(dòng)標(biāo)記為True實(shí)現(xiàn)持續(xù)移動(dòng)

elif event.type == pygame.KEYDOWN:

if event.key == pygame.K_LEFT:

moveLeft = True

elif event.key == pygame.K_RIGHT:

moveRight = True

elif event.key == pygame.K_UP:

moveUp = True

elif event.key==pygame.K_DOWN:

moveDown = True

# 偵聽事件,響應(yīng)松鍵操作

# 如果松開鍵,則修改移動(dòng)標(biāo)記為False停止移動(dòng)

elif event.type == pygame.KEYUP:

if event.key == pygame.K_LEFT:

moveLeft = False

elif event.key == pygame.K_RIGHT:

moveRight = False

elif event.key == pygame.K_UP:

moveUp = False

elif event.key == pygame.K_DOWN:

moveDown = False

# 如果移動(dòng)標(biāo)記為True并且方塊player沒有越過屏幕邊界,那么持續(xù)移動(dòng)

# 將中間變量的值存儲(chǔ)到centerx和centery中去

# 從而改變方塊的位置

if moveDown and player.bottom < screen_rect.bottom:

player_y += MOVESPEED

player.centery = player_y

if moveUp and player.top > screen_rect.top:

player_y -= MOVESPEED

player.centery = player_y

if moveLeft and player.left > screen_rect.left:

player_x -= MOVESPEED

player.centerx = player_x

if moveRight and player.right < screen_rect.right:

player_x += MOVESPEED

player.centerx = player_x

# 每次循環(huán)都用白色填充屏幕

# 么次循環(huán)重新繪制player方塊

# 每次循環(huán)都讓元素在屏幕上可見

screen.fill(WHITE)

pygame.draw.rect(screen, BLACK, player)

pygame.display.flip()

總結(jié)

以上是生活随笔為你收集整理的python pygame模块按键延迟_pygame模块中键控命令不能实现方块移动,求解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。