प्रोग्रामिंग पीएसी मैन


31

प्रोग्राममैन 'पीएसी-मैन

सेटिंग

आप पीएसी-मैन के रूप में खेलते हैं। आप भूत से बचने के दौरान किसी और से पहले छर्रों, फलों और बिजली छर्रों को इकट्ठा करना चाहते हैं।

नियम

  1. हर वैध पीएसी मैन एक भूलभुलैया में होगा। 10 खेलों के बाद सबसे अधिक संचयी स्कोर वाला खिलाड़ी जीत जाएगा।
  2. एक गेम खत्म हो गया है जब सभी पीएसी-मेन मर चुके हैं, सभी छर्रों चले गए हैं, या 500 मोड़ बीत चुके हैं
  3. यदि एक पीएसी मैन मर जाता है, तो वह भूत के रूप में खेलना जारी रखता है
  4. एक बिजली की गोली खाने से आप 10 मोड़ के लिए अजेय हो जाएंगे, और आपको भूत खाने की अनुमति देगा
  5. एक घोस्ट खाने से भूत को एक यादृच्छिक स्थान पर टेलीपोर्ट किया जाएगा
  6. भूत पीक-मेन के अलावा कुछ भी नहीं खा सकते हैं, और कोई अंक नहीं मिलता है
  7. निम्नलिखित वस्तुओं को पीएसी मैन के रूप में खाने से आपको निम्नलिखित बिंदु मिलेंगे:
    1. गोली: १०
    2. पावर पेलेट: 50
    3. फल: १००
    4. भूत: २००

उलझन

यदि n पीएसी-मेन हैं, तो प्राइम के एल्गोरिथ्म का उपयोग करके आकार का एक भूलभुलैया उत्पन्न sqrt(n)*10किया sqrt(n)*10जाएगा (इसके कम नदी कारक के कारण) , फिर पूरी तरह से लट में, पहले से मौजूद मृत सिरों को वरीयता देते हुए। इसके अलावा, इस ब्रेडिंग को किनारों पर किया जा सकता है, ताकि ऊपर से नीचे और बाएं से दाएं कुछ रास्ते हों।

वहां होगा:

  1. 2n भूत
  2. 4n बिजली छर्रों
  3. 2n फल
  4. n पीएसी-पुरुष उन स्थानों में जहां जुड़े हुए पड़ोसी वर्ग खाली हैं।
  5. शेष सभी खाली स्थानों को छर्रों से भर दिया जाएगा

इसलिए, 10 खिलाड़ियों के साथ एक प्रारंभिक नक्शा कुछ इस तरह दिखाई देगा (भूत = हरा, पेलेट = एक्वा, फल = लाल, पीएसी-मैन = पीला):

भूल भुलैया

इनपुट आउटपुट

खेल की शुरुआत में , आपको पात्रों की एक एकल पंक्ति दी जाएगी, जो नक्शे के हर वर्ग में दीवारों का प्रतिनिधित्व करती है। प्रत्येक वर्ग के लिए, ऊपर बाईं ओर से शुरू होकर, दाईं ओर बढ़ते हुए, और अगली पंक्ति में लपेटते हुए, आपको दीवार स्थिति का प्रतिनिधित्व करने वाला एक हेक्स अंक दिया जाएगा:

0: No walls
1: North wall
2: East wall
3: East & North wall
4: South wall
5: South & North wall
6: South & East wall
7: Won't occur
8: West wall
9: West & North wall
A: West & East wall
B: Won't occur
C: West & South wall
D: Won't occur
E: Won't occur
F: Won't occur

सीधे शब्दों में कहें, उत्तर = 1, पूर्व = 2, दक्षिण = 4, और पश्चिम = 8, एक साथ जोड़े।

फिर, प्रत्येक मोड़ पर , आपको अपनी वर्तमान स्थिति और आपके दर्शन की पंक्ति में आइटम दिए जाएंगे (यदि आप एक पीएसी-मैन हैं। सभी भूत अपने रिश्तेदार की स्थिति से -5 से +5 तक सभी वर्गों को प्राप्त करते हैं)। आपकी दृष्टि की दिशा उस दिशा पर आधारित होगी, जिस पर आपने अंतिम यात्रा की थी। यदि आपने उत्तर की यात्रा की है, तो आपको सभी वर्गों को सीधे उत्तर, पूर्व और पश्चिम में दिया जाएगा, जब तक कि कोई दीवार आपके दृश्य को नहीं काटती है, साथ ही एक वर्ग उत्तर-पश्चिम और उत्तर-पूर्व को काटती है, यदि कोई दीवार आपके दृश्य को नहीं काटती है। यदि आप स्थानांतरित नहीं करने का चयन करते हैं, तो आपको सभी 8 दिशाओं में वर्ग दिए जाएंगे।

दृश्य के लिए, Iअदृश्य का Vअर्थ है, दृश्यमान का अर्थ है, Pपीएसी-मैन (उत्तर-पूर्व का सामना करते हुए पीएसी-मैन):

|I I|V|I|
|I V|V V|
|V V P|I|
|I I|I|I|

प्रत्येक वर्ग एक समन्वय द्वारा दिया जाएगा, और फिर यह सामग्री है। यह सामग्री निम्नलिखित वर्णों द्वारा दर्शाई गई है:

  1. P: 1 या अधिक पीएसी मैन
  2. G: 1 या उससे अधिक भूत
  3. o: गोली
  4. O: बिजली की गोली
  5. F: फल का टुकड़ा
  6. X: कुछ भी तो नहीं

अगर किसी चौक पर भूत और कुछ है तो Gवापस कर दिया जाएगा।

इसलिए, यदि आप वर्ग पर थे, तो आप 23,70उत्तर की ओर चले गए, आपके ऊपर का वर्ग एक मृत अंत है और इसमें एक बिजली की गोली है, और आपके दोनों तरफ दीवारें हैं, आपका इनपुट होगा:

23,70X 22,70O

अपने वर्तमान वर्ग पर, यह दिखाएगा कि Gक्या आप भूत हैं, Pयदि आपके वर्ग में एक और पीएसी मैन है, अन्यथा एX

