[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y ] [Home]
4chanarchives logo
Python Help
Images are sometimes not shown due to bandwidth/network limitations. Refreshing the page usually helps.

You are currently reading a thread in /g/ - Technology

Thread replies: 50
Thread images: 4
File: 1.png (8 KB, 360x361) Image search: [Google]
1.png
8 KB, 360x361
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.
>>
File: Screenshot (2).png (46 KB, 665x333) Image search: [Google]
Screenshot (2).png
46 KB, 665x333
>>54433943
Relevant code for the map object.
>>
File: Screenshot (3).png (116 KB, 1273x641) Image search: [Google]
Screenshot (3).png
116 KB, 1273x641
>>54433955
The functions I'm having trouble with.
>>
File: Screenshot (4).png (16 KB, 673x649) Image search: [Google]
Screenshot (4).png
16 KB, 673x649
>>54433974
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.
>>
>>54433993
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".
>>
>>54433974
>moveToCords
What the fuck do you think and means?
>>
>>54434180
Okay changed to "or" in the code. That's a step in the right direction at least.
>>
>>54433974
why is moveToCords testing if self.grid[x][y] is simultaneously equal to four different things
>>
>>54433974
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]"
>>
>>54434220
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.
>>
>>54433974
>all those for loops
imperative programmers, everyone
>>
>>54434219
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?
>>
>>54434295
post your full program with code tags, quickly explain what you want/what letters mean and I'll do it for you
>>
>>54433974
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
>>
>>54434329
>>54434360
>what were you thinking
Not a whole lot to be honest, I'm still pretty new to this. Lots of stupid mistakes.

>>54434360
Should I do:
while direction in ["w", "a", "s", "d"]:

or
if direction in ["w", "a", "s", "d"]:


or neither?

>>54434336
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.
>>
>>54434438
"while True" since there's not supposed to be a way to exit.
>>
>>54434438
yes use
while direction in ["w", "a", "s", "d"]:
this will exit if they enter anything other that wasd
or this >>54434458


and yes post all your code, you can ignore whatever you want
>>
>>54434285
playX and playY are meant to represent the player's current coordinates.

>>54434438
*wouldn't say no to

>>54434458
Fuck I'm retarded, thanks for that actually.

>>54434473
Okay I'll just dump the whole thing, minus a few useless bits. One sec.
>>
>>54434516
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 <= 0):
stillFighting = False
else:
print("You missed!")

def flee(self):
print("You attempt to flee....")
chanceToFlee = random.randint(1,100)
if(self.AGI >= chanceToFlee):
stillFighting = False
ran = True
print("....success!")
else:
print("...and failed.")
>>
>>54434567
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 <= 0):
stillFighting = False
else:
print("Your opponent missed!")


class Map(object):
def __init__(self, size = 15, playX = 7, playY = 0):
self.size = size
self.playX = playX
self.playY = playY
self.grid = []

for x in range(size):
self.grid.append([])

for x in self.grid:
for y in range(size):
x.append("'")

self.grid[playX][playY] = "X"


 def display(self):
for x in range(self.size):
for y in range(self.size):
print(self.grid[y][x], end = "")
print("\n")

def moveToCords(self, x, y):
if self.grid[x][y] == "'" or self.grid[x][y] == "O" or self.grid[x][y] == "@":
self.grid.remove("X")
self.grid[playX][playY] = self.grid[x][y]
self.display()

def move(self):
direction = input("Move: ")
while direction in ["w", "a", "s", "d"]:
if direction == "w":
self.moveToCords(playX, playY - 1)
elif direction == "a":
self.moveToCords(playX - 1, playY)
elif direction == "s":
self.moveToCords(playX, playY + 1)
elif direction == "d":
self.moveToCords(playX + 1, playY)
else:
print("Please use the WASD keys (lowercase) to move.")
direction = input("Move: \n")
>>
>>54434587
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()
>>
>>54434600
    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.
>>
>>54434567
>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)
>>
>>54434516
You got an error in moveToCords
that should be a self. before playX and playY
that function doesn't current have access to them
>>
>>54434651
Overlooked that, I think someone else mentioned that as well, thanks.

>>54434648
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
>>
>>54434726
in moveToCords what are you trying to do with that if statement?
How can one cell be 4 different characters?

What this guy said
>>54434768
use underscore_case
>>
>>54434648
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.
>>
>>54433955
self.grid = [["'" * 15] * 15]


>>54433974
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.
>>
>>54434768
>>54434799
camelCase because that's how the professor does it, just kind of stuck to it myself.

>>54434799
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.

>>54434822
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.
>>
>>54434822
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
>>
>>54434878
>>54434884
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.
>>
>>54434878
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
>>
>>54434878
https://www.python.org/dev/peps/pep-0008/
>>
>>54434979
but if your dumb lecturer wants you to do something there's not much he can do about it
>>
>>54434956
Oh right, I think I had something similar in another part of the code. I appreciate it.

>>54434950
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.

>>54434979
That looks pretty helpful, I'll give it a read through when I can, thanks.
>>
>>54434979
>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.
>>
>>54434950
In any case, I'm going to continue providing OP with some tips for future reference

>>54433974
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])


>>54435044
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
>>
>>54435144
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()


>>54434567
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
>>
>>54435144
Oh I wouldn't have thought of using dictionaries, that looks a lot better.
>>
>>54435267
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
>>
>>54435259
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.
>>
>>54435259
>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?
>>
>>54435317
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
>>
>>54435305
I probably shouldn't use it if it's too impressive, however it works, so I might just do it anyway.
>>
>>54435415
dont worry it's not that impressive. Many many people use similar ideas to remove big long if else statements
>>
>>54435647
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
>>
>>54436520
being retarded is good, moron
>>
>>54436520
Peace out, bitch
Thread replies: 50
Thread images: 4

banner
banner
[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y] [Home]

All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
If a post contains personal/copyrighted/illegal content you can contact me at [email protected] with that post and thread number and it will be removed as soon as possible.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com, send takedown notices to them.
This is a 4chan archive - all of the content originated from them. If you need IP information for a Poster - you need to contact them. This website shows only archived content.