0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
会员中心
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

Python版警察抓小偷游戏源代码

汽车电子技术 来源:Python代码大全 作者: Python代码狂人 2023-02-24 09:56 次阅读

Python版警察抓小偷游戏源代码,有多个难度级别,直接运行game.py,输入难度级别(1-13)。不同的难度等级对应不同的图形。

图片

game.py

""" Header files to initialize the game """
import pygame
import gameGraph
import os
from tkinter import messagebox
from tkinter import *
import platform
import BFS
import random
import cop_robber_algorithm


currentOS = platform.system()


""" GAME DRIVER CODE """
print(f"Welcome to Cops and Robbers!")
level = input("Please enter the level (1 - 13): ")


while int(level) > 13 or int(level) < 1:
    print(f"Invalid Input!")
    level = input("Please enter the level (1 - 13): ")


graphFile = open("data/level" + level + ".txt", "r")
fileData = graphFile.readlines()
totalVertices, totalEdges = map(int, fileData[0].split())
graph = gameGraph.Graph(totalVertices, totalEdges)
graph.acceptGraph(fileData)
gameMatrix = graph.returnDirectedAdjacencyMatrix()
algoMatrix = graph.returnUndirectedAdjacencyMatrix()




def checkLink(nodeA, nodeB):
    if algoMatrix[nodeA][nodeB] == 1:
        return True
    Tk().wm_withdraw()  # to hide the main window
    messagebox.showinfo('Node', 'Node: ' + str(nodeA) + ' is not connected to the current Robber Node')
    return False




pygame.init()  # Initialize pygame module


""" Optimizing screen resolution factor on the basis of operating system """
if currentOS == "Windows":
    factor = 0.8
elif currentOS == "Linux":
    factor = 1
elif currentOS == "Darwin":
    factor = 0.8




def nodeClicked(node):
    Tk().wm_withdraw()  # to hide the main window
    messagebox.showinfo('Next Node', 'You have selected Node: ' + str(node))




""" Game Window Attributes """
screenSize = (int(1500 * factor), int(1000 * factor))
screen = pygame.display.set_mode(screenSize)
pygame.display.set_caption("Cops and Robbers")
screen.fill([255, 255, 255])


""" Sprite Attributes """


# GRAPH ATTRIBUTES #
nodeVector = [pygame.sprite.Sprite() for i in range(totalVertices)]
counter = 0


# ACCEPT GRAPH FROM FILE #
locationVector = []
file = open("data/nodePos" + level + ".txt", "r")
lines = file.readlines()
for line in lines:
    x, y = map(int, line.split())
    x = int(x * factor)
    y = int(y * factor)
    locationVector.append((x, y))


for node in nodeVector:
    node.image = pygame.transform.scale(pygame.image.load("sprites/node.png").convert_alpha(),
                                        (int(75 * factor), int(75 * factor)))
    node.rect = node.image.get_rect(center=locationVector[counter])
    screen.blit(node.image, node.rect)
    counter = counter + 1


# COP ATTRIBUTES #
copNode = 0
cop = pygame.sprite.Sprite()
cop.image = pygame.transform.scale(pygame.image.load("sprites/cop.png").convert_alpha(),
                                   (int(45 * factor), int(45 * factor)))


################
game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, "img")


# ROBBER ATTRIBUTES #
robberNode = 1
robber = pygame.sprite.Sprite()
robber.image = pygame.transform.scale(pygame.image.load("sprites/robber.png").convert_alpha(),
                                      (int(45 * factor), int(45 * factor)))


# DRAW EDGES #
for i in range(totalVertices):
    for j in range(totalVertices):
        if gameMatrix[i][j] == 1 and i != j:
            pygame.draw.line(screen, (0, 0, 0), nodeVector[i].rect.center, nodeVector[j].rect.center, int(5 * factor))


valCorrect = int(22 * factor)
turn = 0




def gameplay(gameRunning):
    """ Function that controls the essential initial components of the game """
    global robberNode, copNode, turn
    while gameRunning:


        """ UPDATE POSITIONS OF COP AND ROBBER SPRITE AT EVERY STEP """
        screen.blit(robber.image,
                    (locationVector[robberNode][0] - valCorrect, locationVector[robberNode][1] - valCorrect))
        screen.blit(cop.image, (locationVector[copNode][0] - valCorrect, locationVector[copNode][1] - valCorrect))
        pygame.display.flip()


        """ HANDLE USER ACTION """
        for userAction in pygame.event.get():
            """ QUIT IF THE EXIT CROSS IS CLICKED """
            if userAction.type == pygame.QUIT:
                gameRunning = False


            """ HANDLING MOUSE BUTTON CLICKS """
            if pygame.mouse.get_pressed()[0]:
                for i in range(totalVertices):
                    if nodeVector[i].rect.collidepoint(pygame.mouse.get_pos()):
                        nodeClicked(i)
                        if checkLink(i, robberNode):
                            """ MOVING THE ROBBER TO A NEW NODE """
                            pygame.draw.rect(screen, (255, 0, 0), (
                                (
                                locationVector[robberNode][0] - valCorrect, locationVector[robberNode][1] - valCorrect),
                                (int(45 * factor), int(45 * factor))))
                            robberNode = i
                            screen.blit(robber.image, (
                                locationVector[robberNode][0] - valCorrect, locationVector[robberNode][1] - valCorrect))
                            pygame.display.flip()


                            """ CHECK IF THE TWO SPRITES HAVE HIT THE SAME NODE """
                            if robberNode == copNode:
                                Tk().wm_withdraw()  # to hide the main window
                                messagebox.showinfo('Uh-Oh!', 'Looks like you were caught')
                                gameRunning = False
                                break


                            """ MOVING THE COP TO A NEW NODE """
                            pygame.draw.rect(screen, (0, 255, 0), (
                                (locationVector[copNode][0] - valCorrect, locationVector[copNode][1] - valCorrect),
                                (int(45 * factor), int(45 * factor))))
                            copNode = BFS.BFS(graph, copNode, robberNode)
                            screen.blit(cop.image, (
                                locationVector[copNode][0] - valCorrect, locationVector[copNode][1] - valCorrect))
                            pygame.display.flip()
                            turn = turn + 1


                            """ CHECK IF THE TWO SPRITES HAVE HIT THE SAME NODE """
                            if robberNode == copNode:
                                Tk().wm_withdraw()  # to hide the main window
                                messagebox.showinfo('Uh-Oh!', 'Looks like you were caught')
                                return "Lost"
                            elif turn > totalEdges + 1:
                                Tk().wm_withdraw()  # to hide the main window
                                messagebox.showinfo('Woooohooooo!', 'Looks like you evaded the cops for long enough!')
                                return "Won"