फिर आप STDOUT के माध्यम से निम्नलिखित आइटम वापस करेंगे:

एक एकल वर्ण जो एक दिशा ( North, East, South, West, or XStay) का प्रतिनिधित्व करता है ।

एक दिशा में गुजरने से पहले, आप किसी भी निर्देशांक में पास हो सकते हैं x,y, और उस वर्ग की दीवारों को वापस पारित किया जाएगा (जैसा कि नीचे वर्णित है)

जब तक Qएसटीडीआईएन के माध्यम से इसे पारित नहीं किया जाता है तब तक कार्यक्रम को लगातार चलना चाहिए । प्रत्येक खेल के लिए कार्यक्रमों को फिर से शुरू किया जाएगा।

एसटीडीआईएन (अन्य पीएसी-मेन डेटा या होस्ट प्रोग्राम द्वारा रखे गए डेटा सहित) से बाहर की अन्य जानकारी तक पहुँचने की अनुमति नहीं है।

1000 एमएस के भीतर एक कदम वापस करने में विफलता कार्यक्रम को समाप्त कर देगी (मेरी काफी सभ्य Win8 मशीन पर चल रही है)। यह दिए जाने पर प्रारंभिक भूलभुलैया लेआउट को संसाधित करने के लिए आपको 2 सेकंड दिए जाएंगे

होस्ट पायथन में लिखा जाएगा, और अपने बॉट का परीक्षण करने के लिए कोड आगामी है।

अपवाद स्वरूप मामले

  • यदि कई पीएसी-मेन एक ही स्थान पर समाप्त होते हैं, तो न तो वर्तमान वर्ग की सामग्री प्राप्त करें, जब तक कि उनमें से 1 अजेय न हो, उस स्थिति में, अजेय पीएसी-मैन को टैबलेट प्राप्त होगा।
  • एक भूत द्वारा खाया गया पै-मैन कहीं और टेलीपोर्ट नहीं किया जाएगा। यदि दो पीएसी-पुरुष एक वर्ग पर हैं, और एक अजेय है, तो भूत को टेलीपोर्ट किया जाएगा।
  • भूत के रूप में टेलीपोर्ट किए जाने से आप 1 मोड़ के लिए आगे बढ़ते हैं। भूत के रूप में खेलते समय, आप बस अपनी बारी को छोड़ देंगे
  • एक दीवार के माध्यम से स्थानांतरित करने का प्रयास "स्टे" के रूप में व्याख्या किया जाएगा
  • प्रारंभिक भूतों में से प्रत्येक को 4 व्यक्तित्व लक्षणों में से एक प्राप्त होगा, जैसा कि यहां वर्णित है , निम्न संशोधन के साथ:

    1. वर्णित बगों को डुप्लिकेट नहीं किया जाएगा
    2. वे सभी शुरू से ही सक्रिय रहेंगे
    3. वे केवल उस खिलाड़ी के प्रति संवेदनशील होते हैं, जिसने गोली खा ली है
    4. वे अनिश्चित काल के लिए स्कैच से स्विच करने के लिए स्विच करेंगे, प्रत्येक में स्विच से पहले निश्चित संख्या में मोड़ होंगे
    5. पीछा करने के लिए स्विच करने पर, वे पीछा करने के लिए निकटतम पीएसी मैन पाएंगे, और अपने पीछा की अवधि के लिए उस पीएसी मैन का पीछा करेंगे। (यदि निकटता के लिए एक टाई है, तो पीएसी-मैन को छद्म रूप से चुना जाएगा)
    6. ब्लिंक की गति तेज नहीं होगी
    7. Inky पीछा करने के लिए स्विच करने के बाद अपनी गणना के आधार पर निकटतम भूत को चुन लेगा।
    8. क्लाइड को सभी खिलाड़ी 8 वर्ग दूर मिलेंगे, फिर सबसे दूर के खिलाड़ी का अनुसरण करेंगे।
    9. क्लाइड को छोड़कर सभी भूत 5 वर्ग से अधिक दूर के खिलाड़ी को निशाना नहीं बनाएंगे

मैं एक मानक भाषा या .exe (कोड के साथ) से संकलन योग्य कोड स्वीकार करूंगा।

प्रोग्रामिंग टिप्स

आप मेरे नियंत्रक के साथ हो सकते हैं। आपको प्रोग्राम के समान निर्देशिका में / bots / your_bot_name / फ़ोल्डर डालना होगा। फ़ोल्डर के भीतर, आपको अपने प्रोग्राम (एक्स:) python my_bot.py, और अपने बॉट को निष्पादित करने के लिए कमांड युक्त कमांड जोड़ने की जरूरत है ।

नियंत्रक कोड Github (Python कोड) पर है, यदि आपको ग्राफिक्स चाहिए तो Pygame की आवश्यकता है।) विंडोज़ और लिन पर परीक्षण किया गया।

स्कोर

घोस्टबस्टर: 72,840 अंक

पथरी: 54,570 अंक

शॉर्टसाइटेड: 50,820 अंक

परिहार: 23,580 अंक

भौतिक विज्ञानी: 18,330 अंक

रैंडमवॉक: 7,760 अंक

डंबपैक: 4,880 अंक


9
+1। यह पहली बार है जब मैं "पैकमेन" शब्द देखता हूं
जस्टफुल

5
एक मजेदार चुनौती की तरह लग रहा है! वैसे: (1) वे वास्तव में "एनर्जाइज़र" कहलाते हैं, न कि "पावर पेललेट्स"। (2) पीएसी मैन में "एम" को पूंजीकृत किया गया है, और इसे "पीएसी मैन" के रूप में हाइफ़न किया गया है न कि "पैकमैन" या "पैकमैन" के रूप में। यहाँ पीएसी-मैन जानकारी के लिए एक बढ़िया संसाधन है: home.comcast.net/~jpittman2/pacman/pacmandossier.html
टोड लेहमैन

2
इस चुनौती पर काम करने वाले किसी को भी कोडगुल्फ के लिए चैट रूम में शामिल होना चाहिए। chat.stackexchange.com/rooms/240/the-nineteenth-byte
Spur

