python实现双人贪吃蛇小游戏

小编今天要给大家分享的是双人贪吃蛇,大家可以和自己的兄弟,姐妹,爸爸,妈妈等一起玩哟!我先介绍一下游戏:

运行游戏,进入初始界面,按下空格键。

玩家(1):w,a,s,d

玩家(2):↑,←,↓,→

玩家要争夺7个实物,直到吃完为止

游戏结束。

下面是小编写的代码:

import math
import random
import pygame
from pygame.locals import *

running = False
playing = False
screen = None
timer = None
snk1 = None
snk2 = None
foods = None
remainFoods = 7
radiusFood = 8

'''
链表节点
'''
class Node:
    def __init__(self, data, prev = None, next = None):
        self.data = data
        self.prev = prev
        self.next = next

    def insert_front(self, node):
        if self.prev:
            node.prev = self.prev
            self.prev.next = node
            self.prev = node
            node.next = self
        else:
            self.prev = node
            node.next = self
        return node

    def insert_back(self, node):
        if self.next:
            node.next = self.next
            self.next.prev = node
            self.next = node
            node.prev = self
        else:
            self.next = node
            node.prev = self
        return node

    def remove(self):
        if self.next:
            self.next.prev = self.prev
        if self.prev:
            self.prev.next = self.next

'''
蛇
'''
class Snack:

    def __init__(self, surface, color, start_pos, end_pos, face):
        self.color = color
        self.surface = surface
        self.head = Node(start_pos)
        self.tail = Node(end_pos)
        self.head.insert_back(self.tail)
        self.length = self.distanceBetween(start_pos, end_pos)
        self.face = face
        self.speed = 120
        self.eat = 0
        self.grow = 0
        self.mapAngle = [
            [0, math.pi * 3 / 2, math.pi / 2],
            [0, math.pi * 7 / 4, math.pi / 4],
            [math.pi, math.pi * 5 / 4, math.pi * 3 / 4]
        ]

    '''坐标取整'''
    def intPos(self, pos):
        return (int(pos[0]), int(pos[1]))

    '''坐标转角度'''
    def pos2Angle(self, pos):
        return self.mapAngle[pos[0]][pos[1]]

    '''极坐标位移'''
    def polarPos(self, pos, angle, dis):
        xx = pos[0] + dis * math.cos(angle)
        yy = pos[1] + dis * math.sin(angle)
        return (xx, yy)

    '''计算两点间距离'''
    def distanceBetween(self, pos1, pos2):
        dx = pos2[0] - pos1[0]
        dy = pos2[1] - pos1[1]
        return math.sqrt(dx*dx + dy*dy)

    '''计算两点间角度'''
    def angleBetween(self, pos1, pos2):
        dx = pos2[0] - pos1[0]
        dy = pos2[1] - pos1[1]
        return math.atan2(dy, dx)

    '''改变面向'''
    def changeFace(self, newFace):
        if newFace[0] == 0 and newFace[1] == 0:
            return
        if newFace == self.face:
            return
        xx = self.face[0] + newFace[0]
        yy = self.face[1] + newFace[1]
        if xx == 0 and yy == 0:
            return
        self.face = newFace
        self.head = self.head.insert_front(Node(self.head.data))

    '''吃到食物'''
    def eatFood(self, grow):
        self.grow = grow
        self.eat += 1

    '''绘制蛇身'''
    def draw(self):
        node = self.head
        pygame.draw.circle(self.surface, self.color, self.intPos(node.data), 6, 6)
        while node:
            n2 = node.next
            if not n2:
                break
            pygame.draw.line(self.surface, self.color, self.intPos(node.data), self.intPos(n2.data), 6)
            node = node.next

    '''每帧移动'''
    def walk(self, delta):
        dis = self.speed * delta / 1000
        self.head.data = self.polarPos(self.head.data, self.pos2Angle(self.face), dis)
        if self.grow >= dis:
            self.grow -= dis
        else:
            dis -= self.grow
            self.grow = 0
            self.cutTail(dis)

    '''收缩尾巴'''
    def cutTail(self, length):
        node = self.tail
        while length > 0:
            n2 = node.prev
            dis = self.distanceBetween(n2.data, node.data)
            angle = self.angleBetween(node.data, n2.data)
            if dis > length:
                node.data = self.polarPos(node.data, angle, length)
                length = 0
            else:
                self.tail = node.prev
                node.remove()
                length -= dis

            node = node.prev

'''屏幕指定位置绘制文字'''
def printText(surface, str, pos, size = 24, color = (255, 255, 255)):
    global screen
    font = pygame.font.SysFont("microsoftyaheimicrosoftyaheiui", size)
    text = font.render(str, True, color)
    w = text.get_width()
    h = text.get_height()
    surface.blit(text, (pos[0] - w / 2, pos[1] - h / 2))

