简体   繁体   English

我不得不帮助我理解我做错了(Python,再次)

[英]I can't but help get the idea I'm doing it all wrong (Python, again)

All of the questions that I've asked recently about Python have been for this project. 我最近问过的关于Python的所有问题都是针对这个项目的。 I have realised that the reason I'm asking so many questions may not be because I'm so new to Python (but I know a good bit of PHP) and is probably not because Python has some inherent flaw. 我已经意识到我问这么多问题的原因可能不是因为我对Python这么新(但我知道很多PHP)并且可能不是因为Python有一些固有的缺陷。

Thus I will now say what the project is and what my current idea is and you can either tell me I'm doing it all wrong, that there's a few things I need to learn or that Python is simply not suited to dealing with this type of project and language XYZ would be better in this instance or even that there's some open source project I might want to get involved in. 因此,我现在将说明项目是什么以及我目前的想法是什么,你可以告诉我,我做错了,我需要学习一些东西,或者Python根本不适合处理这种类型在这种情况下,项目和语言XYZ会更好,甚至可能还有一些我想参与的开源项目。

The project 该项目
I run a free turn based strategy game (think the campaign mode from the total war series but with even more complexity and depth) and am creating a combat simulator for it (again, think total war as an idea of how it'd work). 我运行一个基于免费转弯的策略游戏(从整个战争系列中考虑战役模式,但具有更多的复杂性和深度)并且正在为它创建一个战斗模拟器(再次,将全面战争视为它是如何工作的一个想法) 。 I'm in no way deluded enough to think that I'll ever make anything as good as the Total war games alone but I do think that I can automate a process that I currently do by hand. 我完全没有被认为我会做出与单纯的战争游戏一样好的东西,但我确实认为我可以自动化我目前手工制作的过程。

What will it do 它会做什么
It will have to take into account a large range of variables for the units, equipment, training, weather, terrain and so on and so forth. 它必须考虑到单位,设备,训练,天气,地形等的大量变量等。 I'm aware it's a big task and I plan to do it a piece at a time in my free time. 我知道这是一项艰巨的任务,我打算在空闲时间一次做一件事。 I've zero budget but it's a hobby that I'm prepared to put time into (and have already). 我没有预算,但是我已经准备好把时间投入(并且已经)了。

My current stumbling block 我目前的绊脚石
In PHP everything can access everything else, "wrong" though some might consider this it's really really handy for this. 在PHP中,一切都可以访问其他所有内容,“错误”虽然有些人可能会认为这对它来说非常方便。 If I have an array of equipment for use by the units, I can get hold of that array from anywhere. 如果我有一系列设备供单位使用,我可以从任何地方获取该阵列。 With Python I have to remake that array each time I import the relevant data file and this seems quite a silly solution for a language that from my experience is well thought out. 使用Python我每次导入相关数据文件时都必须重新创建该数组,对于一种经验深思熟虑的语言来说,这似乎是一个非常愚蠢的解决方案。 I've put in a system of logging function calls and class creation (because I know from a very basic version of this that I did in PHP once that it'll help a lot down the line) and the way that I've kept the data in one place is to pass each of my classes an instance to my logging list, smells like a hack to me but it's the only way I've gotten it to work. 我已经建立了一个记录函数调用和类创建的系统(因为我从PHP的一个非常基本的版本中知道它曾经在PHP中做过一次,它会帮助我做很多事情)以及我保留的方式在一个地方的数据是将我的每个类一个实例传递到我的日志列表,闻起来像是一个黑客对我来说,但这是我让它工作的唯一方法。

Thus I conclude I'm missing something and would very much appreciate the insight of anybody willing to give it. 因此,我得出结论,我错过了一些东西,非常欣赏任何愿意给予它的人的洞察力。 Thank you. 谢谢。

Code samples 代码示例

This creates a list of formations, so far there's only one value (besides the name) but I anticipate adding more on which is why they're a list of classes rather than just a standard list. 这创建了一个编队列表,到目前为止只有一个值(除了名称),但我预计会增加更多,这就是为什么它们是一个类列表而不仅仅是一个标准列表。 This is found within data.py 这可以在data.py中找到

formations = []
formationsHash = []
def createFormations(logger):
    """This creates all the formations that will be used"""

    # Standard close quarter formation, maximum number of people per square metre
    formationsHash.append('Tight')
    formations.append(Formation(logger, 'Tight', tightness = 1))

    # Standard ranged combat formation, good people per square metre but not too cramped
    formationsHash.append('Loose')
    formations.append(Formation(logger, 'Loose', tightness = 0.5))

    # Standard skirmishing formation, very good for moving around terrain and avoiding missile fire
    formationsHash.append('Skirmish')
    formations.append(Formation(logger, 'Skirmish', tightness = 0.1))

    # Very unflexible but good for charges
    formationsHash.append('Arrowhead')
    formations.append(Formation(logger, 'Arrowhead', tightness = 1))


def getFormation(searchFor):
    """Returns the fomation object with this name"""
    indexValue = formationsHash.index(searchFor)
    return formations[indexValue]

I don't have a code sample of when I'd need to access it because I've not gotten as far as making it but I anticipate the code looking something like the following: 我没有代码样本,当我需要访问它时,因为我没有达到它的目的,但我预计代码看起来像下面这样:

Python
tempFormation = data.getFormation(unit.formationType)
tempTerrain = data.getTerrain(unit.currentTerrain)
unit.attackDamage = unit.attackDamage * tempTerrain.tighnessBonus(tempFormation.tightness)

The unit contains an integer that links to the index/key of the relevant terrain, formation and whatnot in the master list. 该单元包含一个整数,该整数链接到主列表中相关地形,形成和诸如此类的索引/键。 Temporary variables are used to make the 3rd line shorter but in the long run will possibly cause issues if I forget to get one and it's use a value from earlier which is then incorrect (that's where the logging comes in handy). 临时变量用于使第3行更短但是从长远来看可能会导致问题,如果我忘记得到一个并且它使用之前的值然后是不正确的(这是日志记录派上用场的地方)。

PHP
$unit->attackDamage *= $terrain[$unit->currentTerrain]->tighnessBonus($unit->currentTerrain)

The unit class contains the index (probably a string) of the relevant terrain it's on and the formation it's in. 单元类包含它所在的相关地形的索引(可能是一个字符串)以及它所在的地层。

Maybe this will show some massive flaw in my understanding of Python (6 months vs the 3 years of PHP). 也许这会在我对Python的理解中显示出一些巨大的缺陷(6个月与3年的PHP相比)。

With Python I have to remake that array each time I import the relevant data file 使用Python,每次导入相关数据文件时都必须重新创建该数组

You're missing a subtle point of Python semantics here. 你在这里错过了Python语义的微妙之处。 When you import a module for a second time, you aren't re-executing the code in that module. 第二次导入模块时,不会重新执行该模块中的代码。 The name is found in a list of all modules imported, and the same module is returned to you. 该名称位于导入的所有模块的列表中,并返回相同的模块。 So the second time you import your module, you'll get a reference to the same list (in Python, don't say array, say list). 因此,第二次导入模块时,您将获得对同一列表的引用(在Python中,不要说数组,比如列表)。