1
ठीक है। नियंत्रक अब विंडोज़ और लिनक्स पर काम करता है, लेकिन अगर आपके बॉट ने प्रतिक्रिया नहीं दी है, तो विंडोज़ पर फ्रीज हो जाएगा।
नाथन मेरिल

1
मैं colorblind हूँ और भूत से PacMen को नहीं बता सकता, क्या हम रंग बदल सकते हैं?
19

जवाबों:


8

घोस्टबस्टर - पायथन

नक्शे पर एक यादृच्छिक स्थान प्राप्त करता है, सबसे अच्छा रास्ता खोजने के लिए ए * एल्गोरिथ्म का उपयोग करता है। एक बार जब यह अपने गंतव्य तक पहुंच जाता है, तो यह एक नया उठाएगा और जारी रखेगा। यह भूतों से बचने की कोशिश करेगा, लेकिन सीमित FOV के साथ, यह कभी-कभार उनके अंदर चलेगा। यह पहले से ही देखे गए स्थानों पर चलने से बचना होगा।

  • भूत के लिए जोड़ा गया तर्क। एक करीबी (<8) यादृच्छिक बिंदु को उठाता है और पैक्मेन के अलावा अन्य स्कोर की अवहेलना करता है
  • जोड़ा गया अजेयता तर्क
  • वर्गों के समायोजित बिंदु मान
  • बग (यदि वह बहुत अच्छा है और सभी छर्रों को खाता है, तो खेल किसी कारण से जम जाता है)

स्पार्स के कुछ कोड का उपयोग करता है, तर्क के लिए धन्यवाद।


विंडोज 7, पायथन टूल्स के साथ विजुअल स्टूडियो। लिनक्स बॉक्स पर काम करना चाहिए।

#!/usr/bin/env python

import os
import re
import sys
import math
import random

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # automatically flush stdout

P,G,o,O,F,X = 5,600,-10,-100,-100,10
PreviousSquarePenalty = 10

# read in the maze description
maze_desc = sys.stdin.readline().rstrip()
mazeSize = int(math.sqrt(len(maze_desc)))

North,East,South,West = range(4)
DIRECTIONS = ['N','E','S','W']
Euclidian,Manhattan,Chebyshev = range(3)

sign = lambda x: (1, -1)[x<0]
wrap = lambda v : v % mazeSize

class Node(object):

    def __init__(self, x, y, value):
        self.x, self.y = x,y
        self.wallValue = int(value, 16); #Base 16
        self.nodes = {}
        self.item = 'o' # Start as normal pellet

    def connect(self, otherNode, dir):    
        if dir not in self.nodes:
            self.nodes[dir] = otherNode       
            otherNode.nodes[(dir+2)%4] = self

    def distance(self, otherNode, meth = Manhattan):
        xd = abs(otherNode.x - self.x)        
        yd = abs(otherNode.y - self.y)
        xd = min(xd, mazeSize - xd)
        yd = min(yd, mazeSize - yd)
        if meth == Euclidian:
            return math.sqrt(xd * xd + yd * yd)       
        if meth == Manhattan:
            return xd + yd
        if meth == Chebyshev:      
            return max(xd, yd)

    def direction(self, otherNode):
        for key, value in self.nodes.iteritems():
            if value == otherNode:
                return DIRECTIONS[key]            
        return 'ERROR'

    def getScore(self):
        score = eval(self.item)
        for node in self.nodes.values():
            score += eval(node.item)
        return score

    def nearbyGhost(self):
        if self.item == 'G':
            return True
        for node in self.nodes.values():
            if node.item == 'G':
                return True
        return False

    def __hash__(self):  
        return  (391 + hash(self.x))*23 + hash(self.y)

    def __eq__(self, other):
        return (self.x, self.y) == (other.x, other.y)

    def __ne__(self, other):
        return (self.x, self.y) != (other.x, other.y)

    def __str__(self):
        return str(self.x)+","+str(self.y)

    def __repr__(self):
        return str(self.x)+","+str(self.y)

# Make all the nodes first
nodes = {}
i = 0
for y in range(mazeSize):
    for x in range(mazeSize):       
        nodes[x,y] = Node(x,y,maze_desc[i])  
        i+=1

# Connect all the nodes together to form the maze
for node in nodes.values():
    walls = node.wallValue
    x,y = node.x,node.y    
    if not walls&1:  
        node.connect(nodes[x,wrap(y-1)], North)
    if not walls&2:
        node.connect(nodes[wrap(x+1),y], East)
    if not walls&4:
        node.connect(nodes[x,wrap(y+1)], South)
    if not walls&8:
        node.connect(nodes[wrap(x-1),y], West)

toVisit = set(nodes.values())
currentNode = None
destinationNode = None
previousNode = None
testInvincibilty = False
invincibility = 0
isGhost = False
turns = 0

def aStar(startNode, endNode):
    openSet = set([startNode])
    closedSet = set()
    gScores = {startNode: 0}
    cameFrom = {}
    curNode = startNode  
    while openSet:
        minF = 100000000
        for node in openSet:
            g = gScores[node]
            h = node.distance(endNode)
            f = g+h
            if f < minF:
                minF = f
                curNode = node

        if curNode == endNode:
            path = []
            while curNode != startNode:
                path.insert(0, curNode)
                curNode = cameFrom[curNode]
            return path

        openSet.remove(curNode)
        closedSet.add(curNode)
        for node in curNode.nodes.values():
            if node in closedSet:
                continue
            g = gScores[curNode]
            if isGhost:
                g += 1
                if node.item == 'P':
                    g -= 10 # prefer PacMen
            else:
                s = node.getScore();
                if invincibility > 1:
                    g -= abs(s) # everything is tasty when invincible
                else:
                    g += s
                if previousNode and node == previousNode:
                    g += PreviousSquarePenalty # penalize previous square
            isBetter = False
            if node not in openSet:
                openSet.add(node)
                isBetter = True
            elif g < gScores[node]:
                isBetter = True
            if isBetter:
                gScores[node] = g
                cameFrom[node]=curNode

# regex to parse a line of input
input_re = re.compile('(?:([-\d]+),([-\d]+)([PGoOFX]?) ?)+')

