Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· openaiHugging Face Suzhen/CodeChat

snake game in phyton codes

  1. User

    snake game in phyton codes

  2. Assistant

    Creating a simple Snake game in Python typically involves using a module to create a graphical interface. One of the most common modules used for this purpose is pygame, which provides functions to draw graphics and handle game events.

    Below is a basic example of a Snake game in Python using pygame. Please make sure you have pygame installed before running the code (pip install pygame).

    import pygame
    import time
    import random
    
    pygame.init()
    
    # Define colors
    white = (255, 255, 255)
    yellow = (255, 255, 102)
    black = (0, 0, 0)
    red = (213, 50, 80)
    green = (0, 255, 0)
    blue = (50, 153, 213)
    
    # Set up the display
    dis_width = 600
    dis_height = 400
    dis = pygame.display.set_mode((dis_width, dis_height))
    pygame.display.set_caption('Snake Game by Pythonist')
    
    clock = pygame.time.Clock()
    snake_block = 10
    snake_speed = 15
    
    font_style = pygame.font.SysFont("bahnschrift", 25)
    score_font = pygame.font.SysFont("comicsansms", 35)
    
    def your_score(score):
        value = score_font.render("Your Score: " + str(score), True, yellow)
        dis.blit(value, [0, 0])
    
    # Function to draw the snake
    def our_snake(snake_block, snake_list):
        for x in snake_list:
            pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])
    
    # Function to display messages
    def message(msg, color):
        mesg = font_style.render(msg, True, color)
        dis.blit(mesg, [dis_width / 6, dis_height / 3])
    
    # Game loop
    def gameLoop():
        game_over = False
        game_close = False
    
        x1 = dis_width / 2
        y1 = dis_height / 2
    
        x1_change = 0
        y1_change = 0
    
        snake_List = []
        Length_of_snake = 1
    
        foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
        foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
    
        while not game_over:
    
            while game_close == True:
                dis.fill(blue)
                message("You lost! Press Q-Quit or C-Play Again", red)
                your_score(Length_of_snake - 1)
                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:
                            gameLoop()
    
            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
    
            if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
                game_close = True
            x1 += x1_change
            y1 += y1_change
            dis.fill(blue)
            pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
            snake_Head = []
            snake_Head.append(x1)
            snake_Head.append(y1)
            snake_List.append(snake_Head)
            if len(snake_List) > Length_of_snake:
                del snake_List[0]
    
            for x in snake_List[:-1]:
                if x == snake_Head:
                    game_close = True
    
            our_snake(snake_block, snake_List)
            your_score(Length_of_snake - 1)
    
            pygame.display.update()
    
            if x1 == foodx and y1 == foody:
                foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
                foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
                Length_of_snake += 1
    
            clock.tick(snake_speed)
    
        pygame.quit()
        quit()
    
    gameLoop()
    

    This is a basic implementation of the Snake game. You can move the snake using the arrow keys. The game will end if the snake runs into the screen border or itself, and you can press 'Q' to quit or 'C' to play again after losing.

    Before you run this code, ensure you have pygame installed in your Python environment. You can install it using the following command:

    pip install pygame
    

    Remember that this is just a simplification of the game without any advanced features like increasing difficulty levels or a main menu. You can explore pygame further to add more functionalities such as better graphics, sound effects, or even an AI to play the game.

  3. User

    Yazı ile olabilecek bir oyun söyle

  4. Assistant

    Elbette, Python kullanarak bir metin tabanlı "Tahmin Oyunu" oluşturabiliriz. Bu oyun, bilgisayarın 1 ve 100 arasında rastgele bir sayı seçtiği ve kullanıcının bu sayıyı tahmin etmeye çalıştığı basit bir sayı tahmin oyunudur. Kullanıcı her yanlış tahminde ipucu alır ve doğru tahminde bulunana kadar devam eder.

    İşte bu oyunun Python'da bir örneği:

    import random
    
    def tahmin_oyunu():
        rastgele_sayi = random.randint(1, 100)
        tahmin_sayacı = 0
        
        print("1 ile 100 arasında (1 ve 100 dahil) bir sayı tahmin etmeye çalışın.")
        
        while True:
            tahmin = input("Tahmininizi girin: ")
            tahmin_sayacı += 1
            
            try:
                tahmin = int(tahmin)
            except ValueError:
                print("Lütfen geçerli bir sayı girin.")
                continue  # Devam edip yeni bir giriş istiyoruz
    
            if tahmin < 1 or tahmin > 100:
                print("Tahmin 1 ile 100 arasında olmalıdır!")
            elif tahmin < rastgele_sayi:
                print("Daha yüksek bir sayı tahmin edin.")
            elif tahmin > rastgele_sayi:
                print("Daha düşük bir sayı tahmin edin.")
            else:
                print(f"Tebrikler! Sayıyı {tahmin_sayacı} tahminde buldunuz.")
                break  # Çıkış yaparak döngüyü sonlandırıyoruz
    
    # Oyunu başlat
    tahmin_oyunu()
    

    Bu oyunu çalıştırmak için, Python yüklü bir terminal veya IDE'de yukarıdaki kodu bir dosyaya yapıştırabilirsiniz (örneğin tahmin_oyunu.py olarak kaydedebilirsiniz) ve ardından bu dosyayı çalıştırabilirsiniz. Oyuncudan bir sayı girmesi istenir, eğer tahminleri yanlışsa yüksek ya da düşük diye ipucu verilir, doğru tahminde bulunana kadar devam eder. Oyun, kullanıcının doğru sayıyı tahmin etmesiyle sona erer.