python课程作业-贪吃蛇

python课程作业-贪吃蛇

现在整理经常会用到的课程作业( python第一弹,持续更新中…)

目录

  • python课程作业-贪吃蛇
    • 简介
    • 系统环境
    • pip安装依赖
    • 实现代码
    • 可能的错误
    • 错误解决
    • 运行结果

简介

现在经常需要用到各种作业,网上的资料存在着各种各样的问题,因此我就为了大家的方便,将这些收集整理并在本地进行验证。对这些代码或资料中能缺少、错误的部分加以修正和补充,确保按照我的步骤可以很简单的把这个代码运行出来,供大家当平时作业或者练习使用。

保证可以运行!!!





系统环境

windows 10
python 3.6、3.7、3.8





pip安装依赖

pip install pygame

如果要求不能使用pygame,可以见:贪吃蛇(二)








实现代码

新建“贪吃蛇.py”文件,下列代码直接复制过去就可以使用:

#-*- coding: utf-8 -*-
import pygame, sys, random, time
from pygame.locals import *

pygame.init()

## 这里如果找不到 可以下载资源
font_file = 'trebuc.ttf'
font_filename = 'C:\\Windows\\Fonts\\' + font_file

font = pygame.font.Font(font_filename,30)
mainClock = pygame.time.Clock()
wsurface = pygame.display.set_mode((800,600),0,32)
pygame.display.set_caption("Snake")

Len = 20
snakeRect = []
for i in range(10,13):
    snakeRect.append(pygame.Rect(i * (Len) , 50 , Len, Len))
food = pygame.Rect(10 * (Len), 10 * (Len), Len, Len)
ml    = False
mr    = True
mu    = False
md    = False
score = 0
black = (0, 0, 0)
green = (0, 255, 0)
white = (255, 255, 255)
global FPSCLOCK
FPSCLOCK = pygame.time.Clock()
#####################################################
def judge():
    if snakeRect[0].left - 15 <= food.left <= snakeRect[0].left + 15 and snakeRect[0].top - 15 <= food.top <= snakeRect[0].top + 15:
        return True
def judge2(a, b):
    if a.left - 15 <= b.left <= a.left + 15 and a.top - 15 <= b.top <= a.top + 15:
        return True
def checkForKeyPress():
    #checkForQuit()
    for event in pygame.event.get([KEYDOWN, KEYUP]):
        if event.type == KEYUP:
            continue
        return event.key
    return None
#######################################################
flagg = True
speed = 8
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.QUIT()
            sys.exit()
        if event.type == KEYDOWN:
            if event.key == K_r:
                snakeRect = []
                for i in range(10,13):
                    snakeRect.append(pygame.Rect(i * (Len) , 50 , Len, Len))
                food = pygame.Rect(10 * (Len), 10 * (Len), Len, Len)
                ml    = False
                mr    = True
                mu    = False
                md    = False
                score = 0
                flagg = True
                speed = 8
            if event.key == K_p:
                wsurface.fill(black)
                text_surface1 = font.render('Pause!' , True, (0, 0, 255))
                wsurface.blit(text_surface1, (10, 50))
                while checkForKeyPress() == None:
                    pygame.display.update()
                    FPSCLOCK.tick()
            if event.key == K_LEFT and mr == False:
                ml = True
                mr = False
                mu = False
                md = False
            if event.key == K_RIGHT and ml == False:
                ml = False
                mr = True
                mu = False
                md = False
            if event.key == K_UP and md == False:
                ml = False
                mr = False
                mu = True
                md = False
            if event.key == K_DOWN and mu == False:
                ml = False
                mr = False
                mu = False
                md = True
    head = pygame.Rect(snakeRect[0].left,snakeRect[0].top,snakeRect[0].width,snakeRect[0].height)
    if flagg == False:
        continue
    if ml == True:
        head.right = head.left - 1
    if mr == True:
        head.left = head.right + 1
    if mu == True:
        head.bottom = head.top - 1
    if md == True:
        head.top = head.bottom + 1
    snakeRect.insert(0, head)
    #判断失败和重新游戏
    if head.right < 0 or head.left > 800 or head.bottom < 0 or head.top > 600 or snakeRect[0] in snakeRect[1:]:
        wsurface.fill(white)
        text_surface2 = font.render('Press R to restart!' , True, (0, 0, 255))
        wsurface.blit(text_surface2, (50, 80))
        pygame.display.update()
        while checkForKeyPress() == None:
            pygame.display.update()
            FPSCLOCK.tick()
            break
        flagg = False
        continue
    flagg = True
    if judge():
        score = score + 10
        speed = speed + 1
        while True:
            flag = True
            food.left = random.randrange(10,800)
            food.top = random.randrange(10,600)
            for temp in snakeRect:
                if judge2(food, temp):
                    flag = False
            if flag == True:
                break
    else:
         snakeRect.pop()
    wsurface.fill(black)
    for i in range(len(snakeRect)):
        pygame.draw.rect(wsurface,green,snakeRect[i])
    pygame.draw.rect(wsurface,white,food)
    text_surface = font.render(u"Score: " + str(score), True, (0, 0, 255))
    wsurface.blit(text_surface, (10, 50))
    pygame.display.update()
    mainClock.tick(speed)




可能的错误

报错:

FileNotFoundError: [Errno 2] No such file or directory: ‘C:\Windows\Fonts\simsunb.ttf’

原因:

报错的原因是缺少字体





错误解决

从下面连接下载字体,放入和.py文件同一个目录下:
在这里插入图片描述

链接:https://pan.baidu.com/s/1eeE8Mqm_XSyXqAnQPOORqQ
提取码:ssjp

并且将下列代码更改:

## 这里如果找不到 可以下载资源
font_file = 'trebuc.ttf'
font_filename = 'C:\\Windows\\Fonts\\' + font_file

为:

## 这里如果找不到 可以下载资源
# font_file = 'trebuc.ttf'
font_filename = './trebuc.ttf'




运行结果

python课程作业-贪吃蛇_第1张图片


参考文献:
python实现贪吃蛇:https://www.cnblogs.com/chengjian-physique/p/8083249.html

你可能感兴趣的:(课程作业,python)