while True:
    info = sys.stdin.readline().rstrip()
    if (not info) or (info == "Q"):
        break

    turns += 1

    # break a line of input up into a list of tuples (X,Y,contents)
    info = [input_re.match(item).groups() for item in info.split()]

    # update what we know about all the cells we can see
    for cell in info:
        nodes[int(cell[0]),int(cell[1])].item = cell[2]

    currentNode = nodes[int(info[0][0]),int(info[0][1])]    

    if turns == 1:
        print 'X'
        continue

    if not isGhost and currentNode.item == 'G':
        isGhost = True
        destinationNode = random.sample(nodes.values(), 1)[0]

    if isGhost:     
        while destinationNode == currentNode or currentNode.distance(destinationNode) > 8:
            destinationNode = random.sample(nodes.values(), 1)[0]
    else:     

        if invincibility > 0:
            invincibility -=  1

        if testInvincibilty:
            testInvincibilty = False
            if currentNode.item == 'X':
                invincibility += 10

        while not destinationNode or destinationNode == currentNode:
            destinationNode = random.sample(toVisit, 1)[0]

        if currentNode.item == 'X':
            toVisit.discard(currentNode)

    bestPath = aStar(currentNode, destinationNode)

    nextNode = bestPath[0]

    direction = currentNode.direction(nextNode)

    if not isGhost and nextNode.item == 'O':   
        testInvincibilty = True      

    previousNode = currentNode

    print direction

8

अदूरदर्शा

यह पीएसी आसन्न भूतों से बचती है जब तक कि वह उन्हें नहीं खा सकता है, आसन्न फल या छर्रों पर चलता है, और अंतिम उपाय के रूप में यादृच्छिक रूप से चलता है।

#!/usr/bin/env python

import os
import re
import sys
import math
import random

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # automatically flush stdout

# read in the maze description
maze_desc = sys.stdin.readline().rstrip()
maze_size = int(math.sqrt(len(maze_desc)))

# turn the maze description into an array of arrays
# [wall bitmask, item last seen in square]

def chunks(l, n):
    for i in xrange(0, len(l), n):
        yield l[i:i+n]
maze = []
for row in chunks(maze_desc, maze_size):
    maze.append([[int(c,16),'X'] for c in row])

# regex to parse a line of input
input_re = re.compile('(?:([-\d]+),([-\d]+)([PGoOFX]?) ?)+')

turn = 0
invincibility_over = 0
last_move = None

while True:
    info = sys.stdin.readline().rstrip()
    if (not info) or (info == "Q"):
        break

    # break a line of input up into a list of tuples (X,Y,contents)
    info = info.split()
    info = [input_re.match(item).groups() for item in info]

    # update what we know about all the cells we can see
    for cell in info:
        maze[int(cell[1])][int(cell[0])][1] = cell[2]

    # current location
    x = int(info[0][0])
    y = int(info[0][1])

    # which directions can we move from our current location?
    valid_directions = []
    # we might consider sitting still
    # valid_directions.append('X')
    walls = maze[y][x][0]
    if not walls&1:
        valid_directions.append('N')
    if not walls&2:
        valid_directions.append('E')
    if not walls&4:
        valid_directions.append('S')
    if not walls&8:
        valid_directions.append('W')

    # which direction has the highest value item?
    best_value = 0
    best_direction = 'X'
    for c in [(x,y-1,'N'),(x+1,y,'E'),(x,y+1,'S'),(x-1,y,'W')]:
        if c[2] in valid_directions:
            # am I a ghost?
            if maze[y][x][1] == 'G':
                if maze[c[1]%maze_size][c[0]%maze_size][1] == "P":
                    best_value = 999
                    best_direction = c[2]
            else:
                if maze[c[1]%maze_size][c[0]%maze_size][1] == 'F':
                    if best_value < 100:
                        best_value = 100
                        best_direction = c[2]
                elif maze[c[1]%maze_size][c[0]%maze_size][1] == 'O':
                    if best_value < 50:
                        best_value = 50
                        best_direction = c[2]
                elif maze[c[1]%maze_size][c[0]%maze_size][1] == 'o':
                    if best_value < 10:
                        best_value = 10
                        best_direction = c[2]
                elif maze[c[1]%maze_size][c[0]%maze_size][1] == 'G':
                    if turn < invincibility_over:
                        # eat a ghost!
                        if best_value < 200:
                            best_value = 200
                            best_direction = c[2]
                    else:
                        # avoid the ghost
                        valid_directions.remove(c[2])

    # don't turn around, wasteful and dangerous
    if last_move:
        reverse = ['N','E','S','W'][['S','W','N','E'].index(last_move)]
        if reverse in valid_directions:
            valid_directions.remove(reverse)

    if best_value == 50:
        invincibility_over = turn + 10      
    if best_direction != 'X':
        # move towards something worth points
        # sys.stderr.write("good\n")
        last_move = best_direction
    elif len(valid_directions)>0:
        # move at random, not into a wall
        # sys.stderr.write("valid\n")
        last_move = random.choice(valid_directions)
    else:
        # bad luck!
        # sys.stderr.write("bad\n")
        last_move = random.choice(['N','E','S','W'])
    print last_move

    turn += 1

6

avoider

एक भूत के रूप में सभी भूतों से बचें, और एक भूत होने पर सभी शांतियों से बचें। यदि संभव हो तो अपनी खुद की किसी भी तरह से बचने की कोशिश करता है, और यदि संभव हो तो 180 मोड़ से बचा जाता है।

#!/usr/bin/env python
import os
import re
import sys
import math
import random

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # automatically flush stdout

# read in the maze description
maze_desc = sys.stdin.readline().rstrip()
maze_size = int(math.sqrt(len(maze_desc)))

# turn the maze description into an array of arrays of numbers indicating wall positions

def chunks(l, n):
    for i in xrange(0, len(l), n):
        yield l[i:i+n]
maze = []
for row in chunks(maze_desc, maze_size):
    maze.append([[int(c,16),'X'] for c in row])

# regex to parse a line of input
input_re = re.compile('(?:([-\d]+),([-\d]+)([PGoOFX]?) ?)+')

last_moved = 'X'