You'll probably need to post specific code samples to get more help, it seems like there are a few Python misconceptions mixed into this, and once those are cleared up you'll have a simpler time. 您可能需要发布特定的代码示例以获得更多帮助,似乎有一些Python误解混入其中,一旦这些被清除,您将有一个更简单的时间。

I have narrowed your issue down to: 我已将您的问题缩小到:

With Python I have to remake that array each time I import the relevant data file 使用Python,每次导入相关数据文件时都必须重新创建该数组

Well you have two choices really, the first and easiest is to keep the structure in memory. 那么你真的有两个选择,第一个也是最容易将结构保留在内存中。 That way (just like PHP) you can in theory access it from "anywhere", you are slightly limited by namespacing, but that is for your own good. 这样(就像PHP一样)你理论上可以从“任何地方”访问它,你受命名空间的限制,但这是为了你自己的利益。 It would translate as "anywhere you would like to". 它将翻译为“您想要的任何地方”。

The second choice is to have some data abstraction (like a database, or data file as you have) which stores and you retrieve data from this. 第二种选择是拥有一些数据抽象(如数据库或数据文件),它存储并从中检索数据。 This may be better than the first choice, as you might have far too much data to fit in memory at once. 这可能比第一选择更好,因为您可能有太多的数据不能同时适应内存。 Again the way of getting this data will be available "anywhere" just like PHP. 再次获取这些数据的方式将像PHP一样随处可用。

You can either pass these things directly to instances in an explicit way, or you can use module-level globals and import them into places where you need them, as you go on to say: 您可以以显式方式将这些内容直接传递给实例,也可以使用模块级全局变量并将它们导入到需要它们的位置,然后继续说:

and the way that I've kept the data in one place is to pass each of my classes an instance to my logging list 我将数据保存在一个地方的方式是将每个类的实例传递给我的日志列表

I can assure you that this is not a hack. 我可以向你保证,这不是一个黑客。 It's quite reasonable, depending on the use, eg a config object can be used in the same way, as you may want to test your application with simultaneous different configs. 这是非常合理的,具体取决于用途,例如配置对象可以以相同的方式使用,因为您可能希望同时使用不同的配置来测试您的应用程序。 Logging might be better suited as a module-level global that is just imported and called, as you probably only ever want one way of logging, but again, it depends on your requirements. 记录可能更适合作为刚刚导入和调用的模块级全局,因为您可能只想要一种记录方式,但这又取决于您的要求。

I guess to sum up, you really are on the right track. 我想总结一下,你真的走在了正确的轨道上。 Try not to give in to that "hackish" smell especially when using languages you are not altogether familiar with. 尽量不要让这种“hackish”气味,特别是在使用你并不完全熟悉的语言时。 A hack in one language might be the gold-standard in another. 一种语言的黑客可能是另一种语言的黄金标准。 And of course, best of luck with your project - it sounds fun. 当然,祝你的项目好运 - 听起来很有趣。

