snake game python code


 

 Snake python game 

Code-

import pygame
import random


width=720
height=480

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)



pygame.init()
screen=pygame.display.set_mode((width,height))
title=pygame.display.set_caption('snake game by pydev')
fps=pygame.time.Clock()

score=0
snake=[[400,200] ]

fruit=[[random.randrange(10,71)*10 ,
       random.randrange(10,47)*10] ]
fruit_spawn=True

direction='RIGHT'
change_to = direction

def point():
    
    font = pygame.font.SysFont(None, 30)
    text = font.render(f'Score: {score}', True, (0, 0, 0))
    screen.blit(text, (30, 30))
point()
def game_over():
    
    font = pygame.font.SysFont(None, 30)
    text = font.render(f'GAME OVER Score: {score}', True, (0, 0, 0))
    screen.blit(text, (200, 200))
game_over()




running = True
while running:
    screen.fill(white)
    point()
    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 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'
        
                
    

    head = snake[0]  
    if direction == 'RIGHT':
        new_head = [head[0] + 10, head[1]]
    elif direction == 'LEFT':
        new_head = [head[0] - 10, head[1]]
    elif direction == 'UP':
        new_head = [head[0], head[1] - 10]
    elif direction == 'DOWN':
        new_head = [head[0], head[1] + 10]

    snake.insert(0, new_head)
    if snake[0][0]==fruit[0][0] and snake[0][1]==fruit[0][1] :
        
        fruit_spawn=False
        score+=10
    else:
        snake.pop()

    if not fruit_spawn:
        fruit = [[random.randrange(10, 71)*10, random.randrange(10, 47)*10]]
        fruit_spawn = True




                
    for pos in snake:
        pygame.draw.rect(screen,blue , pygame.Rect(pos[0],pos[1],10,10), border_radius=2)
    for pos in fruit:
        pygame.draw.rect(screen,green, pygame.Rect(pos[0],pos[1],10,10),border_radius=2)


    if snake[0][0]>710 or snake[0][1]>470 :
        game_over()
    if snake[0][0]<10 or snake[0][1]<10 :
        game_over()

        
    if new_head in snake[1:]:
        game_over()
        pygame.display.update()
        pygame.time.delay(2000)  
        running = False

    
    fps.tick(8)

    pygame.display.update() 

 Let’s master it step by step:-

 🟠step 1.module import  करो 

🟠 step 2. window और कलर सेट करो , फ्रेम रेट और डिस्प्ले अपडेट करो

🟠 step 3. करैक्टर को पोजीशन दो , और उनकी बॉडी बनाओ 

🟠 step 4. score और गेम ओवर की विंडो बनाओ 

🟠 step 4. key सेट करो 

🟠 step 5.लॉजिक बनाओ जेसे - snake के हेड की  और फ्रूट की लोकेशन एक है to फ्रूट को हटाओ और score बढाओ 

🟠 step 6. आउट होने के लॉजिक बनाओ और गेम ओवर करो |

pygame– गेम बनाने के लिए लाइब्रेरी।

radom – फ्रूट को random जगह पर दिखाने के लिए।

गेम की window का साइज सेट किया: चौड़ाई = 720px, ऊंचाई = 480px

pygame.Color(R,G,B) से रंग बनाए: 

pygame.init()– गेम स्टार्ट करने के लिए ज़रूरी initialization।

display.set_mode – विंडो बनाता है।

set_caption – टाइटल सेट करता है।

Clock() – फ्रेम रेट कंट्रोल करने के लिए।Snake की शुरुआती position स्क्रीन के बीच में।

random.randrange(...) * 10 – फ्रूट को ग्रिड के हिसाब से दिखाता है।

 

fruit_spawn = True – बताता है कि fruit दिखाना है। 

score दिखाने के लिए एक function बनाते है -

 

  def point():

  पॉइंट नाम का फंक्शन बनाया 

   font = pygame.font.SysFont(None, 30)

   font नाम का veriable , pygame के font module से sysfont फंक्शन , none= कोई फॉण्ट स्टाइल नहीं ली है आप चाहे तो ले सकते है  , 30= फॉण्ट साइज़
    text = font.render(f'Score: {score}', True, (0, 0, 0))

   render method से  score card एक image जेसा बन जायेगा   

  screen.blit(text, (30, 30))

score function की विंडो बिल्ड करो width=30, height=30

अभी तक यह function बना है आगे इसे काम में लेंगे

इसी तरह game over function भी बनाओ - जिसका हम use करेंगे आउट होने पर 


running = True
while running:
while लूप से game शुरू होगा यहाँ while लूप इसलिए use में लिया गया जिससे की विंडो चलती रहे 

इसे हम ऐसे भी लिख सकते है   running को हटाकर
while True :

