generated from mwc/project_game
In this submit, i wokred on making the game more to how i want it.
I was able to get it to move and start from the center. My next goal is to move around and pick up "food" for my snake.
This commit is contained in:
48
player.py
48
player.py
@@ -4,25 +4,39 @@ class Player:
|
||||
|
||||
def __init__(self, board_size):
|
||||
board_width, board_height = board_size
|
||||
self.position = (board_width // 2, board_height - 1)
|
||||
|
||||
start_x = board_width // 2
|
||||
start_y = board_height // 2
|
||||
|
||||
self.position = (start_x, start_y)
|
||||
self.body = [self.position]
|
||||
self.direction = (1, 0)
|
||||
|
||||
def handle_keystroke(self, keystroke, game):
|
||||
x, y = self.position
|
||||
x, y = self.body[0]
|
||||
|
||||
if keystroke.name in ("KEY_LEFT", "KEY_RIGHT", "KEY_UP", "KEY_DOWN"):
|
||||
if keystroke.name == "KEY_LEFT":
|
||||
new_position = (x - 1, y)
|
||||
|
||||
elif keystroke.name == "KEY_RIGHT":
|
||||
new_position = (x +1, y)
|
||||
if keystroke.name == "KEY_LEFT":
|
||||
self.direction = (-1, 0)
|
||||
elif keystroke.name == "KEY_RIGHT":
|
||||
self.direction = (1, 0)
|
||||
elif keystroke.name == "KEY_UP":
|
||||
self.direction = (0, -1)
|
||||
elif keystroke.name == "KEY_DOWN":
|
||||
self.direction = (0, 1)
|
||||
|
||||
elif keystroke.name == "KEY_UP":
|
||||
new_position = (x, y-1)
|
||||
|
||||
elif keystroke.name == "KEY_DOWN":
|
||||
new_position = (x, y+1)
|
||||
dx, dy = self.direction
|
||||
new_head = (x + dx, y + dy)
|
||||
|
||||
if game.on_board(new_position):
|
||||
if game.is_empty(new_position):
|
||||
self.position = new_position
|
||||
else:
|
||||
game.end()
|
||||
if not game.on_board(new_head):
|
||||
game.end()
|
||||
return
|
||||
|
||||
if new_head in self.body:
|
||||
game.end()
|
||||
return
|
||||
|
||||
self.body.insert(0, new_head)
|
||||
self.body.pop()
|
||||
|
||||
self.position = self.body[0]
|
||||
|
||||
Reference in New Issue
Block a user