while True:
    info = sys.stdin.readline().rstrip()
    if (not info) or (info == "Q"):
        break

    # break a line of input up into a list of tuples (X,Y,contents)
    info = info.split()
    info = [input_re.match(item).groups() for item in info]

    # location
    x = int(info[0][0])
    y = int(info[0][1])

    # update what we know about all the cells we can see
    for cell in info:
        maze[int(cell[1])][int(cell[0])][1] = cell[2]

    # which directions can we move from our current location?
    valid_directions = []
    walls = maze[y][x][0]
    if not walls&1: 
        valid_directions.append('N')
    if not walls&2:
        valid_directions.append('E')
    if not walls&4:
        valid_directions.append('S')
    if not walls&8:
        valid_directions.append('W')

    bad_directions = []
    for c in [(x,y-1,'N'),(x+1,y,'E'),(x,y+1,'S'),(x-1,y,'W')]:
        if c[2] in valid_directions:
            # am I a ghost?
            if maze[y][x][1] == 'G':
                # it's a pacman, run. interaction is always a risk.
                if maze[c[1]%maze_size][c[0]%maze_size][1] == "P":
                    valid_directions.remove(c[2])
                # another ghost? let me move away.
                elif maze[c[1]%maze_size][c[0]%maze_size][1] == "G":
                    bad_directions.append(c[2])
            else:
                # it's a ghost, run. ghosts are evil.
                if maze[c[1]%maze_size][c[0]%maze_size][1] == "G":
                    valid_directions.remove(c[2])
                # its another pacman, move away!
                elif maze[c[1]%maze_size][c[0]%maze_size][1] == "P":
                    bad_directions.append(c[2])

    # if possible to avoid normal contact, do so
    good_directions = list(set(valid_directions) - set(bad_directions))
    if len(good_directions) > 0:
        valid_directions = good_directions

    # if not the only option, remove going backwards from valid directions
    if len(valid_directions) > 1:
        if last_moved == 'N' and 'S' in valid_directions:
            valid_directions.remove('S')
        elif last_moved == 'S' and 'N' in valid_directions:
            valid_directions.remove('N')
        elif last_moved == 'W' and 'E' in valid_directions:
            valid_directions.remove('E')
        elif 'W' in valid_directions:
            valid_directions.remove('W')

    # if possible, continue in the same direction
    if last_moved in valid_directions:
        print last_moved
    # prefer turning left/right randomly instead of turning 180
    #   backwards has been removed from valid_directions if not
    #   the only option
    elif len(valid_directions) > 0:
        last_moved=random.choice(valid_directions)
        print last_moved
    # can't move, so stay put. desire to continue in original 
    #   direction remains.
    else:
        print 'X'

यह उत्तर एक त्रुटि फेंकता है। आपने x या y
नाथन मेरिल

फ़ाइल "avoider.py", पंक्ति 42, में <मॉड्यूल> भूलभुलैया [int (सेल [1])] [int (सेल [0])] [1] = सेल [2] टाइप करें: 'int' ऑब्जेक्ट का समर्थन नहीं करता है आइटम असाइनमेंट
नाथन मेरिल

valid_directions.remove ('W') ValueError: list.remove (x): x सूची में नहीं
नाथन मेरिल

@NathanMerrill को अब ठीक किया जाना चाहिए।
es1024

4

भौतिक विज्ञानी, हास्केल

भौतिक विज्ञानी पीएसी-मैन का मानना ​​है कि न्यूटन का सार्वभौमिक गुरुत्वाकर्षण का नियम उसे खेल जीतने में मदद कर सकता है। फिर वह इसे खेल के दौरान उसकी सभी अन्य वस्तुओं पर लागू करता है। चूंकि भौतिक विज्ञानी बूढ़ा है और बुरी याददाश्त है, वह केवल 5 राउंड में चीजों को याद रख सकता है। हुओली, बुरी स्मृति वास्तव में उसे बेहतर स्कोर करने में मदद करती है।

इस उत्तर में दो फ़ाइल हैं:

  • Main.hs, दिलचस्प हिस्सा शामिल है।
  • Pacman.hs, बस कुछ उबाऊ कोड संभाल प्रोटोकॉल। आप इसे अपने खुद के हैस्केल समाधान लिखने के लिए उपयोग कर सकते हैं। इसमें कोई AI कोड नहीं है।

ओह, रुको, हमारे पास एक Makefileभी है।

यहाँ वे आते हैं:

Main.hs

import Pacman
import Data.Complex
import Data.List
import Data.Function
import qualified Data.Map as Map
import Data.Maybe
import System.IO

data DebugInfo = DebugInfo {
  debugGrid :: Grid
, debugForce :: Force
, debugAction :: Action
} deriving (Show)

data Physicist = Physicist [(Int, Object)] (Maybe DebugInfo)

type Force = Complex Double


calcForce :: Int -> Position -> PlayerType -> Object -> Force
calcForce n p1 t1 object = if d2 == 0 then 0 else base / (fromIntegral d2 ** 1.5 :+ 0)
  where
    (x1, y1) = p1
    (x2, y2) = p2
    wrap d = minimumBy (compare `on` abs) [d, n - d]
    dx = wrap $ x2 - x1
    dy = wrap $ y2 - y1
    Object t2 p2 = object
    d2 = dx * dx + dy * dy
    base = (fromIntegral dx :+ fromIntegral dy) * case t1 of
      PacmanPlayer -> case t2 of
        Pellet -> 10.0
        PowerPellet -> 200.0
        Ghost -> -500.0
        Pacman -> -20.0
        Fruit -> 100.0
        Empty -> -2.0
      GhostPlayer -> case t2 of
        Pellet -> 10.0
        PowerPellet -> 200.0
        Ghost -> -50.0
        Pacman -> 500.0
        Fruit -> 100.0
        Empty -> -2.0

