Python Help

Hey so I've got a final project for my intro programming class that I'm having some trouble on, if any of you guys don't mind lending me your expertise I'd appreciate it.

Essentially, I've got a list of lists of strings set up like a grid, made to look like a map (we're making a shitty overhead game using ASCII symbols). My "character" is represented by a letter. I've got the static map all set, easy enough. But I'm having trouble figuring out how to simulate movement. Posting pics of the code in a sec.

Other urls found in this thread:

python.org/dev/peps/pep-0008/
twitter.com/SFWRedditVideos

Relevant code for the map object.

The functions I'm having trouble with.

Aaand what it looks like in the shell at the moment.

Would appreciate any kind of pointers or constructive criticism that might help me figure this out.

Oh and it's probably important that I mention this, the game doesn't error, and when I give it valid input for direction (WASD), it'll reprint the map (like I want it to), but it won't change the position of my character "X".

>moveToCords
What the fuck do you think and means?

Okay changed to "or" in the code. That's a step in the right direction at least.

why is moveToCords testing if self.grid[x][y] is simultaneously equal to four different things

What is playX and playY?
That function movetocoord doesn't have access to them
also "To use the Code tag, book-end your body of code with: [c(letter o)de] and [/code]"

I wanted to set it up so that you could only move to certain coordinates occupied by certain symbols (" ' ", "O", and "@", realized "X" is redundant, getting rid of that one).
I'm pretty sure there is a better way to check if the location is valid, but that's the only thing I could think of so far.

>all those for loops
imperative programmers, everyone

So why would you use for in to test direction against WASD, but not to check if self.grid[x][y] is '0@X ?

What were you thinking?

post your full program with code tags, quickly explain what you want/what letters mean and I'll do it for you

what are you thinking with that while loop?!
if the user enters w,a,s or d then they don't enter it and the program ends. So nothing will happen

>what were you thinking
Not a whole lot to be honest, I'm still pretty new to this. Lots of stupid mistakes.

Should I do:
while direction in ["w", "a", "s", "d"]:
or
if direction in ["w", "a", "s", "d"]:

or neither?

Really? I feel like I really ought to figure it out myself but I really wouldn't say to to that offer if you're serious.

"while True" since there's not supposed to be a way to exit.

yes use
while direction in ["w", "a", "s", "d"]:
this will exit if they enter anything other that wasd
or this and yes post all your code, you can ignore whatever you want

playX and playY are meant to represent the player's current coordinates.

*wouldn't say no to

Fuck I'm retarded, thanks for that actually.

Okay I'll just dump the whole thing, minus a few useless bits. One sec.

import random

class Character(object):
def __init__(self, name, DMG, AGI, HP):
self.name = name
self.DMG = DMG
self.AGI = AGI
self.HP = HP

def getName(self):
return self.name
def setName(self, newName):
self.name = newName
def getDMG(self):
return self.DMG
def setDMG(self, newDMG):
self.DMG = newDMG
def getAGI(self):
return self.AGI
def setAGI(self, newAGI):
self.AGI = newAGI
def getHP(self):
return self.HP
def setHP(self, newHP):
self.HP = newHP

def __str__(self):
r = "You are: \n"
r += "Name: " + self.getName() + "\n"
r += "Damage: " + str(self.getDMG()) + "\n"
r += "Agility: " + str(self.getAGI()) + "\n"
r += "Health: " + str(self.getHP()) + "\n"
return r


def attack(self, enemy):
hitChance = random.randint(1,100) + self.AGI
dodgeChance = random.randint(1,100) + enemy.AGI
if(hitChance > dodgeChance):
enemy.HP -= self.DMG
print("You hit, dealing", self.DMG, "damage.")
print("Current Enemy HP:", enemy.HP)
if(enemy.HP = chanceToFlee):
stillFighting = False
ran = True
print("....success!")
else:
print("...and failed.")

