Zaktualizuj 'basic_grid.py'

Małe usprawnienia kodu: zoptymalizowana metoda Tractor.update, delikatnie zwiększony framerate w celu zapewnienia płynniejszego użytkowania, poprawione komentarze
This commit is contained in:
Cezary Adamczak 2021-03-15 08:48:34 +01:00
parent 0f0242165e
commit ec6dc2d5d3

View File

@ -56,35 +56,31 @@ class Tractor(pygame.sprite.Sprite):
if pressed_keys[K_UP]:
self.rect.move_ip(0, -(HEIGHT + MARGIN))
self.position[1] -= 1
if self.rect.top <= MARGIN:
self.rect.top = MARGIN
self.position[1] = 0
if pressed_keys[K_DOWN]:
self.rect.move_ip(0, HEIGHT + MARGIN)
self.position[1] += 1
self.position[1] += 1
if self.rect.bottom >= SCREEN_HEIGHT-MARGIN:
self.rect.bottom = SCREEN_HEIGHT-MARGIN
self.position[1] = GSIZE-1
if pressed_keys[K_LEFT]:
self.rect.move_ip(-(WIDTH + MARGIN), 0)
self.position[0] -= 1
self.position[0] -= 1
if self.rect.left < MARGIN:
self.rect.left = MARGIN
self.position[0] = 0
if pressed_keys[K_RIGHT]:
self.rect.move_ip(WIDTH + MARGIN, 0)
self.position[0] += 1
if self.rect.right > SCREEN_WIDTH-MARGIN:
self.rect.right = SCREEN_WIDTH-MARGIN
self.position[0] = GSIZE-1
if self.rect.left < MARGIN:
self.rect.left = MARGIN
if self.position[0] < 0:
self.position[0] = 0
if self.rect.right > SCREEN_WIDTH-MARGIN:
self.rect.right = SCREEN_WIDTH-MARGIN
if self.position[0] >= GSIZE-1:
self.position[0] = GSIZE-1
if self.rect.top <= MARGIN:
self.rect.top = MARGIN
if self.position[1] < 0:
self.position[1] = 0
if self.rect.bottom >= SCREEN_HEIGHT-MARGIN:
self.rect.bottom = SCREEN_HEIGHT-MARGIN
if self.position[1] >= GSIZE-1:
self.position[1] = GSIZE-1
def hydrate(self, field):
field[self.position[0]][self.position[1]].hydrate()
def hydrate(self, field, pressed_keys):
if pressed_keys[K_SPACE]:
field[self.position[0]][self.position[1]].hydrate()
# Define a Field object by extending pygame.sprite.Sprite
# The surface drawn on the screen is now an attribute of 'field'
@ -132,6 +128,7 @@ clock = pygame.time.Clock()
# Main loop
while running:
# Look at every event in the queue
for event in pygame.event.get():
# Did the user hit a key?
@ -144,13 +141,14 @@ while running:
elif event.type == QUIT:
running = False
# Get all keys pressed at a time
pressed_keys = pygame.key.get_pressed()
# Set the screen background
# Update the state of tractor
tractor.update(pressed_keys)
if pressed_keys[K_SPACE]:
tractor.hydrate(field)
tractor.hydrate(field, pressed_keys)
# Set the screen background
screen.fill(DBROWN)
# Draw the field
@ -164,5 +162,6 @@ while running:
# Update the screen
pygame.display.flip()
# Ensure program maintains a rate of 30 frames per second
clock.tick(10)
# Ensure program maintains a rate of 15 frames per second
clock.tick(15)