instance PlayerAI Physicist where
  findAction player info = (action, player') where
    Player {
      playerType = type_
    , playerField = field
    , playerMemory = Physicist objectsWithAge _
    } = player

    n = fieldSize field
    NormalRound pos _ objects = info
    objectsWithAge' = combineObjects objectsWithAge objects
    objects' = map snd objectsWithAge'
    directionChoices = filter (not . gridHasWall grid) directions4
    totalForce = sum $ map (calcForce n pos type_) objects'
    grid = fromMaybe (error $ "invalid position " ++ show pos) $ (fieldGetGrid field) pos
    action = if magnitude totalForce < 1e-10
      then if null directionChoices
        then Stay
        else Move $ head directionChoices
      else Move $ maximumBy (compare `on` (projectForce totalForce)) directionChoices
    debugInfo = Just $ DebugInfo grid totalForce action
    player' = player {
      playerMemory = Physicist objectsWithAge' debugInfo
    }

  -- roundDebug player _ = do
  --   let Physicist objects debugInfo = playerMemory player
  --       type_ = playerType player
  --   hPrint stderr (objects, debugInfo)

combineObjects :: [(Int, Object)] -> [Object] -> [(Int, Object)]
combineObjects xs ys = Map.elems $ foldr foldFunc initMap ys where
  foldFunc object@(Object type_ pos) = Map.insert pos (0, object)
  addAge (age, object) = (age + 1, object)
  toItem (age, object@(Object _ pos)) = (pos, (age, object))
  initMap = Map.fromList . map toItem . filter filterFunc . map addAge $ xs
  filterFunc (age, object@(Object type_ _))
    | type_ == Empty = True
    | age < maxAge = True
    | otherwise = False

maxAge = 5

projectForce :: Force -> Direction -> Double
projectForce (fx :+ fy) (Direction dx dy) = fx * fromIntegral dx + fy * fromIntegral dy

main :: IO ()
main = runAI $ Physicist [] Nothing

Pacman.hs

module Pacman (
    Field(..)
  , Grid(..)
  , Direction(..)
  , directions4, directions8
  , Position
  , newPosition
  , Player(..)
  , PlayerType(..)
  , ObjectType(..)
  , Object(..)
  , RoundInfo(..)
  , Action(..)
  , runAI
  , PlayerAI(..)
  ) where

import Data.Bits
import Data.Char
import Data.List
import Data.Maybe
import qualified Data.Map as Map
import qualified System.IO as SysIO

data Field = Field {
  fieldGetGrid :: Position -> Maybe Grid
, fieldSize :: Int
}

data Grid = Grid {
  gridHasWall :: Direction -> Bool
, gridPos :: Position
}

instance Show Grid where
  show g = "Grid " ++ show (gridPos g) ++ ' ':reverse [if gridHasWall g d then '1' else '0' | d <- directions4]

data Direction = Direction Int Int
  deriving (Show, Eq)

directions4, directions8 :: [Direction]
directions4 = map (uncurry Direction) [(-1, 0), (0, 1), (1, 0), (0, -1)]
directions8 = map (uncurry Direction) $ filter (/=(0, 0)) [(dx, dy) | dx <- [-1..1], dy <- [-1..1]]

type Position = (Int, Int)
newPosition :: (Int, Int)  -> Position
newPosition = id

data Player a = Player {
  playerType :: PlayerType
, playerField :: Field
, playerRounds :: Int
, playerMemory :: a
}
data PlayerType = PacmanPlayer | GhostPlayer
  deriving (Show, Eq)

class PlayerAI a where
  onGameStart :: a -> Field -> IO ()
  onGameStart _ _ = return ()

  onGameEnd :: a -> IO ()
  onGameEnd _ = return ()

  findAction :: Player a -> RoundInfo -> (Action, Player a)

  roundDebug :: Player a -> RoundInfo -> IO ()
  roundDebug _ _ = return ()


data ObjectType = Pacman | Ghost | Fruit | Pellet | PowerPellet | Empty
  deriving (Eq, Show)
data Object = Object ObjectType Position
  deriving (Show)

data RoundInfo = EndRound | NormalRound Position PlayerType [Object]

data Action = Stay | Move Direction
  deriving (Show)


