贪吃蛇python游戏

贪吃蛇经典小游戏,使用python程序进行自制复刻

gitcode项目链接:Austin-Clinton / 贪吃蛇python版 · GitCode

源代码:

#贪吃蛇Python游戏
#by hhh in 2021.4.18 first (后续维护)4.20 second 4.22 third 9.23 9.24 Fourthly
#2022.9.25 CSDN@Austin-Cliton
import pygame
import sys
import random

i=3#起始节数
k=0#速度增量
BLACK = (0,0,0)#颜色定义
RED= (255,0,0)
BLUE = (25,90,220)

size = width,height = 600,600#建图
surface = pygame.display.set_mode(size)

snake_length = [[150,150],[140,150],[130,150]]#蛇定义
snake_position = [150,150]

food_position = [random.randint(1,49)*10,random.randint(1,49)*10]#食物定义

direction = 'right'#初始化方向

def Begin():#初始化+刷新函数
    pygame.display.set_caption('109的贪吃蛇 by Hhh')
    pygame.time.Clock().tick(22+k)
    image = pygame.image.load('505.png').convert()
    surface.blit(image, (0, 0))
    # surface.fill(BLACK)
    for i in snake_length:
        pygame.draw.rect(surface, BLUE, (i[0], i[1], 10, 10), 0)
        pygame.draw.rect(surface, RED, (food_position[0], food_position[1], 10, 10), 0)#画蛇
    drawScore()#得分函数
    pygame.display.flip()#刷新页面

def Go():#前进函数
    if direction == 'right':
        snake_position[0] += 10
    if direction == 'left':
        snake_position[0] -= 10
    if direction == 'up':
        snake_position[1] -= 10
    if direction == 'down':
        snake_position[1] += 10

def Grow():#生长函数
    snake_length.insert(0, list(snake_position))
    if snake_position[0] == food_position[0] and snake_position[1] == food_position[1]:
        food_position[0] = random.randint(1,49)*10
        food_position[1] = random.randint(1,49)*10
        global i
        i += 1
        global k
        k += 2
    else:
        snake_length.pop()#移除最后一个元素

def Kill():#自杀函数(头撞身体)
    global A#自杀指数
    A = 1#自杀存疑
    for k in range(2,i,1):
        if snake_position == snake_length[k]:
            A = 0#自杀确认
            break

def Exit():#退出函数
        print("...Game Over...")
        while 1:
            if pygame.event.get(pygame.KEYDOWN) or pygame.event.get(pygame.QUIT):
                 break

def drawScore():#得分函数
    s=i-3
    pygame.init()  # 字体设置:开启注释
    font1 = pygame.font.SysFont('宋体', 30)  # 设置系统字体
    font_list = pygame.font.get_fonts()  # 获得系统可用字体
    surface1 = font1.render('score: %s'% (s),True,[255,0,0])#打印字体
    surface.blit(surface1,[20,20])#显示颜色
    surface2 = font1.render('velocity: %s' % (22+k), True, [255, 0, 0])
    surface.blit(surface2, [450, 20])

while 1 :
    Begin()#初始化+刷新函数
    for event in pygame.event.get():#转向程序
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if (event.key == pygame.K_RIGHT or event.key == pygame.K_d) and direction != 'left':#条件三防原地掉头
                direction = 'right'
            if (event.key == pygame.K_LEFT or event.key == pygame.K_a) and direction != 'right':
                direction = 'left'
            if (event.key == pygame.K_UP or event.key ==  pygame.K_w) and direction != 'down':
                direction = 'up'
            if (event.key == pygame.K_DOWN or event.key == pygame.K_s) and direction != 'up':
                direction = 'down'
            if event.key == pygame.K_ESCAPE:
                pygame.quit()
                sys.exit()
    Go()#前进函数
    Grow()#生长函数
    Kill()#自杀函数
    if snake_position[0] < 0 or snake_position[0] > width or snake_position[1] < 0 or snake_position[1] > height or A == 0:
    #死亡条件
        Exit()#退出函数
        print('score:',i-3)
        break

#未经作者授权,也可以转载~

