# importing libraries import pygame import time import random snake_speed = 15 # Window size window_x = 720 window_y = 480 # defining colors black = pygame.Color(0, 0, 0) white = pygame.Color(255, 255, 255) red = pygame.Color(255, 0, 0) green = pygame.Color(0, 255, 0) blue = pygame.Color(0, 0, 255) # Initialising pygame pygame.init() # Initialise game window pygame.display.set_caption('GeeksforGeeks Snakes') game_window = pygame.display.set_mode((window_x, window_y)) # FPS (frames per second) controller fps = pygame.time.Clock() # defining snake default position snake_position = [100, 50] # defining first 4 blocks of snake body snake_body = [[100, 50], [90, 50], [80, 50], [70, 50] ] # fruit posiiton fruit_position = [random.randrange(1, (window_x//10)) * 10, random.randrange(1, (window_y//10)) * 10] fruit_spawn = True # setting default snake direction towards # right direction = 'RIGHT' change_to = direction # inital score score = 0 # displaying Score function def show_score(choice, color, font, size): # creating font object score_font score_font = pygame.font.SysFont(font, size) # create the display surface object # score_surface score_surface = score_font.render('Score : ' + str(score), True, color) # create a rectangular object for the text # surface object score_rect = score_surface.get_rect() # displaying text game_window.blit(score_surface, score_rect) # game over function def game_over(): # creating font object my_font my_font = pygame.font.SysFont('times new roman', 50) # creating a text surface on which text # will be drawn game_over_surface = my_font.render( 'Your Score is : ' + str(score), True, red) # create a rectangular object for the text # surface object game_over_rect = game_over_surface.get_rect() # setting position of the text game_over_rect.midtop = (window_x/2, window_y/4) # blit wil draw the text on screen game_window.blit(game_over_surface, game_over_rect) pygame.display.flip() # after 2 seconds we will quit the program time.sleep(2) # deactivating pygame library pygame.quit() # quit the program quit() # Main Function while True: # handling key events for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: change_to = 'UP' if event.key == pygame.K_DOWN: change_to = 'DOWN' if event.key == pygame.K_LEFT: change_to = 'LEFT' if event.key == pygame.K_RIGHT: change_to = 'RIGHT' # If two keys pressed simultaneously # we don't want snake to move into two # directions simultaneously if change_to == 'UP' and direction != 'DOWN': direction = 'UP' if change_to == 'DOWN' and direction != 'UP': direction = 'DOWN' if change_to == 'LEFT' and direction != 'RIGHT': direction = 'LEFT' if change_to == 'RIGHT' and direction != 'LEFT': direction = 'RIGHT' # Moving the snake if direction == 'UP': snake_position[1] -= 10 if direction == 'DOWN': snake_position[1] += 10 if direction == 'LEFT': snake_position[0] -= 10 if direction == 'RIGHT': snake_position[0] += 10 # Snake body growing mechanism # if fruits and snakes collide then scores # will be incremented by 10 snake_body.insert(0, list(snake_position)) if snake_position[0] == fruit_position[0] and snake_position[1] == fruit_position[1]: score += 10 fruit_spawn = False else: snake_body.pop() if not fruit_spawn: fruit_position = [random.randrange(1, (window_x//10)) * 10, random.randrange(1, (window_y//10)) * 10] fruit_spawn = True game_window.fill(black) for pos in snake_body: pygame.draw.rect(game_window, green, pygame.Rect(pos[0], pos[1], 10, 10)) pygame.draw.rect(game_window, white, pygame.Rect( fruit_position[0], fruit_position[1], 10, 10)) # Game Over conditions if snake_position[0] < 0 or snake_position[0] > window_x-10: game_over() if snake_position[1] < 0 or snake_position[1] > window_y-10: game_over() # Touching the snake body for block in snake_body[1:]: if snake_position[0] == block[0] and snake_position[1] == block[1]: game_over() # displaying score countinuously show_score(1, white, 'times new roman', 20) # Refresh game screen pygame.display.update() # Frame Per Second /Refres Rate fps.tick(snake_speed)
Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.
OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.
import sys
name = sys.stdin.readline()
print("Hello "+ name)
Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.
When ever you want to perform a set of operations based on a condition IF-ELSE is used.
if conditional-expression
#code
elif conditional-expression
#code
else:
#code
Indentation is very important in Python, make sure the indentation is followed correctly
For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.
mylist=("Iphone","Pixel","Samsung")
for i in mylist:
print(i)
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while condition
#code
There are four types of collections in Python.
List is a collection which is ordered and can be changed. Lists are specified in square brackets.
mylist=["iPhone","Pixel","Samsung"]
print(mylist)
Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
Below throws an error if you assign another value to tuple again.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)
Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.
myset = {"iPhone","Pixel","Samsung"}
print(myset)
Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.
mydict = {
"brand" :"iPhone",
"model": "iPhone 11"
}
print(mydict)
Following are the libraries supported by OneCompiler's Python compiler
Name | Description |
---|---|
NumPy | NumPy python library helps users to work on arrays with ease |
SciPy | SciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation |
SKLearn/Scikit-learn | Scikit-learn or Scikit-learn is the most useful library for machine learning in Python |
Pandas | Pandas is the most efficient Python library for data manipulation and analysis |
DOcplex | DOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling |