大家好,相信学习过Python的朋友们都知道Python中有很多好玩好用的模块,今天我们就来介绍一个模块--pygame
安装方法:pip install pygame
现在就是怎么制作了,我们首先定义了游戏结束自动关闭界面
然后定义一个长640,宽500的主窗口
?紧接着就是while True来控制射的运动
最后就要画蛇和目标方块
?
然后我们以主窗口来运行它
?
?运行结果如图
?
源代码我放在下面,需要的自取
# -*- coding: utf-8 -*-
'''
Author:郑某
'''
import datetime
import pygame,sys,random
from pygame.locals import *
print("当前年份: "+str(datetime.datetime.now().year))
print("当前日期时间 "+datetime.datetime.now().strftime('%y-%m-%d %H:%M:%S'))
redColour = pygame.Color(255,0,0)
blackColour = pygame.Color(0,0,0)
whiteColour = pygame.Color(255,255,255)
def gameOver():
pygame.quit()
sys.exit()
def main():
pygame.init()
fpsClock = pygame.time.Clock()
playSurface = pygame.display.set_mode((640,500)) # 创建游戏界面的大小
pygame.display.set_caption('贪吃蛇') # 创建游戏标题
snakePosition = [100,100]
snakeBody = [[100,100],[80,100],[60,100]]
targetPosition = [300,300]
targetflag = 1
direction = 'right'
changeDirection = direction
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_RIGHT or event.key == ord('d'):
changeDirection = 'right'
if event.key == K_LEFT or event.key == ord('a'):
changeDirection = 'left'
if event.key == K_UP or event.key == ord('w'):
changeDirection = 'up'
if event.key == K_DOWN or event.key == ord('s'):
changeDirection = 'down'
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
if changeDirection == 'left' and not direction == 'right':
direction = changeDirection
if changeDirection == 'right' and not direction == 'left':
direction = changeDirection
if changeDirection == 'up' and not direction == 'down':
direction = changeDirection
if changeDirection == 'down' and not direction == 'up':
direction = changeDirection
#3.7 根据方向移动蛇头的坐标
if direction == 'right':
snakePosition[0] += 20
if direction == 'left':
snakePosition[0] -= 20
if direction == 'up':
snakePosition[1] -= 20
if direction == 'down':
snakePosition[1] += 20
snakeBody.insert(0,list(snakePosition))
if snakePosition[0] == targetPosition[0] and snakePosition[1] == targetPosition[1]:
targetflag = 0
else:
snakeBody.pop()
if targetflag == 0:
x = random.randrange(1,32)
y = random.randrange(1,24)
targetPosition = [int(x*20),int(y*20)]
targetflag = 1
playSurface.fill(blackColour)
for position in snakeBody: #rect(Surface, color, Rect, width=0)
pygame.draw.rect(playSurface,whiteColour,Rect(position[0],position[1],20,20))#画蛇
pygame.draw.rect(playSurface,redColour,Rect(targetPosition[0], targetPosition[1],20,20)) #画目标方块
pygame.display.flip()
if snakePosition[0] > 620 or snakePosition[0] < 0:
gameOver()
elif snakePosition[1] > 460 or snakePosition[1] < 0:
gameOver()
fpsClock.tick(5)
if __name__ == "__main__": #主窗口运行该程序
main()
|