'''添加食物'''
def addFood():
    global screen, snk1, snk2, foods, remainFoods
    if remainFoods <= 0:
        return
    w = screen.get_width()
    h = screen.get_height()
    while True:
        posX = random.randint(5, w - 5)
        posY = random.randint(5, h - 5)
        color = tuple(screen.get_at((posX, posY)))
        if color != snk1.color and color != snk2.color:
            break
    remainFoods -= 1
    if not foods:
        foods = Node((posX, posY))
    else:
        foods = foods.insert_front(Node((posX, posY)))

'''删除食物'''
def removeFood(node):
    global foods
    if node == foods:
        foods = foods.next
    else:
        node.remove()

'''检测吃到食物'''
def checkEatFood():
    global foods, radiusFood, snk1, snk2
    node = foods
    while node:
        if snk1.distanceBetween(snk1.head.data, node.data) < (radiusFood + 4):
            snk1.eatFood(50)
            removeFood(node)
            addFood()
            break
        elif snk2.distanceBetween(snk2.head.data, node.data) < (radiusFood + 4):
            snk2.eatFood(50)
            removeFood(node)
            addFood()
            break
        else:
            node = node.next

'''游戏初始界面'''
def logo():
    global screen, remainFoods
    w = screen.get_width()
    h = screen.get_height()
    printText(screen, "Snack V1.0", (w / 2, h / 3), 48)
    printText(screen, "任意键继续", (w / 2, h / 2), 24, (55, 255, 55))
    printText(screen, str(remainFoods) + "个食物,抢完即止", (w / 2, h * 2 / 3), 32)

def quit():
    pygame.font.quit()

'''检测游戏结束'''
def checkGameOver():
    global remainFoods, snk1, snk2, foods, playing, screen
    if remainFoods == 0 and foods == None:
        playing = False
        screen.fill((0,0,0))
        w = screen.get_width()
        h = screen.get_height()
        if snk1.eat > snk2.eat:
            printText(screen, "玩家1 胜利", (w / 2, h / 2), 48)
        elif snk1.eat < snk2.eat:
            printText(screen, "玩家2 胜利", (w / 2, h / 2), 48)
        else:
            printText(screen, "平局", (w / 2, h / 2), 48)

'''键盘按键转换成面向角度'''
def cmd():
    global snk1, snk2
    keys = pygame.key.get_pressed()
    x1 = x2 = y1 = y2 = 0
    if keys[pygame.K_RIGHT]:
        x2+=1
    if keys[pygame.K_LEFT]:
        x2-=1
    if keys[pygame.K_UP]:
        y2+=1
    if keys[pygame.K_DOWN]:
        y2-=1
    if keys[pygame.K_d]:
        x1+=1
    if keys[pygame.K_a]:
        x1-=1
    if keys[pygame.K_w]:
        y1+=1
    if keys[pygame.K_s]:
        y1-=1
    snk1.changeFace((x1, y1))
    snk2.changeFace((x2, y2))

'''游戏每帧更新'''
def play(delta):
    global playing, snk1, snk2
    if not playing:
        return
    cmd()
    snk1.walk(delta)
    snk2.walk(delta)
    checkEatFood()
    checkGameOver()