## 注释十分清晰,相关库函数问题大家可以自行查找学习

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一份简单的双人贪吃蛇Python游戏的代码,希望对你有所帮助: ```python import tkinter as tk import random # 定义游戏区域大小 WIDTH = 500 HEIGHT = 500 # 定义蛇的初始长度 INIT_LENGTH = 5 # 定义每个格子的大小 GRID_SIZE = 20 # 定义蛇的移动速度 SPEED = 100 # 定义蛇的颜色 SNAKE_COLOR = "green" # 定义食物的颜色 FOOD_COLOR = "red" # 定义蛇的方向 UP = 1 DOWN = 2 LEFT = 3 RIGHT = 4 class Snake: def __init__(self, canvas, x, y, length, color): self.canvas = canvas self.x = x self.y = y self.length = length self.color = color self.direction = random.randint(1, 4) self.body = [] for i in range(length): self.body.append(canvas.create_rectangle(x-i*GRID_SIZE, y, x-(i-1)*GRID_SIZE, y+GRID_SIZE, fill=color)) def move(self): if self.direction == UP: self.y -= GRID_SIZE elif self.direction == DOWN: self.y += GRID_SIZE elif self.direction == LEFT: self.x -= GRID_SIZE elif self.direction == RIGHT: self.x += GRID_SIZE for i in range(self.length-1, 0, -1): self.canvas.coords(self.body[i], *self.canvas.coords(self.body[i-1])) self.canvas.coords(self.body[0], self.x, self.y, self.x+GRID_SIZE, self.y+GRID_SIZE) def change_direction(self, direction): if direction == UP and self.direction != DOWN: self.direction = UP elif direction == DOWN and self.direction != UP: self.direction = DOWN elif direction == LEFT and self.direction != RIGHT: self.direction = LEFT elif direction == RIGHT and self.direction != LEFT: self.direction = RIGHT def eat_food(self, food): x1, y1, x2, y2 = self.canvas.coords(self.body[0]) if x1 == food.x and y1 == food.y: self.length += 1 self.body.append(self.canvas.create_rectangle(*self.canvas.coords(self.body[-1]), fill=self.color)) food.new_food() class Food: def __init__(self, canvas, color): self.canvas = canvas self.color = color self.x = random.randint(0, WIDTH/GRID_SIZE-1) * GRID_SIZE self.y = random.randint(0, HEIGHT/GRID_SIZE-1) * GRID_SIZE self.body = canvas.create_rectangle(self.x, self.y, self.x+GRID_SIZE, self.y+GRID_SIZE, fill=color) def new_food(self): self.x = random.randint(0, WIDTH/GRID_SIZE-1) * GRID_SIZE self.y = random.randint(0, HEIGHT/GRID_SIZE-1) * GRID_SIZE self.canvas.coords(self.body, self.x, self.y, self.x+GRID_SIZE, self.y+GRID_SIZE) class Game: def __init__(self, master): self.master = master self.canvas = tk.Canvas(master, width=WIDTH, height=HEIGHT, bg="white") self.canvas.pack() self.snake1 = Snake(self.canvas, WIDTH/2, HEIGHT/2, INIT_LENGTH, SNAKE_COLOR) self.snake2 = Snake(self.canvas, WIDTH/2 - GRID_SIZE, HEIGHT/2, INIT_LENGTH, "blue") self.food = Food(self.canvas, FOOD_COLOR) self.canvas.bind_all("<Up>", lambda event: self.snake1.change_direction(UP)) self.canvas.bind_all("<Down>", lambda event: self.snake1.change_direction(DOWN)) self.canvas.bind_all("<Left>", lambda event: self.snake1.change_direction(LEFT)) self.canvas.bind_all("<Right>", lambda event: self.snake1.change_direction(RIGHT)) self.canvas.bind_all("w", lambda event: self.snake2.change_direction(UP)) self.canvas.bind_all("s", lambda event: self.snake2.change_direction(DOWN)) self.canvas.bind_all("a", lambda event: self.snake2.change_direction(LEFT)) self.canvas.bind_all("d", lambda event: self.snake2.change_direction(RIGHT)) self.timer = self.master.after(SPEED, self.game_loop) def game_loop(self): self.snake1.move() self.snake2.move() self.snake1.eat_food(self.food) self.snake2.eat_food(self.food) if self.check_collision(): self.master.after_cancel(self.timer) self.canvas.create_text(WIDTH/2, HEIGHT/2, text="游戏结束!", fill="red", font=("Arial", 30)) return self.timer = self.master.after(SPEED, self.game_loop) def check_collision(self): x1, y1, x2, y2 = self.canvas.coords(self.snake1.body[0]) if x1 < 0 or x2 > WIDTH or y1 < 0 or y2 > HEIGHT: return True for body in self.snake1.body[1:]: if self.canvas.coords(body) == (x1, y1, x2, y2): return True for body in self.snake2.body: if self.canvas.coords(body) == (x1, y1, x2, y2): return True x1, y1, x2, y2 = self.canvas.coords(self.snake2.body[0]) if x1 < 0 or x2 > WIDTH or y1 < 0 or y2 > HEIGHT: return True for body in self.snake2.body[1:]: if self.canvas.coords(body) == (x1, y1, x2, y2): return True for body in self.snake1.body: if self.canvas.coords(body) == (x1, y1, x2, y2): return True return False root = tk.Tk() game = Game(root) root.mainloop() ``` 该游戏使用tkinter库实现,运行后会在窗口中显示一个游戏区域,两条贪吃蛇一个食物。玩家1使用键盘上的方向键控制自己的蛇,玩家2使用W、A、S、D键控制自己的蛇,当蛇吃到食物时,身体长度会增加。当任意一条蛇撞到边界或自己的身体时,游戏结束。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值