I need some help finalizing and adding some additions to my Snake Game. Please r
ID: 3903278 • Letter: I
Question
I need some help finalizing and adding some additions to my Snake Game. Please respond ASAP! I am using Python version 3.6.5 on Windows. Here is what I need and need help coding in:
- Intro Screen (With title and click to play).
- End screen that shows the total score once game is lost.
- Slower game speed.
If someone is able to help code these in for me so I can see how you did it, I'd greatly appreciate it!
My Game (pygame is necessary, and I commented it to the best of my ability):
import pygame
import sys
import random
class dog():
def __init__(self):
# Starting position of the dog.
self.position = [100,50]
# Starting length of the dog's body.
self.body = [[100,50],[90,50],[80,50]]
# Starting direction of the dog.
self.direction = "RIGHT"
# Enables the dog to change directions.
self.changeDirectionTo = self.direction
def changeDirTo(self,dir):
# Allows the dog to move right ONLY IF dog is NOT moving left.
if dir=="RIGHT" and not self.direction=="LEFT":
self.direction = "RIGHT"
# Allows the dog to move left ONLY IF dog is NOT moving right.
if dir=="LEFT" and not self.direction=="RIGHT":
self.direction = "LEFT"
# Allows the dog to move up ONLY IF dog is NOT moving down.
if dir=="UP" and not self.direction=="DOWN":
self.direction = "UP"
# Allows the dog to move down ONLY IF dog is NOT moving up.
if dir=="DOWN" and not self.direction=="UP":
self.direction = "DOWN"
def move(self,foodPos):
# If the dog moves right, it increases the X-Coordinate by 10 units.
if self.direction == "RIGHT":
self.position[0] += 10
# If the dog moves left, it decreases the X-Coordinate by 10 units.
if self.direction == "LEFT":
self.position[0] -= 10
# If the dog moves left, it increases the Y-Coordinate by 10 units.
if self.direction == "UP":
self.position[1] -= 10
# If the dog moves left, it decreases the Y-Coordinate by 10 units.
if self.direction == "DOWN":
self.position[1] += 10
self.body.insert(0,list(self.position))
# If the dog has collided with a treat, it will generate another treat at a random location.
if self.position == foodPos:
return 1
# If the dog is not picking up a treat, the length of its body does not increase.
else:
self.body.pop()
return 0
# Check if the dog has collided with a wall.
def checkCollision(self):
# Play zone is a (500,500) square, and since the dog moves in increments of 10, 490 is the
# max the dog can reach without colliding with the wall.
if self.position[0] > 490 or self.position[0] < 0:
return 1
elif self.position[1] > 490 or self.position[1] < 0:
return 1
# Check if the head of the dog has collided with the body itself.
for bodyPart in self.body[1:]:
if self.position == bodyPart:
return 1
return 0
def getHeadPos(self):
return self.position
def getBody(self):
return self.body
# Create the random generation of treats.
class foodGenerator():
def __init__(self):
# Make sure food is within the play area and aligns with the movement patterns of the dog.
self.position = [random.randrange(1,50)*10,random.randrange(1,50)*10]
self.isFoodOnScreen = True
# If treat does not generate on the screen, then it is regenerated until it is on the screen and
# Reinitializes it as true.
def spawnFood(self):
if self.isFoodOnScreen == False:
self.position = [random.randrange(1,50)*10,random.randrange(1,50)*10]
self.isFoodOnScreen = True
return self.position
# Once a treat is eaten, it dissappears from the screen.
def setFoodOnScreen(self,b):
self.isFoodOnScreen = b
# Set the pygame window as a (500,500) grid.
window = pygame.display.set_mode((500,500))
# Game title.
pygame.display.set_caption("Treats!")
fps = pygame.time.Clock()
# Initializes the score at 0.
score = 0
dog = dog()
foodGenerator = foodGenerator()
def gameOver():
# When the game is over, the game and console close.
pygame.quit()
sys.exit()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameOver();
# When each key is pressed down, the dog will change its direction.
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
dog.changeDirTo('RIGHT')
if event.key == pygame.K_LEFT:
dog.changeDirTo('LEFT')
if event.key == pygame.K_UP:
dog.changeDirTo('UP')
if event.key == pygame.K_DOWN:
dog.changeDirTo('DOWN')
foodPos = foodGenerator.spawnFood()
if(dog.move(foodPos)==1):
score+=1
foodGenerator.setFoodOnScreen(False)
# Set backgroud color for game to grass green. (RGB Colors)
window.fill(pygame.Color(34,139,34))
for pos in dog.getBody():
# Set the color of the dog and the size of the dog. Since the dog is moving in increments of 10, the
# Size of the dog will be a square of the same length (ten by ten).
pygame.draw.rect(window,pygame.Color(153,76,0),pygame.Rect(pos[0],pos[1],10,10))
pygame.draw.rect(window,pygame.Color(102,52,0),pygame.Rect(foodPos[0],foodPos[1],10,10))
# If the dog collides with something, then the game is over.
if(dog.checkCollision()==1):
gameOver()
pygame.display.set_caption('Score : '+ str(score) )
# Reset the game on game over.
pygame.display.flip()
# Keep the framerate constant at 24 frames per second.
fps.tick(24)
Explanation / Answer
Answer: See the code below:
1. Intro window and score label:
----------------------------------------------
#import tkinter
import tkinter as tk
#class to generate Intro window
class MySnakeApp(tk.Frame):
def __init__(self,master=None):
tk.Frame.__init__(self,master)
self.master.minsize(300,300)
self.grid()
self.addComponents()
def addComponents(self):
self.playButton = tk.Button(self,text='Play',command=self.showMessage)
#self.scoreLabel = tk.Label(self,text="Score:20") #uncomment for score label
self.playButton.grid()
#self.scoreLabel.grid() #uncomment for score label
def showMessage(self):
print("Play Game")
#show window
snakeApp = MySnakeApp()
snakeApp.master.title('My Snake Game')
snakeApp.mainloop()
--------------------------------------