使用pycharm完成
- 首先 pip install pygame
- 后面就是根据逻辑搬代码了
- 只是简化版的贪吃蛇游戏,当然还能完善一下细节
Plus代码:
class Point:
row=0
col=0
def __init__(self, row, col):
self.row = row
self.col = col
def copy(self):
return Point(row=self.row,col=self.col)
import pygame
import random
#初始化
pygame.init()
W=800
H=600
ROW = 30
COL = 40
size = (W, H)
window = pygame.display.set_mode(size)
pygame.display.set_caption('贪吃蛇')
def gen_food():
while 1:
pos=Point(row=random.randint(0,ROW-1), col=random.randint(0,COL-1))
#食物出现在头上
is_coll=False
if head.row==pos.row and head.col==pos.col:
is_coll=True
#食物出现在身体上
for snack in snacks:
if snack.row==pos.row and snack.col==pos.col:
is_coll=True
break
if not is_coll:
break
return pos
bg_color=(255,255,255)
snack_color=(200,200,200)
#定义坐标
head = Point(row = int(ROW/2),col=int(COL/2))
head_color = (0,128,128)
food = Point(row=random.randint(0,ROW-1), col=random.randint(0,COL-1))
food_color=(255,255,0)
snacks=[
Point(row=head.row,col=head.col+1),
Point(row=head.row,col=head.col+2),
Point(row=head.row,col=head.col+3)
]
direct='left'
def rect(point,color):
cell_width=W/COL
cell_height=H/ROW
left = point.col*cell_width
top = point.row*cell_height
pygame.draw.rect(
window,color,
(left,top,cell_width,cell_height)
)
#游戏循环
run = True
clock = pygame.time.Clock()
while run:
#处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
run=False
elif event.type==pygame.KEYDOWN:
# print(event)
if event.key==1073741906:
if direct=='left' or direct=='right':
direct='up'
elif event.key==1073741905:
if direct == 'left' or direct == 'right':
direct='down'
elif event.key==1073741904:
if direct == 'up' or direct == 'down':
direct='left'
elif event.key==1073741903:
if direct == 'up' or direct == 'down':
direct = 'right'
# 吃东西
eat=(head.row==food.row and head.col==food.col)
#重新产出食物
if eat :
food = gen_food()
#处理body
#1.把原来的头,插入到snacks的头上
snacks.insert(0,head.copy())
# 2.把snkes的最后一个删掉
if not eat:
snacks.pop()
#移动
if direct=='left':
head.col-=1
elif direct=='right':
head.col+=1
elif direct=='up':
head.row-=1
elif direct=='down':
head.row+=1
#检测
dead=False
#1.撞墙
if head.col<0 or head.row<0 or head.col>=COL and head.row>=ROW:
dead=True
#2.撞自己
for snack in snacks:
if head.row==snack.row and head.col==snack.col:
dead=True
break
if dead:
print("你死了")
run=False
#渲染 - 画出来
pygame.draw.rect(window,bg_color, (0,0,W,H))
#蛇头
for body in snacks:
rect(body,snack_color)
rect(head,head_color)
rect(food,food_color)
#更新整个待显示的Surface对象到屏幕上
pygame.display.flip()
#设置一个帧频
clock.tick(20)
(原谅我没见过Linux)单纯python而已py还可以写这玩意??
我一个学了半年Python的蒟蒻还没见过(当然,我已经改py为c++)这是
Pygame
好吧我学了4年pythono
Linux???