I am trying to create a pokemon battle game where the user can select their pokemon and then choose moves. The computer also does this. I have written my game logic in Python, and I am using fetch to send the user inputs through to my backend and returning data for the next move.
My issue is that I want the two functions that run the battle to loop until one pokemon faints. This involves new buttons in the DOM, adding event listeners to these and repeating the fetch requests. My two functions work, but not when I call them within the while loop.
Here is my battle.js code:
const form = document.getElementById('form')
const choiceSection = document.getElementById("userPokemonChoice")
const launchGame = document.getElementById("launchGame")
const launchGameForm = document.getElementById("launchGameForm")
const gamePlay = document.getElementById("gamePlay")
launchGame.style.display = "none"
let cpu_status = ""
let user_status = ""
function getPokemonStats() {
form.addEventListener('submit', function(e){
e.preventDefault();
// Create a form with user input.
const formData = new FormData(this);
// Add the name and value of the pressed button to the form.
formData.append(e.submitter.name, e.submitter.value);
// Send a fetch request of type POST.
// generate url
const url = '/battle';
fetch(url, {
method: 'post',
body: formData
})
.then(response => response.json()) // Read the response as json.
.then(data => {
displayPokemonStats(data)
});
choiceSection.style.display = "none"
launchGame.style.display = "block"
});
}
displayPokemonStats = function(data) {
const pokemonStats = document.getElementById('stats')
pokemonStats.innerText =
`You have chosen ${data[0]['name']}. ${data[0]['name']}'s hp is ${data[0]['hp']}. ${data[0]['name']}'s moves are ${data[0]['moves'].join(', ')}.
The cpu has chosen ${data[1]['name']}.`
}
function cpuTurn(){
launchGameForm.addEventListener('submit', function(e) {
launchGame.style.display = "none"
e.preventDefault();
// Create a form with user input.
const cpuFormData = new FormData(this);
// Add the name and value of the pressed button to the form.
cpuFormData.append(e.submitter.name, e.submitter.value);
// Send a fetch request of type POST.
const url = '/battle/launch';
fetch(url, {
method: 'post',
body: cpuFormData
})
.then(response => response.json()) // Read the response as json.
.then(data => {
let user_status = data[2]
const new_para = launchGameForm.appendChild(document.createElement("p"))
if (user_status == 'alive'){
new_para.innerText = `${data[1]['name']} used ${data[1]['move']} causing ${data[1]['damage']} damage.
${data[0]['name']}'s hp was reduced to ${data[0]['hp']}.
Choose your next move!`
launchGameForm.setAttribute("action", "/battle/launch/turn")
new_button_1 = launchGameForm.appendChild(document.createElement("button"))
new_button_1.setAttribute("type", "submit")
new_button_1.setAttribute("name", "chooseMove")
new_button_1.setAttribute("value", `${data[0]['moves'][0]}`)
new_button_1.textContent = `${data[0]['moves'][0]}`
new_button_2 = launchGameForm.appendChild(document.createElement("button"))
new_button_2.setAttribute("type", "submit")
new_button_2.setAttribute("name", "chooseMove")
new_button_2.setAttribute("value", `${data[0]['moves'][1]}`)
new_button_2.textContent = `${data[0]['moves'][1]}`
} else {
new_para.innerText = `${data[1]['name']} used ${data[1]['move']} causing ${data[1]['damage']} damage.
${data[0]['name']} fainted!`
}
// console.log(data[2])
//console.log(data[0]['moves'])
console.log(`The user status is ${user_status}`)
return user_status
})
})
}
function userTurn(){
launchGameForm.addEventListener('submit', function(e) {
e.preventDefault();
// Create a form with user input.
const userFormData = new FormData(this);
// Add the name and value of the pressed button to the form.
userFormData.append(e.submitter.name, e.submitter.value);
// Send a fetch request of type POST.
const url = '/battle/launch/turn';
fetch(url, {
method: 'post',
body: userFormData
})
.then(response => response.json()) // Read the response as json.
.then(data => {
const new_para = launchGameForm.appendChild(document.createElement("p"))
let cpu_status = data[2]
if (cpu_status == "alive"){
new_para.innerText = `${data[0]['name']} used ${data[0]['move']} causing ${data[0]['damage']} damage.
${data[1]['name']}'s hp was reduced to ${data[1]['hp']}.`
} else {
new_para.innerText = `${data[0]['name']} used ${data[0]['move']} causing ${data[0]['damage']} damage.
${data[1]['name']}' fainted!`
}
console.log(`The cpu status is ${cpu_status}`)
return cpu_status
});
})
}
function battle(cpu_status, user_status) {
while (cpu_status == "alive" && user_status == "alive") {
cpuTurn()
userTurn()
}
}
battle(cpu_status, user_status)
Here is my battle.py code:
import requests
import random
from flask import request, session
import db_utils as db
def get_pokemon():
user_pokemon_name = request.form['userPokemonChoice']
session['pokemon_name'] = user_pokemon_name
user_pokemon = dict(name = f"{user_pokemon_name}", hp = get_hp_stat(user_pokemon_name), moves = get_initial_moves(user_pokemon_name) )
# launch_battle_button = request.form['launchBattle']
starter_pokemon =["bulbasaur", "charmander", "squirtle"]
"""later: cpu chooses pokemon with type advantage"""
available_pokemon = [pokemon for pokemon in starter_pokemon if pokemon != user_pokemon_name]
cpu_pokemon_name = random.choice(available_pokemon)
session['cpu_pokemon_name'] = cpu_pokemon_name
cpu_pokemon = dict(name = f"{cpu_pokemon_name}", hp = get_hp_stat(cpu_pokemon_name), moves = get_initial_moves(cpu_pokemon_name) )
poke_list = []
poke_list.append(user_pokemon)
poke_list.append(cpu_pokemon)
print(poke_list)
return poke_list
def get_response_from_api(pokemon_name):
api_url = f"https://pokeapi.co/api/v2/pokemon/{pokemon_name}"
response = requests.get(api_url)
data = response.json()
return data
def get_initial_moves(pokemon_name):
data = get_response_from_api(pokemon_name)
# filter data by level-learned-at: 1 and mover_learn_method: name: "level-up"
"""later: up to four moves are allocated to the pokemon"""
move_names = []
for i in range(len(data)):
if data['moves'][i]['version_group_details'][0]['move_learn_method']['name'] == "level-up" and data['moves'][i]['version_group_details'][0]['level_learned_at'] == 1:
move_names.append(data['moves'][i]['move']['name'])
return move_names
def get_hp_stat(pokemon_name):
# get pokemon hp
data = get_response_from_api(pokemon_name)
hp_stat = data['stats'][0]['base_stat']
return hp_stat
def damage():
return random.randint(1, 10)
def cpu_turn():
user_status = "alive"
cpu_pokemon_name = session['cpu_pokemon_name']
cpu_pokemon = dict(name = f"{cpu_pokemon_name}", hp = get_hp_stat(cpu_pokemon_name), moves = get_initial_moves(cpu_pokemon_name) )
user_pokemon_name = session['pokemon_name']
user_pokemon = dict(name = f"{user_pokemon_name}", hp = get_hp_stat(user_pokemon_name), moves = get_initial_moves(user_pokemon_name) )
if request.form['launchBattle']:
cpu_move = random.choice(cpu_pokemon['moves'])
cpu_damage = damage()
user_pokemon['hp']-= cpu_damage
cpu_pokemon_dict = dict(name = f"{cpu_pokemon_name}", move = cpu_move, damage = cpu_damage)
user_pokemon_dict = dict(name = f"{user_pokemon_name}", moves = user_pokemon['moves'], hp = user_pokemon['hp'])
cpu_move_result = []
cpu_move_result.append(user_pokemon_dict)
cpu_move_result.append(cpu_pokemon_dict)
session['user_hp'] = user_pokemon['hp']
if user_pokemon['hp'] > 0:
print(f"{user_pokemon['name']}'s hp was reduced to {user_pokemon['hp']} ")
print(" ")
cpu_move_result.append(user_status)
else:
print(f"{user_pokemon['name']} fainted!")
user_status = "fainted"
cpu_move_result.append(user_status)
return cpu_move_result
def user_turn():
cpu_status = "alive"
cpu_pokemon_name = session['cpu_pokemon_name']
user_pokemon_name = session['pokemon_name']
user_pokemon = dict(name = f"{user_pokemon_name}", hp = session['user_hp'], moves = get_initial_moves(user_pokemon_name) )
cpu_pokemon = dict(name = f"{cpu_pokemon_name}", hp = get_hp_stat(cpu_pokemon_name), moves = get_initial_moves(cpu_pokemon_name) )
user_move_choice = request.form['chooseMove']
user_damage = damage()
cpu_pokemon['hp']-=user_damage
cpu_pokemon_dict = dict(name = f"{cpu_pokemon_name}", moves = cpu_pokemon['moves'], hp = cpu_pokemon['hp'])
user_pokemon_dict = dict(name = f"{user_pokemon_name}", move = user_move_choice, damage = user_damage)
user_move_result = []
user_move_result.append(user_pokemon_dict)
user_move_result.append(cpu_pokemon_dict)
session['cpu_hp'] = cpu_pokemon['hp']
if cpu_pokemon['hp'] > 0:
print(f"{cpu_pokemon['name']}'s hp was reduced to {cpu_pokemon['hp']} ")
print(" ")
user_move_result.append(cpu_status)
else:
print(f"{cpu_pokemon['name']} fainted!")
cpu_status = "fainted"
user_move_result.append(cpu_status)
return user_move_result
Here is my app.py code:
from flask import Flask, render_template, request, session
from flask_session import Session
import battle
app = Flask(__name__ ,
static_url_path='',
static_folder='../frontend/static',
template_folder='../frontend/templates')
# CORS(app)
app.secret_key = 'BAD_SECRET_KEY'
@app.route("/")
def main():
return render_template('index.html')
@app.route("/battle")
def battle_page():
return render_template('battle.html')
@app.route("/battle", methods=['POST', 'GET'])
def get_user_cpu_pokemon():
return battle.get_pokemon()
@app.route("/battle/launch", methods=['GET', 'POST'])
def cpu_move():
return battle.cpu_turn()
@app.route("/battle/launch/turn", methods=['GET', 'POST'])
def user_move():
return battle.user_turn()
if __name__ == '__main__':
app.run(debug=True, port=5001)
I have tried looking into async functions – I’m not sure if that’s my issue or whether I need to generate new app routes in my app.py. I’ve definitely bitten off more than I can chew and have debated just rewriting the game logic in js but I’d like to know if what I want to do is at least possible!
Any help would be muchly appreciated.
user26782974 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.