class Enemy(Character):
def attack(self, player):
hitChance = random.randint(1,100) + self.AGI
dodgeChance = random.randint(1,100) + player.AGI
if(hitChance > dodgeChance):
player.HP -= self.DMG
print("Current Player HP:", player.HP)
if(player.HP

def charMenu():
menu = '''


Remind me again, which are you again?

1 - Fighter: Medium Damage, Low Agility, High HP

2 - Ranger: Medium Damage, High Agility, Medium HP

3 - Mage: High Damage, Medium Agility, Low HP


4 - DEITY: Monstrous Everything (PICK ME)


'''
charChoice = input(menu)
while charChoice not in ["1","2","3","4"]:
charChoice = input(menu)

if charChoice == "1":
player = Character("Dovydas", 15, 10, 50)
print(player)
elif charChoice == "2":
player = Character("Garth", 15, 20, 40)
print(player)
elif charChoice == "3":
player = Character("Morrin", 20, 15, 30)
print(player)
elif charChoice == "4":
player = Character("Thor", 9999, 9999, 9999)
print(player)
else:
print("Invalid Choice, please try again.")
charChoice = input("Please choose a champion type: ")

def main():
#Spawning enemies and creating map
soldier1 = Enemy("Soldier", 7, 7, 30)
soldier2 = Enemy("Soldier", 7, 7, 30)
soldier3 = Enemy("Soldier", 7, 7, 30)
soldier4 = Enemy("Soldier", 7, 7, 30)
soldier5 = Enemy("Soldier", 7, 7, 30)
soldier6 = Enemy("Soldier", 7, 7, 30)
soldier7 = Enemy("Soldier", 7, 7, 30)
soldier8 = Enemy("Soldier", 7, 7, 30)
soldier9 = Enemy("Soldier", 7, 7, 30)
commander1 = Enemy("Commander", 17, 17, 45)
gameMap = Map()

print('''


**ASCII Title here**

Created by Someone

1 - NEW GAME
2 - LOAD GAME
3 - QUIT

Legend:
X - Player
O - Enemy
@ - Boss
# - Building
% - Tree

Controls:
WASD - Move North/East/South/West (respectively)
P - Pause Menu

''')
i = input(" Make a selection: ")
if i == "1":
print('''\n


Story text goes here


''')
charMenu()
print('''\n
(HINT: Commander dead = end of game)\n''')
print("")
while commander1.HP > 0:
gameMap.display()
gameMap.move()

elif i == "2":
print("Load Game")
elif i == "3":
print("Quit")

input("Press Any Key to Exit: ")

#Make working map
#Make fight sequence
#Make save/load functionality

main()

Now, before you all tear me a new one:
Yes, I know a lot of these functions aren't going anywhere or doing anything yet.
Yes, I know some of those objects are kind of useless right now.
Yes, I know it's shit for balance; that's not a priority.

>DMG, AGI, HP
You generally only capitalize constants, but since you have setters it doesn't seem like these are constants.

>def setDMG(self, newDMG):
You don't need the "new" here. Python won't confuse DMG with self.DMG.

Also, the second direction = input() will only get run if the user didn't enter wasd previously.

(Don't call yourself Awful OP)

You got an error in moveToCords
that should be a self. before playX and playY
that function doesn't current have access to them

Overlooked that, I think someone else mentioned that as well, thanks.

Yeah they're not really constants, just have them capitalized for my own sake. Not good practice but whatever.
And I had the setters in case I wanted to make the attributes private or something (don't remember to be honest), don't need them but figured I'd leave them in just in case.

>camelCase in MY python

in moveToCords what are you trying to do with that if statement?
How can one cell be 4 different characters?

What this guy said
use underscore_case

Oh and yeah I was just getting to the move and moveToCords functions, was still in the process of trying to make it so that you can repeat the action. Was trying to get it to work at least once first.

self.grid = [["'" * 15] * 15]


def display(self):
print('\n'.join(row[0] for row in self.grid))


Not gonna fix those 2 other functions that don't currently work, but homie, you really need to clean up your code. Stop using shitty normal constructs that make your code less readable.

camelCase because that's how the professor does it, just kind of stuck to it myself.

I wanted to check to see if one cell contained any of those four characters. I really did not think that bit would work but I felt like I had to try something.

Yeah I know it looks bad, but I'm really not good at this stuff, and expectations are low as this is a beginner's course.

There's no harm in doing something a shitty way if your just learning and it makes more sense to you.
Being more verbose also helps with debugging and makes it easier for new devs to understand your code.
But in this case he is using shitty code and should prob try clean it up a bit

Learning by doing something the shitty way is detrimental imo, and I agree doing something verbose if it looks simple is better for sharing code, but python's constructs make code more readable

Don't get me wrong, I'm not trying to trash OP, just letting him know that for future reference, he'll learn a language faster if he finds out and uses a language's given, unique tools.

If it's required for school, I recommend unlearning it as soon as possible.

to check if @ x,y contains any of those just change
if self.grid[x][y] == "'" or self.grid[x][y] == "O" or self.grid[x][y] == "@":

to
if self.grid[x][y] in ["'", "O", "@"]:


same effect but easier to read

python.org/dev/peps/pep-0008/

but if your dumb lecturer wants you to do something there's not much he can do about it

Oh right, I think I had something similar in another part of the code. I appreciate it.

Yeah I gotcha, I'm just trying to get through this course for now. I don't think I'll be doing any more Python next semester, but I'll be starting up Java and C++. Trying to learn from my mistakes in this course to at least do better in those.

That looks pretty helpful, I'll give it a read through when I can, thanks.

>tfw I've been using camelCase in python since forever
Fuck. I don't know if I'll ever be able to switch over, but I'll try.

Then again, there's no way I'm not gonna stop using in-line comments all the time.

In any case, I'm going to continue providing OP with some tips for future reference

Back to this, I believe moveToCords is supposed to let you move to ', O or @ spaces

Checking for X (yourself) is useless as display() has no side effects that require it.

Your logic should be if self.grid[x][y] in ["'", "O", "@"]:


For move(self), there's a lot of redundant code
direction = input("Move: ")
while direction not in ["w", "a", "s", "d"]:
direction = input("Move: ")
dir_map = {
"w": (0, -1),
"a": (-1, 0),
"s": (0, 1),
"d": (1, 0)
}
self.moveToCords(playX+dir_map[directon][0], playY+dir_map[direction][1])


C++ and Java have their unique quirks, though you need something like Spring for aspect-oriented programming to make Java close to python's expressiveness. C++ preprocessor macros are fun to toy around with, and making games in it is pretty fun. It's going to be good course

before the 2nd direction=input("Move: "), add the line
print("Please use the WASD keys (lowercase) to move.")


Lower case is a pretty weird requirement when str.lower() is pretty short. You could do:
direction = input("Move: ").lower()


getters and setters are entirely useless in python as everything is public (and should be, as encapsulation has long been known a useless meme). If you REALLY wanted to make them accessible only through an interface (and your code doesn't really look it need it), you can use the property decorator, and define getters and setters after

Oh I wouldn't have thought of using dictionaries, that looks a lot better.

To be fair, I didn't come up with it, I discovered that particular style during a competition and it was the highest rated solution. It was about a few weeks to a month after I picked up python, and these new ways of doing things fascinated me too

Yeah that makes a lot more sense, I'll change that now. And yeah, since I don't really need them I guess I'll get rid of the getters/setters.

>encapsulation has long been known a useless meme
Please explain or tell me what to google for that. It seemed pretty pointless when I learned it, but I was wondering if it is actually useful in some way. I think they might still ask about it in some interview questions even if it's a meme?

I've worked with java and python professionally, and no, they will not ask about OO concepts. Encapsulation is useless because it doesn't mean anything, people were just excited about the idea of interfaces. Even when people were making delicate libraries in C, it didn't matter what you could or couldn't do, everything was manipulable and encapsulating anything would provide no benefit. It still provides no benefit

I probably shouldn't use it if it's too impressive, however it works, so I might just do it anyway.

dont worry it's not that impressive. Many many people use similar ideas to remove big long if else statements

Gotcha, he probably won't notice.

Thanks for the help (the rest of you too if anyone is still around) by the way, seems like the thread is dying, gonna have to go back to working on it on my own. Really appreciate it.

why are you all helping a retard with his homework he can't even post the fucking code he posted pics

god this website is pure cancer good job ruining the 4chin retards im done

being retarded is good, moron

Peace out, bitch