日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

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

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

# 導入pygame和sys模塊

import pygame,sys

# 初始化pygame、生成屏幕對象screen、顯示標題字幕

pygame.init()

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

pygame.display.set_caption('hello world')

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

# 獲取屏幕對象的矩形坐標

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

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

screen_rect = screen.get_rect()

player.centerx = screen_rect.centerx

player.centery = screen_rect.centery

# 設置上下左右移動標記,實現方塊在按鍵以后持續移動

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

# 設置顏色值

moveLeft = False

moveRight = False

moveUp = False

moveDown = False

MOVESPEED = 0.1

BLACK=(0,0,0)

WHITE=(255,255,255)

# 因為centerx和centery不能存儲小數,所以要設置中間變量

player_x = float(player.centerx)

player_y = float(player.centery)

# 進入游戲大循環

while True:

# 偵聽事件,響應退出操作

for event in pygame.event.get():

if event.type==pygame.QUIT:

pygame.quit()

sys.exit()

# 偵聽事件,響應按鍵操作

# 如果按下 鍵,則修改移動標記為True實現持續移動

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

# 偵聽事件,響應松鍵操作

# 如果松開鍵,則修改移動標記為False停止移動

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

# 如果移動標記為True并且方塊player沒有越過屏幕邊界,那么持續移動

# 將中間變量的值存儲到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

# 每次循環都用白色填充屏幕

# 么次循環重新繪制player方塊

# 每次循環都讓元素在屏幕上可見

screen.fill(WHITE)

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

pygame.display.flip()

總結

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

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。