'''绘制'''
def draw():
    global snk1, snk2, playing, screen, radiusFood, remainFoods
    if not playing:
        return
    screen.fill((0,0,0))
    snk1.draw()
    snk2.draw()
    node = foods
    while node:
        color = (255, 255, 255)
        if remainFoods == 0:
            color = (255, 0, 0)
        pygame.draw.circle(screen, color, node.data, radiusFood, radiusFood // 2 + 1)
        node = node.next

def start(width = 800, height = 600, fps = 60):
    global running, screen, timer, playing, snk1, snk2
    pygame.init()
    pygame.font.init()
    font = pygame.font.SysFont("microsoftyaheimicrosoftyaheiui", 20)
    pygame.display.set_caption("Snack V1.0")
    screen = pygame.display.set_mode((width, height))

    logo()
    snk1 = Snack(screen, (0, 150, 200), (100, 100), (0, 100), (1, 0))
    snk2 = Snack(screen, (255, 100, 0), (width * 5 // 6, height // 2), (width * 5 // 6 + 100, height // 2), (-1, 0))
    for i in range(3):
        addFood()

    timer = pygame.time.Clock()
    running = True
    while running:
        delta = timer.tick(fps)
        play(delta)
        draw()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and playing == False:
                    screen.fill((0,0,0))
                    playing = True

        pygame.display.flip()

if __name__ == "__main__":
    start()
    quit()

以上就是双人贪吃蛇的代码啦!

教大家pygame的安装方式

在终端输入

pip install pyame,然后回车键进行安装

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • python贪吃蛇游戏代码

    本文实例为大家分享了python贪吃蛇游戏的具体代码,供大家参考,具体内容如下 贪吃蛇游戏截图: 首先安装pygame,可以使用pip安装pygame: pip install pygame 运行以下代码即可: #!/usr/bin/env python import pygame,sys,time,random from pygame.locals import * # 定义颜色变量 redColour = pygame.Color(255,0,0) blackColour = pygame.

  • python实现贪吃蛇小游戏

    关于编写游戏,是博主非常向往的东西(博主喜爱游戏),编写游戏得一步一步的走!今天我简单的编写一下非常经典的游戏贪吃蛇!!!! 效果图: 首先引入pygame模块 pip install pygame 关于编写贪吃蛇有如下几个步骤!依次思考 1.设置背景大小,即游戏框大小,---像素(px) 2.设置颜色,蛇的颜色,背景颜色,豆子的颜色 #pygame游戏库,sys操控python运行的环境 import pygame,sys,random #这个模块包含所有pygame所使用的常亮 from p

  • 使用Python写一个贪吃蛇游戏实例代码

    我在程序中加入了分数显示,三种特殊食物,将贪吃蛇的游戏逻辑写到了SnakeGame的类中,而不是在Snake类中. 特殊食物: 1.绿色:普通,吃了增加体型 2.红色:吃了减少体型 3.金色:吃了回到最初体型 4.变色食物:吃了会根据食物颜色改变蛇的颜色 #coding=UTF-8 from Tkinter import * from random import randint import tkMessageBox class Grid(object): def __init__(self,

  • Python 实现 贪吃蛇大作战 代码分享

    感觉游戏审核新政实施后,国内手游市场略冷清,是不是各家的新游戏都在排队等审核.媒体们除了之前竞相追捧<Pokemon Go>热闹了一把,似乎也听不到什么声音了.直到最近几天,突然听见好几人都提到同一个游戏,网上还有人表示朋友圈被它刷屏了.(不过现在微信已经悍然屏蔽了它的分享) 这个游戏就是现在iOS免费榜排名第一的<贪吃蛇大作战>.一个简单到不行的游戏,也不知道怎么就火了.反正一款游戏火了,各路媒体.专家总能说出种种套路来,所以我就不发表意见了.不过这实在是一个挺好实现的游戏,于是

  • python实现贪吃蛇游戏

    本文实例为大家分享了python实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下 本文稍作改动,修复一些bug,原文链接:python实现贪吃蛇游戏 #!/usr/bin/env python #__*__ coding: utf-8 __*__ import pygame,sys,time,random from pygame.locals import * redColour = pygame.Color(255,0,0) blackColour = pygame.Color(0,0,0)

  • 教你一步步利用python实现贪吃蛇游戏

    0 引言 前几天,星球有人提到贪吃蛇,一下子就勾起了我的兴趣,毕竟在那个Nokia称霸的年代,这款游戏可是经典中的经典啊!而用Python(蛇)玩Snake(贪吃蛇),那再合适不过了

  • Python写的贪吃蛇游戏例子

    第一次用Python写这种比较实用且好玩的东西,权当练手吧 游戏说明: * P键控制"暂停/开始"* 方向键控制贪吃蛇的方向 源代码如下: 复制代码 代码如下: from Tkinter import *import tkMessageBox,sysfrom random import randint class Grid(object):    def __init__(self,master=None,window_width=800,window_height=600,grid_

  • 利用python实现简易版的贪吃蛇游戏(面向python小白)

    引言 作为python 小白,总是觉得自己要做好百分之二百的准备,才能开始写程序.以至于常常整天在那看各种语法教程,学了几个月还是只会print('hello world'). 这样做效率太低,正确的做法,是到身边找问题,然后编程实现.比如说,我学了高等数学,我是不是应该考虑下如何去用编程实现求导或者积分操作,如果想不出怎么办,是不是应该 baidu 一下,别人是如何实现数值积分或是符号积分的.我们每天买东西都要用到加减甚至乘除,那么我是否能编写个简单的计算器,如果命令行太丑的话,我是否能够快速

  • python实现贪吃蛇游戏源码

    本文实例为大家分享了python实现贪吃蛇的具体代码,供大家参考,具体内容如下 import pygame import sys import random SCREEN_X=600 SCREEN_Y=600 class Snake(object): def __init__(self): self.direction=pygame.K_RIGHT self.body = [] for i in range(5): self.addnode() def addnode(self): left,

  • Python贪吃蛇游戏编写代码

    最近在学Python,想做点什么来练练手,命令行的贪吃蛇一般是C的练手项目,但是一时之间找不到别的,就先做个贪吃蛇来练练简单的语法. 由于Python监听键盘很麻烦,没有C语言的kbhit(),所以这条贪吃蛇不会自己动,运行效果如下: 要求:用#表示边框,用*表示食物,o表示蛇的身体,O表示蛇头,使用wsad来移动 Python版本:3.6.1 系统环境:Win10 类: board:棋盘,也就是游戏区域 snake:贪吃蛇,通过记录身体每个点来记录蛇的状态 game:游戏类 本来还想要个foo

随机推荐