本篇文章主要介绍如何实现游戏界面
实现贪吃蛇游戏,我们首先需要画一张游戏地图,具体代码如下
import pygame,sys
grey = 60,60,60
black = 0,0,0
green = 0,255,0
red = 255,0,0
myfont = (None,48)
width = 800
height = 500
size = 20
pygame.init()
screen = pygame.display.set_mode((width,height))
pygame.display.set_caption("贪吃蛇")
screen.fill(grey)
#画地图
def print_map():
for x in range(0,width,size):
pygame.draw.line(screen,black,(x,0),(x,height))
for y in range(0,height,size):
pygame.draw.line(screen,black,(0,y),(width,y))
pygame.display.update()
print_map()
运行效果如下:
现在,我们已经画好了地图,接下来就是写我们的游戏主角——贪吃蛇
那么,首先我们先让主角显示在屏幕上,添加如下代码
snake = [(0,0),(1,0),(2,0)]
for s in snake:
x = s[0] * size
y = s[1] * size
pygame.draw.rect(screen,green,(x,y,size-1,size-1))
此时,我们的游戏主角已经出现了:
接下来,就是要让食物出现在游戏界面上
添加如下代码:
pygame.draw.rect(screen,red,(100,100,size-1,size-1))
最终代码:
import pygame,sys
grey = 60,60,60
black = 0,0,0
green = 0,255,0
red = 255,0,0
myfont = (None,48)
width = 800
height = 500
size = 20
pygame.init()
screen = pygame.display.set_mode((width,height))
pygame.display.set_caption("贪吃蛇")
screen.fill(grey)
#画地图
def print_map():
for x in range(0,width,20):
pygame.draw.line(screen,black,(x,0),(x,height))
for y in range(0,height,20):
pygame.draw.line(screen,black,(0,y),(width,y))
pygame.display.update()
#设置蛇
snake = [(0,0),(1,0),(2,0)]
for s in snake:
x = s[0] * size
y = s[1] * size
pygame.draw.rect(screen,green,(x,y,size-1,size-1))
#食物
pygame.draw.rect(screen,red,(100,100,size-1,size-1))
print_map()