mirror of
https://github.com/kristoferssolo/2048.git
synced 2025-10-21 15:20:35 +00:00
feat(game): add block movement
Allowed movemt keys are WASD, Arrow keys and vim motion keys
This commit is contained in:
parent
72b31e90c0
commit
d2d2a07822
@ -21,3 +21,7 @@ class Block(pygame.sprite.Sprite):
|
||||
text = font.render(str(self.value), True, COLORS.FG)
|
||||
text_rect = text.get_rect(center=self.image.get_rect().center)
|
||||
self.image.blit(text, text_rect)
|
||||
|
||||
def move(self, dx: int, dy: int) -> None:
|
||||
self.rect.x += dx
|
||||
self.rect.y += dy
|
||||
|
||||
@ -14,7 +14,7 @@ class Game:
|
||||
self.screen = pygame.display.set_mode((Config.WIDTH, Config.HEIGHT))
|
||||
pygame.display.set_caption("2048")
|
||||
self.sprites = pygame.sprite.Group()
|
||||
self.generate_random_block()
|
||||
self.generate_random_block(Config.INITIAL_BLOCK_COUNT)
|
||||
|
||||
def run(self) -> None:
|
||||
while True:
|
||||
@ -33,18 +33,36 @@ class Game:
|
||||
def hande_events(self) -> None:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
pygame.quit()
|
||||
sys.exit()
|
||||
self.exit()
|
||||
elif event.type == pygame.KEYDOWN:
|
||||
if event.key in (pygame.K_LEFT, pygame.K_a, pygame.K_h):
|
||||
self.move_blocks(-Config.BLOCK_SIZE, 0)
|
||||
elif event.key in (pygame.K_RIGHT, pygame.K_d, pygame.K_l):
|
||||
self.move_blocks(Config.BLOCK_SIZE, 0)
|
||||
elif event.key in (pygame.K_UP, pygame.K_w, pygame.K_k):
|
||||
self.move_blocks(0, -Config.BLOCK_SIZE)
|
||||
elif event.key in (pygame.K_DOWN, pygame.K_s, pygame.K_j):
|
||||
self.move_blocks(0, Config.BLOCK_SIZE)
|
||||
elif event.key == pygame.K_q:
|
||||
self.exit()
|
||||
|
||||
def generate_random_block(self) -> None:
|
||||
for _ in range(Config.INITIAL_BLOCK_COUNT):
|
||||
def move_blocks(self, dx, dy) -> None:
|
||||
for block in self.sprites:
|
||||
block.move(dx, dy)
|
||||
|
||||
def generate_random_block(self, count: int) -> None:
|
||||
for _ in range(count):
|
||||
while True:
|
||||
x = random.randint(0, 2) * Config.BLOCK_SIZE # random column position
|
||||
y = random.randint(0, 2) * Config.BLOCK_SIZE # random row position
|
||||
|
||||
block = Block(x, y)
|
||||
colligin_blocks = pygame.sprite.spritecollide(block, self.sprites, False)
|
||||
|
||||
colligin_blocks = pygame.sprite.spritecollide(block, self.sprites, False) # check collision
|
||||
|
||||
if not colligin_blocks:
|
||||
self.sprites.add(block)
|
||||
break
|
||||
|
||||
def exit(self) -> None:
|
||||
pygame.quit()
|
||||
sys.exit()
|
||||
|
||||
Loading…
Reference in New Issue
Block a user