我在Pygame制作游戏。现在我只有一个矩形在屏幕上移动。可以从键盘更改矩形的方向。
main.py:
import pygame
import sys
import player
import room
# Colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
blue = (0, 255, 0)
green = (0, 0, 255)
# Global variables
S_WIDTH = 800
S_HEIGHT = 800
FPS = 60
# player speed
SPEED = 2
# Initialization
pygame.init()
screen = pygame.display.set_mode([S_WIDTH, S_HEIGHT])
pygame.display.set_caption("Py-Man Alpha")
clock = pygame.time.Clock()
# Game class
class Game(object):
"""
This is main class of game.
All game events will happen here.
"""
Player = player.Player(blue, 50, 50, 0, 0)
def __init__(self, screen, running):
self.screen = screen
self.running = running
self.run()
def run(self):
while self.running:
# Events
for event in pygame.event.get():
# If user hits 'x'
if event.type == pygame.QUIT:
self.running = False
# Keyborad events
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.Player.direction = 'up'
self.Player.move(SPEED, WALLS)
elif event.key == pygame.K_DOWN:
self.Player.direction = 'down'
self.Player.move(SPEED, WALLS)
elif event.key == pygame.K_LEFT:
self.Player.direction = 'left'
self.Player.move(SPEED, WALLS)
elif event.key == pygame.K_RIGHT:
self.Player.direction = 'right'
self.Player.move(SPEED, WALLS)
elif event.key == pygame.K_p:
self.Player.direction = 'pause'
# Clear screen
self.screen.fill(white)
#Draw
self.Player.move(SPEED, WALLS)
self.Player.draw(self.screen)
for wall in WALLS:
wall.draw()
# Set clock
clock.tick(60)
# Update screen
pygame.display.flip()
# End of game
pygame.quit()
sys.exit()
# Tests
game = Game(screen, True)
player.py:
#imports
import pygame
class Player(pygame.sprite.Sprite):
"""
This class represent the player image
and has the player actions.
"""
direction = 'right'
def __init__(self, color, width, height, x, y):
# Pygame constructor
pygame.sprite.Sprite.__init__(self)
# Init. variables
self.color = color
self.width = width
self.height = height
# Create sprite
self.image = pygame.Surface([width, height])
self.image.fill(self.color)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def draw(self, screen):
# Draw player on the screen
pygame.draw.rect(screen, self.color, [self.rect.x, self.rect.y, self.width, self.height], 0)
def move(self, speed, walls):
# Move the player
if self.direction == 'up':
self.rect.y -= speed
elif self.direction == 'down':
self.rect.y += speed
elif self.direction == 'left':
self.rect.x -= speed
elif self.direction == 'right':
self.rect.x += speed
那么,我如何才能加快游戏速度?我怎样才能提高速度?哪里错了? 谢谢!
编辑: 监视器的刷新很慢。我按“向上”键,但在2-3秒后监控取指令。为什么呢?
答案 0 :(得分:0)
您可以增加SPEED
或clock.tick(60)
但我更愿意增加SPEED
。
clock.tick(60)
表示60 FPS
,您可以增加它,但许多监视器会使用60Hz
刷新其屏幕,这意味着60 FPS
。更大的FPS意味着更多的CPU工作,所以它更热,你可以听到CPU风扇:)