Please don't reinvent the wheel. 请不要重新发明轮子。 Your formationsHash as a list of key values isn't helpful and it duplicates the features of a dictionary. 您的formationsHash作为键值列表没有帮助,它复制了字典的功能。

def createFormations(logger):
    """This creates all the formations that will be used"""
    formations = {}
    formations['Tight']= Formation(logger, 'Tight', tightness = 1)
    formations['Loose']= Formation(logger, 'Loose', tightness = 0.5)
    formations['Skirmish']= Formation(logger, 'Skirmish', tightness = 0.1)
    formations['Arrowhead']= Formation(logger, 'Arrowhead', tightness = 1)
    return formations

Note, you don't actually need getFormation , since it does you no good. 注意,你实际上并不需要getFormation ,因为它对你没有好处。 You can simply use something like this. 你可以简单地使用这样的东西。

formations = createFormations( whatever )
f= formations[name]

"data.py creates an array (well, list), to use this list from another file I need to import data.py and remake said list." “data.py创建一个数组(好吧,列表),从我需要导入data.py并重新创建列表的另一个文件中使用此列表。”

I can't figure out what you're talking about. 我无法弄清楚你在谈论什么。 Seriously. 认真。

Here's a main program, which imports the data, and another module. 这是一个导入数据的主程序和另一个模块。

SomeMainProgram.py SomeMainProgram.py

import data
import someOtherModule

print data.formations['Arrowhead']
someOtherModule.function()

someOtherModule.py someOtherModule.py

import data
def function():
    print data.formations['Tight']

data.py data.py

import theLoggerThing
class Formation( object ):
    pass # details omitted.
def createFormations( logger ):
    pass # details omitted
formations= createFormations( theLoggerThing.logger )

So the main program works like this. 所以主程序就是这样的。

  1. import data . import data The data module is imported. 导入data模块。

    a. 一种。 import theLoggerThing . import theLoggerThing Whatever this is. 不管这是什么。

    b. class Formation( object ): . class Formation( object ): Create a class Formations . 创建一个类Formations

    c. C。 def createFormations( logger ): . def createFormations( logger ): Create a function createFormations . 创建一个函数createFormations

    d. d。 formations = . formations = Create an object, formations . 创建一个对象, formations

  2. import someOtherModule . import someOtherModule The someOtherModule is imported. someOtherModule已导入。

    a. 一种。 import data . import data Nothing happens. 什么都没发生。 data is already available globally. data已在全球范围内提供 This is a reference to what is -- effectively -- a Singleton . 这是对 - 有效 - 单身人士的参考 All Python modules are Singletons . 所有Python模块都是单例

    b. def function . def function Create a function function . 创建一个功能function

  3. print data.formations['Arrowhead'] . print data.formations['Arrowhead'] Evaluate data.formations , which is a dictionary object. 评估data.formations ,它是一个字典对象。 Do a get('Arrowhead') on the dictionary which does some magical lookup and returns the object found there (an instance of Formation ). 在字典上做一个get('Arrowhead')做一些神奇的查找并返回那里找到的对象( Formation一个实例)。

  4. someOtherModule.function() . someOtherModule.function()

    What happens during this function evaluation. 在此功能评估期间会发生什么。

    a. 一种。 print data.formations['Tight'] . print data.formations['Tight'] Evaluate data.formations , which is a dictionary object. 评估data.formations ,它是一个字典对象。 Do a get('Tight') on the dictionary which does some magical lookup and returns the object found there (an instance of Formation ). 在字典上做一个get('Tight')做一些神奇的查找并返回那里找到的对象(一个Formation的实例)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在尝试 cURL 这个简单的 URL 在 PHP 中,我不知道我做错了什么 - I'm trying to cURL this simple URL in PHP and I can't figure out what I'm doing wrong 无法在数据库MYSQLI中插入值我做错了什么? - Can't insert values in database MYSQLI what I'm doing wrong? 遵循Codeigniter / Ajax / Jquery教程:似乎无法调试我做错了什么 - Following a Codeigniter/Ajax/Jquery tutorial: Can't seem to debug what I'm doing wrong 无法找出我在用这个php条件做错了什么 - Can't figure out what I'm doing wrong with this php conditional 我做错了什么? “的cronjob” - What I'm doing wrong? “cronjob” 我做错了什么? “会话开始” - What I'm doing wrong? "session start" 我收到“语法错误,意外的T_VARIABLE”错误。 我不明白我做错了什么? - I'm getting a “syntax error, unexpected T_VARIABLE” error. I don't see what I'm doing wrong? 当我使用外部php文件进行所有类型的查询时,如何获取INSERT查询的最后一个ID? - How i can get the last id of INSERT query when i'm using an external php file for doing all type of querys? PHP AES加密......不知道我在做什么 - PHP AES encryption… no idea what I'm doing 在从URL提取GET值时遇到问题,不确定我在做什么错 - Having issues pulling a GET value from a URL, Not sure what I'm doing wrong
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM