用pygame做一個簡單的python小游戲---貪吃蛇


此文轉載自:https://blog.csdn.net/weixin_46791942/article/details/110383746

用pygame做一個簡單的python小游戲—貪吃蛇

貪吃蛇游戲鏈接:
c++貪吃蛇:
https://blog.csdn.net/weixin_46791942/article/details/106850986
python貪吃蛇:https://blog.csdn.net/weixin_46791942/article/details/110383746

正文開始
下載pygame模塊

pip install pygame 

編寫的是最簡單的貪吃蛇游戲(實現最基本的功能)
效果圖:
在這里插入圖片描述

附上代碼:

import pygame, sys, time, random

color_red = pygame.Color(255, 0, 0)
color_white = pygame.Color(255, 255, 255)
color_green = pygame.Color(0, 255, 0)
pygame.init()
screen = pygame.display.set_mode((600, 400))
screen.fill(color_white)
pygame.display.set_caption("貪吃蛇小游戲")
arr = [([0] * 41) for i in range(61)]  # 創建一個二維數組
x = 10  # 蛇的初始x坐標
y = 10  # 蛇的初始y坐標
foodx = random.randint(1, 60)  # 食物隨機生成的x坐標
foody = random.randint(1, 40)  # 食物隨機生成的y坐標
arr[foodx][foody] = -1
snake_lon = 3  # 蛇的長度
way = 1  # 蛇的運動方向

while True:
    screen.fill(color_white)
    time.sleep(0.1)
    for event in pygame.event.get():  # 監聽器
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if (event.key == pygame.K_RIGHT) and (way != 2):  # 向右移動且避免反向移動
                way = 1
            if (event.key == pygame.K_LEFT) and (way != 1):  # 向左移動且避免反向移動
                way = 2
            if (event.key == pygame.K_UP) and (way != 4):  # 向上移動且避免反向移動
                way = 3
            if (event.key == pygame.K_DOWN) and (way != 3):  # 向下移動且避免反向移動
                way = 4
    if way == 1:
        x += 1
    if way == 2:
        x -= 1
    if way == 3:
        y -= 1
    if way == 4:
        y += 1
    if (x > 60) or (y > 40) or (x < 1) or (y < 1) or (arr[x][y] > 0):  # 判斷死亡(撞牆或自食)
        sys.exit()
    arr[x][y] = snake_lon
    for a, b in enumerate(arr, 1):
        for c, d in enumerate(b, 1):
            # 在二維數組中,食物為-1,空地為0,蛇的位置為正數
            if (d > 0):
                # print(a,c) #輸出蛇的當前坐標
                arr[a - 1][c - 1] = arr[a - 1][c - 1] - 1
                pygame.draw.rect(screen, color_green, ((a - 1) * 10, (c - 1) * 10, 10, 10))
            if (d < 0):
                pygame.draw.rect(screen, color_red, ((a - 1) * 10, (c - 1) * 10, 10, 10))
    if (x == foodx) and (y == foody):   #蛇吃到食物
        snake_lon += 1    #長度+1
        while (arr[foodx][foody] != 0):    #刷新食物
            foodx = random.randint(1, 60)
            foody = random.randint(1, 40)
        arr[foodx][foody] = -1
    pygame.display.update()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM