Let a module file use a global variable?

2024/10/16 3:22:18

Forgive me if this is just a super easy solution as I am pretty new to Python. Right now I'm trying to make a basic video game, and to save space I decided to make a module for a combat encounter -- so that all I have to do when writing the code for each encounter is run the function in that module, only having to write the unique variables of the enemy. However, the code needs to know things like the player's HP, or what kind of weapon the player has. I tried putting global before the variables in the function module, but of course it doesn't work, as that's referencing global variables in the module, not the main game file. Or is there another way to go about this? If you need me to enclose my code, I will gladly do so.

Edit: Heres the code, in the module (called combat). What I want it to do is the main file's code will just say:

combat.combat(3, "mysterious creature", 12, 2, 4, 3, "claws", 5, 0)

Which, based off my shallow understanding, is how i edit the variables for each oppoent, its from this line in the module file.

def combat(enemylevel, enemyname, enemyhp, enemydefense, enemystrength,enemyattack, enemyweaponattack, enemygp, run):

Based off you guys' confusion I'm guessing I'm doing something pretty basic wrong. Forgive my (most likely) cringey and ineffecient code-writing:

import random
import math
def combat(enemylevel, enemyname, enemyhp, enemydefense, enemystrength, enemyattack, enemyweaponattack, enemygp, run):global xpglobal hpglobal maxhpglobal gpglobal weapon_attackglobal weaponlevelandname = "level" , enemylevel, enemynameprint("You draw your weapon and prepare for battle. You are fighting a",levelandname, ".")while enemyhp > 0:if enemyhp > 0:print()attackorrun = input("Do you wish to attack or run? ")if attackorrun == "attack" or "a":print("You" , weapon_attack , "your" , weapon, "at the",enemyname) # this is where the first error happens,# says weapon_attack isn't defined.attackroll = random.randint(1, 20)attackroll = (attackroll+(math.floor(attack/2)))

I'm probably still leaving something unclear, feel free to tell me to do something else or ask me something.

Answer

Using large numbers of global variables can get messy. It doesn't provide you much flexibility, and as you're discovering, its hard to access those variables from other modules.

Many programmers will avoid using the global statement in a function, any data the function needs should be provided by other means.

Using container objects might be a good start, keeping related variables together, perhaps in a dictionary. You could pass an enemy dict (with hp, defense, strength etc.) and a player dict (xp, hp, weapon etc.) in to your function. That would give you access to those values in the function, and the function would even be able to modify those values (because you would be passing an object reference).

enemy = {'hp': 100, 'weapon': 'axe', 'strength': 50}
player = {'xp': 22, 'hp': 150, 'weapon': 'sword'}
def combat(player, enemy):#calculate results of combatplayer['hp'] = player['hp'] - damage

Another strategy might be to use classes. Classes are object definitions that can contain functions and variables. You can instantiate multiple instances of your class. An Enemy object (instance of an Enemy class) for example would contain an enemy hp variable, and functions that modify it during combat.

https://en.xdnf.cn/q/117761.html

Related Q&A

Python Subprocess readline hangs() after reading all input

I am trying to readlines from the tcp server that I ran in the same script. I am able to send one command and reads its output but at the end (after reading all outputs) it looks like that program hang…

Python Counting countries in dictionary

Im writing a function that counts the number of times a country appears in a dictionary and returns the country that appeared the most. If more then one country appears the most then it should return a…

How to wait for any socket to have data?

Im implementing a socket-client which opens several sockets at the same time. Any socket may have data at a different time and I want to execute code when any socket has data and is readable.Im not sur…

Retrieving ad URLs

Im looking for a way to retrieve the ad URLs for this website. http://www.quiltingboard.com/resources/What I want to do is probably write a script to continuously refresh the page and grab the ad URLs.…

Extract data (likes) from JSON API using Python

I want to pull the number of likes for my project. Heres my code: import facepy from facepy import GraphAPI from bs4 import BeautifulSoup import json access = CAACEdEose0cBAE3IL99IreDeAfqaVZBOje8ZCqIhf…

No nested nodes. How to get one piece of information and then to get additional info respectively?

For the code below I need to get dates and their times+hrefs+formats+...(not shown) respectively.<div class="showtimes"><h2>The Little Prince</h2><div class="poster&…

I need help changing the color of text in python

Hey I need help with coloring the text in a program I am making. It is a password program and I am trying to make the denied and granted red and green when they appear. Here is the program so far:passw…

How do I use Liclipse to write a ParaView script?

Ive tried following the directions here without success. Here are some of my environment variables:Path: C:\Python34\;C:\Python34\Scripts;...;C:\Program Files (x86)\ParaView 4.3.1\lib\paraview-4.3\site…

List of tuples to nested dictionary without overriding

I need to convert the above list of tuples to nested dictionary without overwriting the value as below in python[(a, 1),(b, true),(b, none),(a, 2),(b, true),(a, 3),(b, false)]{a: {1 : { b : (true,none)…

Rotate matplotlib pyplot with curve by 90 degrees

I have plot with one line as this:import numpy as np import matplotlib.pyplot as pla = np.array([4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9]) b = np.array([i/len(a) for i in range(1,…