parseField :: String -> Field
parseField s = if validateField field
  then field 
  else error $ "Invalid field: " ++ show ("n", n, "s", s, "fieldMap", fieldMap)
  where
    field = Field {
      fieldGetGrid = flip Map.lookup fieldMap
    , fieldSize = n
    }
    (n : _) = [x | x <- [0..], x * x == length s]
    fieldMap = Map.fromList [
        ((i, j), parseGrid c (newPosition (i, j))) 
        | (i, row) <- zip [0..n-1] rows,
          (j, c) <- zip [0..n-1] row
      ]
    rows = reverse . snd $ foldr rowFoldHelper (s, []) [1..n]
    rowFoldHelper _ (s, rows) =
      let (row, s') = splitAt n s
      in (s', row:rows)

validateField :: Field -> Bool
validateField field@(Field { fieldGetGrid=getGrid, fieldSize=n }) = 
  all (validateGrid field) $ map (fromJust.getGrid) [(i, j) | i <- [0..n-1], j <- [0..n-1]]

validateGrid :: Field -> Grid -> Bool
validateGrid
  field@(Field { fieldGetGrid=getGrid, fieldSize=n })
  grid@(Grid { gridPos=pos })
  = all (==True) [gridHasWall grid d == gridHasWall (getNeighbour d) (reverse d) | d <- directions4]
  where
    reverse (Direction dx dy) = Direction (-dx) (-dy)
    (x, y) = pos
    getNeighbour (Direction dx dy) = fromJust . getGrid . newPosition $ (mod (x + dx) n, mod (y + dy) n)

parseGrid :: Char -> Position -> Grid
parseGrid c pos = Grid gridHasWall pos
  where
    walls = zip directions4 bits
    bits = [((x `shiftR` i) .&. 1) == 1 | i <- [0..3]]
    Just x = elemIndex (toLower c) "0123456789abcdef"
    gridHasWall d = fromMaybe (error $ "No such direction " ++ show d) $
      lookup d walls

parseRoundInfo :: String -> RoundInfo
parseRoundInfo s = if s == "Q" then EndRound else NormalRound pos playerType objects'
  where
    allObjects = map parseObject $ words s
    Object type1 pos : objects = allObjects
    objects' = if type1 `elem` [Empty, Ghost] then objects else allObjects
    playerType = case type1 of
      Ghost -> GhostPlayer
      _ -> PacmanPlayer

parseObject :: String -> Object
parseObject s = Object type_ (newPosition (x, y)) where
  (y, x) = read $ "(" ++ init s ++ ")"
  type_ = case last s of
    'P' -> Pacman
    'G' -> Ghost
    'o' -> Pellet
    'O' -> PowerPellet
    'F' -> Fruit
    'X' -> Empty
    c -> error $ "Unknown object type: " ++ [c]

sendAction :: Action -> IO ()
sendAction a = putStrLn name >> SysIO.hFlush SysIO.stdout where
  name = (:[]) $ case a of
    Stay -> 'X'
    Move d -> fromMaybe (error $ "No such direction " ++ show d) $
      lookup d $ zip directions4 "NESW"

runPlayer :: PlayerAI a => Player a -> IO ()
runPlayer player = do
  roundInfo <- return . parseRoundInfo =<< getLine
  case roundInfo of
    EndRound -> return ()
    info@(NormalRound _ type_' _) -> do
      let
        updateType :: Player a -> Player a
        updateType player = player { playerType = type_' }
        player' = updateType player
        (action, player'') = findAction player' info
      roundDebug player'' info
      sendAction action
      let 
        updateRounds :: Player a -> Player a
        updateRounds player = player { playerRounds = playerRounds player + 1}
        player''' = updateRounds player''
      runPlayer player'''

runAI :: PlayerAI a => a -> IO ()
runAI mem = do
  field <- return . parseField =<< getLine
  let player = Player {
    playerType = PacmanPlayer
  , playerField = field
  , playerRounds = 0
  , playerMemory = mem
  }
  runPlayer player

makefile

physicist: Main.hs Pacman.hs
    ghc -O3 -Wall Main.hs -o physicist

command.txt

./physicist

मैं इसे चलाने में असमर्थ हूं। Main' Expected जब मैं इसे बनाने की कोशिश करता हूं, तो मुझे "फ़ाइल का नाम मॉड्यूल के नाम से मेल नहीं खाता है।" इसके अलावा, इसे चलाने के लिए, क्या मुझे इसे बनाने की आवश्यकता है, या क्या मुझे चलाने के लिए एक और कमांड की आवश्यकता है?
नाथन मेरिल

@NathanMerrill आपको पहले इसे बनाना चाहिए फिर physicistनिष्पादन योग्य चलाना चाहिए । संपादित और जोड़ा गया command.txt, अब।
रे

मैं इसे बना रहा हूं। मेरे द्वारा सूचीबद्ध की गई त्रुटि को मेरे द्वारा किए जाने पर फेंक दिया जाता है। यह भी मान लें कि आप भौतिक विज्ञानी निर्देशिका में हैं। क्या यह कमांड कमांड में ghc भौतिक विज्ञानी नहीं होगा?
नाथन मेरिल

@NathanMerrill यह अजीब है। शायद विंडोज पर जीएचसी के विभिन्न व्यवहार के कारण। नाम बदलने physicist.hsसे Main.hsकाम चल सकता है। मैंने जवाब अपडेट कर दिया है।
रे

@NathanMerrill क्या आपने इन दो फ़ाइलों को संयोजित किया है? यह काम नहीं करेगा।
रे

3

dumbpac

यह पीएसी बस बेतरतीब ढंग से चलती है, जिसमें भूलभुलैया लेआउट या भूतों या किसी भी अन्य कारकों का कोई संबंध नहीं है।

पर्ल:

#!/usr/bin/perl
local $| = 1; # auto flush!
$maze_desc = <>;
while(<>) { 
    if($_ eq "Q"){
        exit;
    }
    $move = (("N","E","S","W","X")[rand 5]);
    print ($move . "\n");
}

अजगर:

#!/usr/bin/env python

import os
import sys
import random

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # automatically flush stdout

maze_desc = sys.stdin.readline().rstrip()
while True:
    info = sys.stdin.readline().rstrip()
    if (not int) or (info == "Q"):
        break
    print random.choice(['N', 'E', 'S', 'W', 'X'])

3

चहलकदमी

यह पीएसी यादृच्छिक रूप से चलता है, लेकिन दीवारों में नहीं

#!/usr/bin/env python

import os
import re
import sys
import math
import random

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # automatically flush stdout

# read in the maze description
maze_desc = sys.stdin.readline().rstrip()
maze_size = int(math.sqrt(len(maze_desc)))

# turn the maze description into an array of arrays of numbers indicating wall positions
def chunks(l, n):
    for i in xrange(0, len(l), n):
        yield l[i:i+n]
map = []
for row in chunks(maze_desc, maze_size):
    map.append([int(c,16) for c in row])

# regex to parse a line of input
input_re = re.compile('(?:([-\d]+),([-\d]+)([PGoOFX]?) ?)+')

while True:
    info = sys.stdin.readline().rstrip()
    if (not info) or (info == "Q"):
        break

    # break a line of input up into a list of tuples (X,Y,contents)
    info = info.split()
    info = [input_re.match(item).groups() for item in info]

    # this pac only cares about its current location
    info = info[0]

    # which directions can we move from our current location?
    valid_directions = []
    # we might consider sitting still
    # valid_directions.append('X')
    walls = map[int(info[1])][int(info[0])]
    if not walls&1:
        valid_directions.append('N')
    if not walls&2:
        valid_directions.append('E')
    if not walls&4:
        valid_directions.append('S')
    if not walls&8:
        valid_directions.append('W')

    # move at random, not into a wall
    print random.choice(valid_directions)

1

पैथी, अजगर ३

यह बॉट बहुत खोजने का उपयोग करता है। एक शुरुआती स्थिति और अंतिम स्थिति को देखते हुए, यह सबसे छोटा रास्ता खोजने के लिए सरल BFS का उपयोग करता है। पथ खोज में उपयोग किया जाता है:

  • पावर छर्रों, फलों या छर्रों का पता लगाएं।
  • यदि यह अजेय है, तो भूतों का पीछा करें
  • यदि यह भूत है, तो पीएसी-मेन का पीछा करें
  • भूतों से भागना
  • किसी दिए गए पदों के बीच की दूरी की गणना करें।

command.txt

python3 pathy.py

pathy.py

import sys
import random
from collections import deque

DIRECTIONS = [(-1, 0), (0, 1), (1, 0), (0, -1)]
GHOST = 'G'
PACMAN = 'P'
FRUIT = 'F'
PELLET = 'o'
POWER_PELLET = 'O'
EMPTY = 'X'

PACMAN_PLAYER = 'pacman-player'
GHOST_PLAYER = 'ghost-player'


class Field:
    def __init__(self, s):
        n = int(.5 + len(s) ** .5)
        self.size = n
        self.mp = {(i, j): self.parse_grid(s[i * n + j]) for i in range(n) for j in range(n)}

    @staticmethod
    def parse_grid(c):
        x = int(c, 16)
        return tuple((x >> i) & 1 for i in range(4))

    def can_go_dir_id(self, pos, dir_id):
        return self.mp[pos][dir_id] == 0

    def connected_neighbours(self, pos):
        return [(d, self.go_dir_id(pos, d)) for d in range(4) if self.can_go_dir_id(pos, d)]

    def find_path(self, is_end, start):
        que = deque([start])
        prev = {start: None}
        n = self.size

        def trace_path(p):
            path = []
            while prev[p]:
                path.append(p)
                p = prev[p]
            path.reverse()
            return path

        while que:
            p = x, y = que.popleft()
            if is_end(p):
                return trace_path(p)
            for d, p1 in self.connected_neighbours(p):
                if p1 in prev:
                    continue
                prev[p1] = p
                que.append(p1)
        return None

    def go_dir_id(self, p, dir_id):
        dx, dy = DIRECTIONS[dir_id]
        x, y = p
        n = self.size
        return (x + dx) % n, (y + dy) % n

    def distance(self, p1, p2):
        return len(self.find_path((lambda p: p == p2), p1)) 

    def get_dir(self, p1, p2):
        x1, y1 = p1
        x2, y2 = p2
        return (self.dir_wrap(x2 - x1), self.dir_wrap(y2 - y1))

    def dir_wrap(self, x):
        if abs(x) > 1:
            return 1 if x < 0 else -1
        return x


class Player:
    def __init__(self, field):
        self.field = field

    def interact(self, objects):
        " return: action: None or a direction_id"
        return action

    def send(self, msg):
        print(msg)
        sys.stdout.flush()


class Pathy(Player):
    FLEE_COUNT = 8

    def __init__(self, field):
        super().__init__(field)
        self.type = PACMAN_PLAYER
        self.pos = None
        self.mem_field = {p: GHOST for p in self.field.mp}
        self.power = 0
        self.flee = 0
        self.ghost_pos = None
        self.ghost_distance = None

    @property
    def invincible(self):
        return self.type == PACMAN_PLAYER and self.power > 0

    def detect_self(self, objects):
        ((x, y), type) = objects[0]
        self.type = GHOST_PLAYER if type == GHOST else PACMAN_PLAYER
        self.pos = (x, y)

    def update_mem_field(self, objects):
        for (p, type) in objects:
            self.mem_field[p] = type

    def find_closest_ghost_pos(self, objects):
        try:
            return min(
                (p for (p, t) in objects if t == GHOST),
                key=lambda p: self.field.distance(self.pos, p)
            )
        except:
            return None

    def chase(self, types):
        is_end = lambda p: self.mem_field[p] in types
        path = self.field.find_path(is_end, self.pos)
        if not path:
            return None
        return DIRECTIONS.index(self.field.get_dir(self.pos, path[0]))

    def interact(self, objects):
        self.detect_self(objects)
        self.update_mem_field(objects)

        action = None
        if self.invincible:
            self.debug('invincible!!!')
            action = self.chase((GHOST,))
            if action is None:
                action = self.chase((POWER_PELLET,))
            if action is None:
                action = self.chase((FRUIT, PELLET,))
        elif self.type == GHOST_PLAYER:
            action = self.chase((PACMAN,))
        else:
            # PACMAN_PLAYER
            ghost_pos = self.find_closest_ghost_pos(objects)
            if ghost_pos:
                ghost_distance = self.field.distance(ghost_pos, self.pos)
                if not self.flee or ghost_distance < self.ghost_distance:
                    self.flee = self.FLEE_COUNT
                    self.ghost_distance = ghost_distance
                    self.ghost_pos = ghost_pos

            if self.flee > 0:
                self.flee -= 1
                action = max(
                    self.field.connected_neighbours(self.pos),
                    key=lambda dp: self.field.distance(dp[1], self.ghost_pos)
                )[0]
                # self.debug('flee: ghost_pos {} pos {} dir {} dist {}'.format(
                #     self.ghost_pos, self.pos, DIRECTIONS[action], self.field.distance(self.pos, self.ghost_pos)))
            else:
                self.ghost_pos = self.ghost_distance = None
                action = self.chase((POWER_PELLET, FRUIT))
                if action is None:
                    action = self.chase((PELLET,))
                if action is None:
                    action = random.choice(range(5))
                    if action > 3:
                        action = None

        # Detect power pellet
        if action is None:
            next_pos = self.pos
        else:
            next_pos = self.field.go_dir_id(self.pos, action)
        if self.mem_field[next_pos] == POWER_PELLET:
            self.power = 9
        elif self.invincible and self.mem_field[next_pos] == GHOST:
            self.debug('Got a ghost!')
        else:
            self.power = max(0, self.power - 1)
        return action

    def debug(self, *args, **kwargs):
        return
        print(*args, file=sys.stderr, **kwargs)


def start_game(player_class):
    field = Field(input())
    player = player_class(field)
    while True:
        line = input()
        if line == 'Q':
            break
        objects = [(tuple(map(int, x[:-1].split(',')))[::-1], x[-1]) for x in line.split(' ')]
        action = player.interact(objects)
        player.send('NESW'[action] if action is not None else 'X')


if __name__ == '__main__':
    start_game(Pathy)

objects = [(tuple(map(int, x[:-1].split(',')))[::-1], x[-1]) for x in line.split(' ')]ValueError: invalid literal for int() with base 10: '8o'
नाथन मेरिल

नियंत्रक ने क्या भेजा? क्या यह हर बार विफल होता है? यह यहां काम करता है और मुझे लगता है कि इस कथन को अच्छी तरह से काम करना चाहिए।
रे
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.