如何使player_1随键移动?

时间:2019-06-27 17:13:08

标签: python pygame pong

我想用Python制作Pong游戏。我已经有了窗户和播放器型号。

我试图用

if keys[pygame.K_LEFT]:
    x -= speed
if keys[pygame.K_LEFT]:
    x += speed

这是我的整个代码:

import pygame
from pygame import *
import math
import random
clock = pygame.time.Clock()  # fps

pygame.init()  # start
title = pygame.display.set_caption("Pong")
width = 640
height = 480
screen = pygame.display.set_mode((width, height))   # screen
running = True
speed = 10
white = (255, 255, 255)
x = 120
y = 5
player_1 = pygame.draw.rect(screen, white, (240, 430, x, y))
player_2 = pygame.draw.rect(screen, white, (240, 40, x, y))
pong = pygame.draw.circle(screen, white, (300, 235), 4)
pygame.display.update()
fps = clock.tick(60)
keys = pygame.key.get_pressed()

if keys[pygame.K_LEFT]:
    x -= speed
if keys[pygame.K_LEFT]:
    x += speed


while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            running = False


我想让下位玩家用箭头键移动,但是什么也没发生。

1 个答案:

答案 0 :(得分:0)

放入


keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
    x -= speed
if keys[pygame.K_LEFT]:
    x += speed

player_1 = pygame.draw.rect(screen, white, (240, 430, x, y))
player_2 = pygame.draw.rect(screen, white, (240, 40, x, y))
pong = pygame.draw.circle(screen, white, (300, 235), 4)
pygame.display.update()
fps = clock.tick(60)


在while循环中。

还可以更改

if keys[pygame.K_LEFT]:
    x += speed

if keys[pygame.K_RIGHT]:
    x += speed