Skip to content

Instantly share code, notes, and snippets.

@hoadh
Created October 12, 2021 14:21
Show Gist options
  • Save hoadh/8f9e5cd8742e3fc6d031d58a54e1f8c9 to your computer and use it in GitHub Desktop.
Save hoadh/8f9e5cd8742e3fc6d031d58a54e1f8c9 to your computer and use it in GitHub Desktop.
Phiên bản terminal game "Rắn săn mồi"
FIRST_ROW = 0
LAST_ROW = 11
FIRST_COLUMN = 0
LAST_COLUMN = 11
EMPTY_VALUE = 0
SNAKE_VALUE = 1
FOOD_VALUE = 2
game = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
]
snake = [
[5, 6],
[4, 6]
]
def show_game():
global game
for row in game:
for col in row:
print(f"{col:>2}", end=" ")
print()
def move_snake():
direction = input("Hướng di chuyển: ")
if direction == 'a':
turn_left()
elif direction == 'd':
turn_right()
elif direction == 'w':
turn_up()
elif direction == 's':
turn_down()
else:
exit()
update_snake_in_game()
show_game()
def turn_up():
global snake
head = snake[0]
del snake[len(snake)-1]
next_row = head[0] - 1
if next_row < FIRST_ROW:
next_row = LAST_ROW
new_position = [next_row, head[1]]
snake.insert(0, new_position)
def turn_down():
global snake
head = snake[0]
del snake[len(snake) - 1]
next_row = head[0] + 1
if next_row > LAST_ROW:
next_row = FIRST_ROW
new_position = [next_row, head[1]]
snake.insert(0, new_position)
def turn_left():
global snake
head = snake[0]
del snake[len(snake) - 1]
next_column = head[1] - 1
if next_column < FIRST_COLUMN:
next_column = LAST_COLUMN
new_position = [head[0], next_column]
snake.insert(0, new_position)
def turn_right():
global snake
head = snake[0]
del snake[len(snake) - 1]
next_column = head[1] + 1
if next_column > LAST_COLUMN:
next_column = FIRST_COLUMN
new_position = [head[0], next_column]
snake.insert(0, new_position)
def update_snake_in_game():
global game, snake
# reset snake in game
for i in range(len(game)):
for j in range(len(game[i])):
if game[i][j] == SNAKE_VALUE:
game[i][j] = EMPTY_VALUE
# update new positions of snake in game
for pos in snake:
game[pos[0]][pos[1]] = SNAKE_VALUE
update_snake_in_game()
show_game()
while True:
move_snake()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment