Select your cookie preferences

We use essential cookies and similar tools that are necessary to provide our site and services. We use performance cookies to collect anonymous statistics, so we can understand how customers use our site and make improvements. Essential cookies cannot be deactivated, but you can choose “Customize” or “Decline” to decline performance cookies.

If you agree, AWS and approved third parties will also use cookies to provide useful site features, remember your preferences, and display relevant content, including relevant advertising. To accept or decline all non-essential cookies, choose “Accept” or “Decline.” To make more detailed choices, choose “Customize.”

AWS Logo
Menu
From Concept to Playable in Seconds: Creating the Greedy Snake Game with Amazon Q Developer

From Concept to Playable in Seconds: Creating the Greedy Snake Game with Amazon Q Developer

Demonstrating AI's potential for rapid prototyping, this post details using Amazon Q Developer to generate a Greedy Snake game from prompts, including the AI's thought process, final Python code leveraging Pygame, and iterative improvements.

Haowen Huang
Amazon Employee
Published Sep 30, 2024
Last Modified Nov 2, 2024
In my previous blog post, I demonstrated how to create a prototype of the classic Greedy Snake game using Amazon Bedrock and natural language prompts. If that inspired you to develop games with AWS services, I have good news for you: AWS is currently running an AWS Game Builder Challenge, which is a hackathon for developers. I'll provide the detailed event URL at the end of the article.
After the post was published, many developers were intrigued by this demo and curious to know if Amazon Q Developer could generate the entire Greedy Snake game prototype. That is what we will discuss in this post.
The Greedy Snake is a timeless arcade game that has captivated gamers for decades. The objective is straightforward: control a continuously growing snake by guiding it to eat small food pellets while avoiding collisions with the boundaries or the snake’s own body. As the snake consumes more food, it grows longer, making the game increasingly challenging and requiring swift reflexes and strategic thinking from the player.
Next, let’s examine Amazon Q Developer’s capability to generate the complete Greedy Snake game directly from natural language prompts.

The Prompts

I will use the same prompt that I used in the previous blog post to interact with Amazon Bedrock, so you can observe the difference between code generation by Amazon Q Developer and Amazon Bedrock.
Here's the prompt I used to generate the code for the Greedy Snake game:
1
2
3
4
5
6
7
8
Write a short and high-quality python script for the following task, something a very skilled python expert would write. You are writing code for an experienced developer so only add comments for things that are non-obvious. Make sure to include any imports required.

NEVER write anything before the ```python``` block. After you are done generating the code and after the ```python``` block, check your work carefully to make sure there are no mistakes, errors, or inconsistencies.

If there are errors, list those errors in tags, then generate a new version with those errors fixed. If there are no errors, write "CHECKED: NO ERRORS" in tags.

Here is the task: write a greedy snake game.
Double check your work to ensure no errors or inconsistencies.
As you can see, this prompt provides detailed requirements for the game's functionality, libraries to use, and other implementation details. Providing this level of specificity is crucial for obtaining high-quality code output.

Develop fearures with /dev

As Shown in the screenshot below, in the Amazon Q Developer chat dialog box, I typed "/dev" before the prompt described above.
Image not found
Develop fearures with /dev
In the context of Amazon Q Developer, "/dev" is a special command used to invoke the Amazon Q Developer Agent for software development, rather than referring to directory like in Linux systems.
You can refer to the “Developing software with the Amazon Q Developer Agent for software development” document at the following link for details:

Interacting with Amazon Q

The screenshot below shows a chat interface from Amazon Q, where the user has requested the AI assistant to generate a high-quality Python script for a Greedy Snake game. The AI assistant acknowledges the request and informs that it may take a few minutes to generate the code.
Image not found
Amazon Q Developer: Generating Code
After several seconds, the Amazon Q Developer responds with a summary of changes.
This part reflects the thought process of the Large Language Model (LLM) behind the Amazon Q Developer, as shown in the following image.
Image not found
Amazon Q Developer: Insights into the LLM's Thought Process for Summarizing Changes
According to the summary of changes, the generative AI model behind the Amazon Q Developer goes through the following steps:
1. It initially plans to open existing files that might be relevant to the problem statement of writing a Greedy Snake game, in order to explore the workspace and determine if any files could be reused or modified.
2. However, it apologizes for an error in the previous iteration, as the workspace is empty, with no existing files related to the snake game. To address the problem statement, it decides to create a new file called "snake_game.py" and start implementing the Greedy Snake game from scratch.
3. The Greedy Snake game is then implemented in the snake_game.py file. It claims that the code appears to be complete and functional.
4. After reviewing the code, it confirms that the Greedy Snake game implementation is complete and functional. It mentions that the code includs all necessary components such as game initialization, main game loop, snake movement, food generation, collision detection, and score display. No obvious errors or improvements are needed.
The "Files used" section at the bottom summarizes the file operations performed during the code generation process. It shows that no files were reviewed (0), one file was created (snake_game.py), and no files were changed or deleted.
Overall, the screenshot depicts the Amazon Q Developer's thought process and actions as it successfully implemented a Greedy Snake game in Python, starting from an empty workspace and creating a new file for the game's code.

The Output: Greedy Snake Game Code

The following is the entire code generated by Amazon Q developer.
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import pygame
import random

# Initialize Pygame
pygame.init()

# Set up the game window
width, height = 640, 480
window = pygame.display.set_mode((width, height))
pygame.display.set_caption("Greedy Snake")

# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)

# Snake properties
snake_block = 20
snake_speed = 15

# Initialize clock
clock = pygame.time.Clock()

# Font for score display
font = pygame.font.SysFont(None, 50)

def draw_snake(snake_list):
for block in snake_list:
pygame.draw.rect(window, GREEN, [block[0], block[1], snake_block, snake_block])

def game_loop():
game_over = False
game_close = False

# Starting position of the snake
x1 = width // 2
y1 = height // 2

# Initial movement
x1_change = 0
y1_change = 0

# Initialize snake
snake_list = []
length_of_snake = 1

# Generate first food
foodx = round(random.randrange(0, width - snake_block) / snake_block) * snake_block
foody = round(random.randrange(0, height - snake_block) / snake_block) * snake_block

while not game_over:
while game_close:
window.fill(BLACK)
message = font.render("You Lost! Press Q-Quit or C-Play Again", True, RED)
window.blit(message, [width // 6, height // 3])
pygame.display.update()

for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
game_loop()

for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0

# Check if snake hits the boundaries
if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_close = True

x1 += x1_change
y1 += y1_change
window.fill(BLACK)
pygame.draw.rect(window, RED, [foodx, foody, snake_block, snake_block])
snake_head = [x1, y1]
snake_list.append(snake_head)

if len(snake_list) > length_of_snake:
del snake_list[0]

# Check if snake hits itself
for segment in snake_list[:-1]:
if segment == snake_head:
game_close = True

draw_snake(snake_list)

# Display score
score = font.render(f"Score: {length_of_snake - 1}", True, WHITE)
window.blit(score, [0, 0])

pygame.display.update()

# Check if snake eats food
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, width - snake_block) / snake_block) * snake_block
foody = round(random.randrange(0, height - snake_block) / snake_block) * snake_block
length_of_snake += 1

clock.tick(snake_speed)

pygame.quit()
quit()

if __name__ == "__main__":
game_loop()
The following image shows the code snippets as the background with a screenshot of the game running in the foreground:
Image not found
Code Snippets as Background with Game Screenshot in Foreground
Before diving into the game's code implemented by the Amazon Q Developer, it's essential to understand the role of Pygame in game development. Pygame is a set of Python modules designed specifically for writing multimedia applications, including games. It provides a wealth of functionality, ranging from handling graphics and sound to managing user input and game events.
The above code is a Python implementation of the classic "Snake" game using the Pygame library. The main functionality includes setting up the game window, initializing the snake and its movements, generating food items, handling user input for controlling the snake, detecting collisions with boundaries or the snake itself, updating the game state, and rendering the game elements on the screen. The game continues until the snake collides with a boundary or itself, at which point the player has the option to quit or restart the game.
However, if you are a beginner at the game, the speed of the snake might be too fast. Thus, let’s assign a new task to the Amazon Q Developer to adjust the speed.

Adjust the speed of the snake

The prompt I plan to be submit to the Amazon Q Developer to adjust the speed of the snake game is as follows:
1
The code works, but the speed of the snake is too fast. I'm just a beginner at the game, could you adjust the game's speed for me?
Image not found
Request for Adjusting Snake Game Speed for Beginners
After submitting the prompt, Amazon Q Developer quickly responded with the following screenshot:
Image not found
Adjusting Snake Game Speed for Beginner Players: Modifying snake_speed Variable
The screenshot displays a chat conversation where the user requests a code adjustment for a snake game, stating that the current speed is too fast for a beginner player. The response explains how to modify the snake_speed variable from its initial value of 15 to a lower value of 8, which should make the snake move slower and the game more manageable for a beginner. The code snippet at the bottom shows the snake_speed variable being changed from 15 to 8 with a comment indicating the adjustment.
You can follow the above suggestion and only need to modify one line, shown as follows:
1
snake_speed = 8
You can try it yourself, and you will see It really works! The snake’s speed is much slower than before, and even a beginner can handle it freely!

Conclusion

This blog post showcased the remarkable capabilities of Amazon Q Developer in generating a fully functional Greedy Snake game prototype from natural language prompts.
The generated code demonstrated the AI model's ability to understand complex requirements, leverage popular libraries, and implement iterative improvements based on user feedback. By adjusting the snake's speed, the AI exhibited its adaptability in personalizing the game experience. The thought process summary provided valuable insights, fostering transparency and trust in the AI system.
As AI technologies advance, tools like Amazon Q Developer have the potential to revolutionize software development by accelerating the prototyping and iteration cycle, promoting innovation. While the Greedy Snake game serves as a simple example, the demonstrated capabilities open up exciting possibilities for more complex applications.
Overall, this post highlighted Amazon Q Developer's abilities and provided a glimpse into the future of software development, where human ingenuity and AI-powered efficiency combine to push boundaries.
If you're ready to build your own game, AWS is running a hackathon through the month of November. From a simple tic tac toe game built with HTML/CSS/JS to a complex Unity game -- all skill levels and tech stacks are welcome. Join now on DevPost: https://awsdevchallenge.devpost.com!
Note: The cover image for this blog post was generated using the SD3 Large 1.0 model on Amazon Bedrock. The prompt given was as follows:
1
“An illustration of a greedy snake slithering through a modern abstract circuit board design, with binary code and computer components in the background, representing the fusion of classic gaming and cutting-edge AI technology. The snake should be large, bold, and vibrant, with a sleek and dynamic appearance. The background should have a futuristic and digital aesthetic, with glowing neon colors and intricate circuitry patterns. The overall style should be a blend of retro gaming elements and contemporary AI/tech motifs.”
 

Any opinions in this post are those of the individual author and may not reflect the opinions of AWS.

1 Comment

Log in to comment