-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproject.py
More file actions
94 lines (77 loc) · 2.43 KB
/
project.py
File metadata and controls
94 lines (77 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import pygame, random
snake = [(20, 14), (20, 15), (20, 16)]
def main():
initialize_game()
def initialize_game():
global direction
direction = 'up'
global food_position
food_position = generate_new_food_position()
pygame.init()
window = pygame.display.set_mode((800, 600))
# Main game loop
global running
running = True
clock = pygame.time.Clock()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
direction = 'up'
elif event.key == pygame.K_DOWN:
direction = 'down'
elif event.key == pygame.K_LEFT:
direction = 'left'
elif event.key == pygame.K_RIGHT:
direction = 'right'
update_game()
draw_game(window)
pygame.display.flip()
clock.tick(30)
pygame.quit()
def calculate_new_head_position():
global direction
x, y = snake[0] # get the current head position
if direction == 'up':
y -= 1
elif direction == 'down':
y += 1
elif direction == 'left':
x -= 1
elif direction == 'right':
x += 1
return (x, y)
def update_game():
global food_position
global running
x, y = calculate_new_head_position()
# Check if the new head position is outside the screen
if x < 0 or x >= 40 or y < 0 or y >= 30:
running = False # or wrap around to the other side
else:
new_head_position = (x, y)
if new_head_position in snake:
running = False
else:
snake.insert(0, new_head_position)
if new_head_position == food_position:
food_position = generate_new_food_position()
else:
snake.pop()
def draw_game(window):
window.fill((255, 255, 255))
for segment in snake:
pygame.draw.rect(window, (0, 255, 0), pygame.Rect(segment[0]*20, segment[1]*20, 20, 20))
#draw food
pygame.draw.rect(window, (255, 0, 0), pygame.Rect(food_position[0]*20, food_position[1]*20, 20, 20))
pygame.display.update()
def generate_new_food_position():
while True:
x = random.randrange(0, 40)
y = random.randrange(0, 30)
if (x, y) not in snake:
return (x, y)
if __name__ == "__main__":
main()