runStatus = True
robberNode = 1
gameResult = gameplay(runStatus)
cop_robber_algorithm.cop_robber_preliminary(algoMatrix, totalVertices)
if cop_robber_algorithm.cop_robber_final(algoMatrix, totalVertices):
    graphType = "Robber Win"
else:
    graphType = "Cop Win"


Tk().wm_withdraw()
messagebox.showinfo(gameResult,
                    "Level: " + level + "\\n" + "Turns Survived: " + str(turn) + "\\n" + "Graph Type:" + graphType)

完整程序代码下载地址:

https://download.csdn.net/download/weixin_42756970/86813741

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 图形
    +关注

    关注

    0

    文章

    71

    浏览量

    19263
  • 源代码
    +关注

    关注

    96

    文章

    2944

    浏览量

    66638
  • python
    +关注

    关注

    55

    文章

    4777

    浏览量

    84410
收藏 人收藏

    评论

    相关推荐

    java编写的扫雷游戏源代码

    求一个java编写的扫雷游戏源代码,谢谢!!!
    发表于 07-15 15:20

    HFC5209A“不好了,有人偷东西,快来抓小偷”语言集成电

    HFC5209A“不好了,有人偷东西,快来抓小偷”语言集成电路图
    发表于 03-31 16:30 1256次阅读
    HFC5209A“不好了,有人偷东西,快来<b class='flag-5'>抓小偷</b>”语言集成电

    贪吃蛇游戏java源代码

    贪吃蛇游戏java源代码
    发表于 12-27 17:56 9次下载

    Python微服务开发的源代码合集免费下载

    本文档的主要内容详细介绍的是Python微服务开发的源代码合集免费下载。
    发表于 09-20 08:00 3次下载

    python的html基本结构及常见文本标签源代码免费下载

    本文档的主要内容详细介绍的是python的html基本结构及常见文本标签源代码免费下载。
    发表于 12-04 08:00 0次下载
    <b class='flag-5'>python</b>的html基本结构及常见文本标签<b class='flag-5'>源代码</b>免费下载

    Python深度学习2018的源代码合集免费下载

    本文档的主要内容详细介绍的是Python深度学习2018的源代码合集免费下载。
    发表于 01-16 10:25 69次下载

    python实现目标检测的源代码免费下载

    本文档的主要内容详细介绍的是python实现目标检测的源代码免费下载
    发表于 04-09 08:00 6次下载
    <b class='flag-5'>python</b>实现目标检测的<b class='flag-5'>源代码</b>免费下载

    python文件读取的源代码免费下载

    本文档的主要内容详细介绍的是python文件读取的源代码免费下载。
    发表于 08-07 17:14 20次下载
    <b class='flag-5'>python</b>文件读取的<b class='flag-5'>源代码</b>免费下载

    使用文件保存游戏python代码和资料说明

    本文档的主要内容详细介绍的是使用文件保存游戏python代码和资料说明免费下载。
    发表于 09-24 17:08 11次下载
    使用文件保存<b class='flag-5'>游戏</b>的<b class='flag-5'>python</b><b class='flag-5'>代码</b>和资料说明

    使用Python按行读文件的源代码免费下载

    本文档的主要内容详细介绍的是使用Python按行读文件的源代码免费下载。
    发表于 10-22 17:57 12次下载
    使用<b class='flag-5'>Python</b>按行读文件的<b class='flag-5'>源代码</b>免费下载

    基于LabVIEW的贪吃蛇游戏源代码

    基于LabVIEW的贪吃蛇游戏源代码
    发表于 04-22 09:27 74次下载

    Python版超市管理系统源代码

    Python版超市管理系统源代码,基于django+mysql安装步骤
    的头像 发表于 02-24 09:59 1607次阅读
    <b class='flag-5'>Python</b>版超市管理系统<b class='flag-5'>源代码</b>

    Python版蚊子大作战源代码

    Python灭蚊小游戏源代码,超解压的灭蚊小游戏,通过消灭蚊子赚钱,屏幕里的蚊子不被消灭就会被蚊子吸血,通过商店购买血包、血瓶、血桶、回血针来使自己回血,也可以在商店购买不同的灭蚊工具
    的头像 发表于 02-24 10:29 1051次阅读
    <b class='flag-5'>Python</b>版蚊子大作战<b class='flag-5'>源代码</b>

    Python编程实战(源代码)

    [源代码]Python编程实战 妙趣横生的项目之旅
    发表于 06-06 17:49 3次下载

    [源代码]Python算法详解

    [源代码]Python算法详解[源代码]Python算法详解
    发表于 06-06 17:50 0次下载