screen.fill(white)

स्क्रीन का कलर रहो white
 

point()

अब point विंडो को दिखाना है 

 

यह पार्ट समझना सबसे इम्पोर्टेन्ट है 

for event in pygame.event.get():

लो एक घटना को में से , pygame के event method से, get-लो
    if event.type == pygame.KEYDOWN:

   यदि घटना का type == keydown   मतलब की key प्रेस की जाती है to 

      if event.key == pygame.K_UP:

      यदि key == K_UP  = यह pygame में पहले से सेट किया गया है   up key  के लिए        

     change_to = 'UP'

  change_to को up कर दो  

इसी तरह बाकि
if change_to == 'UP' and direction != 'DOWN':
    direction = 'UP'
...
यदि change_to == up के और , डायरेक्शन पहले से down नहीं है तो

direction को up कर दो मतलब अब snake उपर जायेगा 

Snake का सिर (Head) Move करना

head = snake[0]
snake[0] का अर्थ है snake के हेड की value [x,y]
अगर snake[1] होता तो उसका अर्थ होता snake की बॉडी के पहले coloum की value   
if direction == 'RIGHT':
  new_head = [head[0] + 10, head[1]]
 डायरेक्शन राईट साइड में होती हैतो हेड[0]( x एक्सिस )में 10px बढाओ यहाँ आप 20 30 अपनी मर्जी से रख सकते हो

snake.insert(0, new_head)

snake में इन्सर्ट करो न्यू हेड  0 = शुरू में न की बॉडी में 

 

if snake[0][0] == fruit[0][0] and snake[0][1] == fruit[0][1]:

यदि फ्रूट की x y एक्सिस = snake की x y एक्सिस 

   fruit_spawn = False

तब फ्रूट को false कर दो 

    score += 10
else:
    snake.pop() का अर्थ है की

snake आगे बढ़े तब यह भी जरुरी है की snake की टेल आगे बढे इसलिए snake के हेड बनते ही टेल काट दो 

नया Fruit बनाना अगर पुराना खा लिया

for pos in snake:
    pygame.draw.rect(screen, blue, pygame.Rect(pos[0], pos[1], 10, 10), border_radius=2)
 

 snake की  बॉडी को draw करो rectangular में ( विंडो का नाम , कलर , pos[0](x axis), pos[1] y axis  width, height ) उसकी border रेडियस  )

 

इसी तरह फ्रूट की पोजीशन बनाओ

👉अब सवाल: Snake और Fruit को “लूप के start में ही” draw क्यों नहीं कर सकते?

⛔ ऐसा करने पर समस्या:

  • अगर पहले draw कर दिया, और बाद में फ्रूट खाने का कोड चलेगा जिससे की वो अपडेट नहीं होगा क्युकी पोजीशन तो पहले ही draw कर दी 

    पाइथन कोड को लाइन बाई लाइन पढता है इसलिए


if snake[0][0] > 710 or snake[0][1] > 470:
    game_over()
if snake[0][0] < 10 or snake[0][1] < 10:
    game_over()

अब अगर snake[0] (हेड) [0]  (x पोजीशन ) और y पोजीशन fixed px से आगे जाते है तो आउट कर दो और game_over function चला दो 

 

Self Collision (Snake खुद से टकराया?)

if new_head in snake[1:]:

यदि न्यू हेड में से , snake के snake[0] coloumn को छोड़कर snake[1:] =1 से लेकर लास्ट तक कही भी हो to     game_over()
    pygame.display.update()
    pygame.time.delay(2000)

 टाइम २ sec डिले के बाद
    running = False

fps.tick(8)
pygame.display.update()

 
गेम को 8 FPS पर चला रहे हैं। fps बढ़ाने पर snake की स्पीड बढ़ेगी

हर frame को update किया जाता है।

 

summary - 

 while game चल रहा है:
    1. screen को साफ़ करो (fill white)
    2. score दिखाओ
    3. events को handle करो (keyboard input वगैरह)
    4. direction और snake की नई head तय करो
    5. fruit खाया तो score बढ़ाओ, नहीं तो tail हटाओ
    6. fruit दोबारा बनाओ (अगर खा लिया गया है)
    7. snake की बॉडी draw करो ✅
    8. fruit को draw करो ✅
    9. collision check करो
    10. delay लगाओ (fps.tick)
    11. display update करो



🎯 Task for You: (give answer in comment)

1.बैकग्राउंड में कोई image लगाईये इस गेम में 
2. 5 बार फ्रूट spawn होने पर एक बोनस फ्रूट spawn कीजिये और उसके एक्स्ट्रा score दीजिये 

 

                          Your feedback is fuel for our journey — keep it coming!


 


 

 

 

No comments:

Post a Comment