??????
感谢优秀的你打开了小白的文章
“希望在看文章的你今天又进步了一点点,离美好生活更近一步!”🌈
前言
Python Pygame 是一款专门为开发和设计 2D 电子游戏而生的软件包,它支 Windows、Linux、Mac OS 等操作系统,具有良好的跨平台性。Pygame 由??Pete Shinners 于 2000 年开发而成,是一款免费、开源的的软件包,因此您可以放心地使用它来开发游戏,不用担心有任何费用产生。 Pygame 在 SDL(Simple DirectMedia Layer,使用 C语言编写的多媒体开发库) 的基础上开发而成,它提供了诸多操作模块,比如图像模块(image)、声音模块(mixer)、输入/输出(鼠标、键盘、显示屏)模块等。
相比于开发 3D 游戏而言,Pygame 更擅长开发 2D 游戏,比如于飞机大战、贪吃蛇、扫雷等游戏。
环境配置?
开始>所有程序 >Anaconda3(64-bit)>Anaconda prompt,直接输入Python,回车 接着换行输入pip install pygame ?
简单的贪吃蛇实现
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pygame,sys,random
from pygame.locals import *
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,480)) # 创建游戏界面的大小
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:
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()
?结果展示
?
|