Python game logic: "coins" variable is not incrementing - python

I am working on a game where the player is in search of treasure. Everything works perfectly, although my money system does not work. I need my code to work so that if the user lands on a treasure chest, they gain 10 extra coins. However, their number of coins is being set to 10 instead of adding 10.
import easygui
import time
from random import *
# Set up Initial Variables
Money = 0
grid = []
character = "X"
# player_loc will hold the x, y location of the player
player_loc = (0, 0)
# These are a mapping of direction
NORTH = "N"
SOUTH = "S"
EAST = "E"
WEST = "W" #All variables used for Later on
Treasure = "T"
Goblin = "G"
def menu(): #function
msg = "Would you like to...?" #Users choice to start game
buttons = ["start", "quit"]
while True:
title = "Menu"
selection = easygui.buttonbox(msg, title , buttons)
if selection == "quit":
exit()
elif selection == "start": #If users input is to start the game the all of this appears("Welcome to the treasure hunt game!")
easygui.msgbox("These are the rules! You have a choice of a grid ranging from a 3x3 choice to a 20x20 choice")
easygui.msgbox("In these grids, bandits and treasure chests will spawn at random locations, hidden to you.")
easygui.msgbox("You will have a choice of the amount of goblins and treasures you would like to spawn in, ranging from 1-2")
easygui.msgbox("You will move around the map, in search of treasures which will give you 10 gold. Although landing on a goblin would deduct the amount of gold to 0.")
easygui.msgbox("Furthurmore, just deciding on a position you would like to move to, would give you an extra 1 piece of gold.")
easygui.msgbox("You can only find the same treasure chest two times before it's replaced by a bandit.")
easygui.msgbox("To check the amount of gold you have and the amount of bandits and treasure chests in the grid. Simply type 'status'")
easygui.msgbox("Don't forget! If you have collected all the treasure chests and you don't have 100 gold, you lose the game!")
easygui.msgbox("Good luck, you will now be entered into the game")
easygui.msgbox("Ok! let's jump into the game!")
setupGrid()
Chests_and_Goblins()
def setupGrid(): #New function for creating grid
global grid #Adding/creating global variables
global row
global N
N = easygui.integerbox("How big would you like the grid to be?") #User input
while int(N) > 20: #Changing N to an integer so computer understamds
N = easygui.intergerbox("That number is too high, The grid has to be at a size of under 20x20")
else:
while int(N) < 3 : # Asking the user to input again as number is too high or low
N = easygui.integerbox("That number is too low, the grid has to be a size of over 3x3. Please try again")
for x in range(0, (int(N))):#For everything in range N
row = [] #The N amount of rows are created
for y in range(0, (int(N))): #For everything in range N
if x == player_loc[0] and y == player_loc[1]: #If the positions is equal to th player location
row.append(character) # Add the character in
else:
row.append('O') #Add the same amount of 0's as N
grid.append(row)
def Chests_and_Goblins(): #Function used for adding the treasures and goblins in the grid
global grid
global row
global Treasure
B = easygui.enterbox(" How many chests would you like in the grid? The amount of chests you like is given by the amount of C's")
F = easygui.enterbox(" How many Bandits would you like in the grid? The amount of bandits you like is given by the amount of B's")
for each in B:
grid[randint(0, int(N)-1)][randint(0, int(N)-1)] = Treasure
for each in F:
grid[randint(0, int(N)-1)][randint(0, int(N)-1)] = Goblin
gridRunner()
def moveSouth(n):
global player_loc
grid[player_loc[0]][player_loc[1]] = "O"
grid[player_loc[0] + n][player_loc[1]] = character
player_loc = (player_loc[0] + n, player_loc[1])
money()
def moveNorth(n):
global player_loc
grid[player_loc[0]][player_loc[1]] = "O"
grid[player_loc[0] - n][player_loc[1]] = character
player_loc = (player_loc[0] - n, player_loc[1])
money()
def moveEast(n):
global player_loc
grid[player_loc[0]][player_loc[1]] = "O"
grid[player_loc[0]][player_loc[1] + n] = character
player_loc = (player_loc[0], player_loc[1] + n)
money()
def moveWest(n):
global player_loc
grid[player_loc[0]][player_loc[1]] = "O"
grid[player_loc[0]][player_loc[1] - n] = character
player_loc = (player_loc[0], player_loc[1] - n)
money()
def gridRunner():
while True:
for row in grid:
print (row)
switch = {NORTH : moveNorth,
SOUTH : moveSouth,
EAST : moveEast,
WEST : moveWest }
print (" ")
P = easygui.enterbox("What direction would you like to move in? North (N), South(S), East(E) or West(W)?")
if P not in switch:
easygui.msgbox("invalid move")
continue
distance = easygui.integerbox("How far would you like to move in this direction? (blocks are the units)")
switch[P](distance)
def money():
global player_loc
global character
global Treasure
if player_loc == Treasure:
print("Well done, You have gained coins")
money = 10
else:
print ("You got nothing")
money = 0
menu()

In this part here:
if player_loc == Treasure:
print("Well done, You have gained coins")
money = 10
You are setting the money to 10, not adding 10. All you need to do is:
money += 10
Also make sure def money(): isn't indented; it won't work as it currently is indented.

It looks like you have to indent the code under your money() function first:
def money():
global player_loc
global character
global Treasure
if player_loc == Treasure:
print("Well done, You have gained coins")
money = 10
else:
print ("You got nothing")
money = 0

Related

Error with a player turn ending loop in the Zombie Dice game

I'm trying to develop a code for the zombie dice game.
My problem is when the first player replies that he doesn't want to continue playing.
The game ends and I can't get the second player to play. Can someone help me?
import random
print("========== ZOMBIE DICE (PROTÓTIPO SEMANA 4) ==========")
print("========= WELCOME TO THE ZOMBIE DICE GAME! ========")
numeroJogadores = 0
while numeroJogadores < 2:
numeroJogadores = int(input("Enter the number of players: "))
print(numeroJogadores)
if numeroJogadores < 2:
print("NOTICE: You must have at least 2 players to continue!")
listaJogadores = []
for i in range(numeroJogadores):
nome = str(input("\nEnter player name: " + str(i+1) + ": "))
listaJogadores.append(nome)
print(listaJogadores)
dadoVerde = ("brain", "steps", "brain", "shot", "steps", "brain")
dadoAmarelo = ("shot", "steps", "brain", "shot", "steps", "brain")
dadoVermelho = ("shot", "steps", "shot", "brain", "steps", "shot")
listaDados = [dadoVerde, dadoVerde, dadoVerde, dadoVerde, dadoVerde, dadoVerde,
dadoAmarelo, dadoAmarelo, dadoAmarelo, dadoAmarelo,
dadoVerde, dadoVermelho, dadoVermelho]
print("\nSTARTING THE GAME...")
jogadorAtual = 0
dadosSorteados = []
tiros = 0
cerebros = 0
passos = 0
while True:
print("PLAYER TURN: ", listaJogadores[jogadorAtual])
for i in range (3):
numeroSorteado = random.randint(0, 12)
dadoSorteado = listaDados[numeroSorteado]
if (dadoSorteado == dadoVerde):
corDado = "Green"
elif (dadoSorteado == dadoAmarelo):
corDado = "Yellow"
else:
corDado = "Red"
print("Dice Drawn: ", corDado)
dadosSorteados.append(dadoSorteado)
print("\nThe faces drawn were: ")
for dadoSorteado in dadosSorteados:
numeroFaceDado = random.randint(0,5)
if dadoSorteado[numeroFaceDado] == "brain":
print("- brain (you ate a brain)")
cerebros = cerebros + 1
elif dadoSorteado[numeroFaceDado] == "tiro":
print("- shot (you got shot)")
tiros = tiros + 1
else:
print("- steps (a victim escaped)")
passos = passos + 1
print("\nCURRENT SCORE: ")
print("brins: ", cerebros)
print("shots: ", tiros)
if cerebros >= 13:
print("Congratulations, you've won the game!")
break
elif tiros >= 3:
print("You lost the game!")
break
else:
continuarTurno = str(input("\nNOTICE: Do you want to continue playing dice? (y=yes / n=no)")).lower()
if continuarTurno == "n":
jogadorAtual = jogadorAtual + 1
dadossorteados = 0
tiros = 0
cerebros = 0
passos = 0
if jogadorAtual > numeroJogadores:
print("Finalizing the game prototype")
else:
print("Starting another round of the current turn")
dadossorteados = []
print("======================================================")
print("===================== END OF THE GAME ====================")
print("======================================================")
Does anyone know what I'm doing wrong?
I'm new as a programmer. If anyone knows how to help me with this problem, I would be grateful.
EDIT: Well now the code just works. I can switch players just fine, but if you go through all the characters it crashes again since jogadorAtual gets too big for listaJogadores. I don't quite understand the game, but assuming you want to start back with the first player, an elegant way you can accomplish that is by doing modulus with the % operator, which divides two numbers but returns the remainder. If you divide the number of players by the size of listaJogadores, you'll always get a number inside listaJogadores's range.
# Change this...
print("PLAYER TURN: ", listaJogadores[jogadorAtual])
# ...to this
print("PLAYER TURN: ", listaJogadores[jogadorAtual % len(listaJogadores)])
If that's not what you need for your game, let me know.
Original answer: Is the game ending or is it crashing? When I run the game, it always crashes with:
File "C:\Users\me\Desktop\Untitled-1.py", line 56, in <module>
diceDrawns.append(diceDrawn)
AttributeError: 'int' object has no attribute 'append'
This is because after looping, you try to do diceDrawns.append(), but you've already replaced the diceDrawns list with an integer on line 87. I'm not sure if you meant to replace diceDrawn instead, but that's definitely the source of the problem.
An unrelated note: You can do += as a shorthand way to increment a variable by a certain amount, so you can replace a lot of instances of things like currentPlayer = currentPlayer + 1 with currentPlayer += 1, and the same can be done with any operator, so you could also do things like -= or *=

Program will not stop when the conditions are passed

I'm writing a sum up game where two players will take turns picking a random number in the range (1,9), no repeated number allowed. If the first player picks [7, 2, 3, 5], he will win because 7+3+5 = 15
So my question is why doesn't the program stop when first_player has a sum of inputs that == 15
Below is the readme file
The game doesn't stop when first player's inputs equal 15 because you ask for second player's input regardless of whether the first player won. You can see this in your testing code, where you have two while statements for each player's input. If you complete that round with second player's input, your program works and stops there. To stop when a player wins on input, just add the conditional check to break out of main loop before asking for next player's input.
Your script is too verbose. If you made it more dynamic, with reusable logic, it becomes much easier to work with. I rewrote your game as an example.
notes:
All the game states are reused in fstrings, as dict keys, and even to represent the player
The game loop (update()) represents a single turn, and the player that turn corresponds to is toggled at the end of the loop
make_move also represents one turn
the entire game is contained in the class
reset() is used to clear the window, reset all the game properties, and start the loop, but the very first time it is called it acts as an initializer for all of the game properties.
There is never going to be an instance where both players have 15 points
import os
UNFINISHED = "unfinished"
DRAW = "draw"
FIRST_WON = "First"
SECOND_WON = "Second"
CLEAR = lambda: os.system('cls') #windows only
class AddThreeGame:
#property
def current_state(self):
return self.__state
#property
def player(self):
return self.__rotation[self.__player]
def __init__(self):
self.__rotation = [FIRST_WON, SECOND_WON]
self.__states = {
UNFINISHED:'We have unfinished business, come back for more\n',
DRAW:'Draw game\n',
FIRST_WON:'First player won this game!!!\n',
SECOND_WON:'Second player won this game!!!\n',
}
self.reset()
def make_move(self, player, number):
if number not in range(1, 10) or number in self.__input:
return False
self.__input.append(number)
self.__players[self.player].append(number)
if len(self.__players[self.player]) >= 3:
L = self.__players[self.player]
for i in range(0, len(L)-2):
for j in range(i+1, len(L)-1):
for k in range(j+1, len(L)):
if (L[i] + L[j] + L[k]) == 15:
self.__state = player
return True
if len(self.__input) == 9:
self.__state = DRAW
return True
def update(self):
while True:
num = int(input(f'{self.player} player please enter a number from 1 to 9: '))
while True:
if self.make_move(self.player, num):
break
else:
num = int(input("Wrong input, please try a different number: "))
if self.current_state == UNFINISHED:
if self.__player == 1: #technically, this is player 2
print(self.__states[self.current_state])
#next player
self.__player = (self.__player + 1) % 2
else:
print(self.__states[self.current_state])
break
if input('Play Again? (y or n): ') == 'y':
self.reset()
def reset(self):
CLEAR()
self.__player = 0
self.__input = []
self.__state = UNFINISHED
self.__players = {
FIRST_WON:[],
SECOND_WON:[],
}
self.update()
if __name__ == '__main__':
AddThreeGame()

I'm stuck in the creating of a Board game in python

I have an excercise to do and I'm stuck. It's the board game Alak, not much known, that I have to code in python. I can link the execrcise with the rules so you can help me better. The code has the main part and the library with all the procedures and function.
from Library_alak import *
n = 0
while n < 1:
n = int(input('Saisir nombre de case strictement positif : '))
loop = True
player = 1
player2 = 2
removed = [-1]
board = newboard(n)
display(board, n)
while loop:
i = select(board, n, player, removed)
print(i)
board = put(board, player, i)
display(board, n)
capture(board, n, player, player2)
loop = True if again(board, n, player, removed) is True else False
if player == 1 and loop:
player, player2 = 2, 1
elif player == 2 and loop:
player, player2 = 1, 2
win(board, n)
print(win(board, n))
And here is the library:
def newboard(n):
board = ([0] * n)
return board
def display(board, n):
for i in range(n):
if board[i] == 1:
print('X', end=' ')
elif board[i] == 2:
print('O', end=' ')
else:
print(' . ', end=' ')
def capture(board, n, player, player2):
for place in range(n):
if place == player:
place_beginning = place
while board[place] != player:
place_end = place
if board[place + x] == player:
return board
else:
return board
def again(board, n, player, removed):
for p in board(0):
if p == 0:
if p not in removed:
return True
else:
return False
def possible(n, removed, player, i, board):
for p in range(n + 1):
if p == 1:
if board[p-1] == 0:
if p not in removed:
return True
else:
return False
def win(board, n):
piecesp1 = 0
piecesp2 = 0
for i in board(0):
if i == 1:
piecesp1 += 1
else:
piecesp2 += 1
if piecesp1 > piecesp2:
print('Victory : Player 1')
elif piecesp2 > piecesp1:
print('Victory : Player 2')
else:
return 'Equality'
def select(board, n, player, removed):
loop = True
while loop:
print('player', player)
i = int(input('Enter number of boxes : '))
loop = False if possible(n, removed, player, i, board)is True else True
return i
def put(board, player, i):
i -= 1
if board[i] == 0:
if player == 1:
board[i] = 1
return board
else:
board[i] = 2
return board
else:
put(board, player, i)
So my problems here are that I have few errors, the first one is that when I enter the number '1' when asked to enter a number of boxes ( which is the place to play on ) nothing happens. Then when entering any other number, either the error is : if board[place + x] == player:
NameError: name 'x' is not defined
or there seems to be a problem with the : if board[place + x] == player:
NameError: name 'x' is not defined
I would appreciate a lot if anyone could help me. I'm conscious that it might not be as detailed as it should be and that you maybe don't get it all but you can contact me for more.
Rules of the Alak game:
Black and white take turns placing stones on the line. Unlike Go, this placement is compulsory if a move is available; if no move is possible, the game is over.
No stone may be placed in a location occupied by another stone, or in a location where a stone of your own colour has just been removed. The latter condition keeps the game from entering a neverending loop of stone placement and capture, known in Go as ko.
If placing a stone causes one or two groups of enemy stones to no longer have any adjacent empty spaces--liberties, as in Go--then those stones are removed. As the above rule states, the opponent may not play in those locations on their following turn.
If placing a stone causes one or two groups of your own colour to no longer have any liberties, the stones are not suicided, but instead are safe and not removed from play.
You shouldn't use "player2" as a variable, there's an easier way, just use "player" which take the value 1 or 2 according to the player. You know, something like that : player = 1 if x%2==0 else 2
and x is just a increasing int from 0 until the end of the game.

How do I add points to a total in treasure hunt game?

So Im making a treasure hunt game in which the user is placed on a grid as 'P' and can move around to collect coins from chests ('X') which are shown on the grid. On the same gird, bandits('B') are also present which take away all previously collected coins.
Now, Ive gotten as far as allowing the player to move around the board but dont know how to add coins to the already created coins variable when the player lands on the treasure.
This is the relevant part of the code which randomly placed 5 Bandits and 10 treasure chests on the board:
def bandits(board):
added_bandits = 0
while added_bandits < 5:
x_bandit = r.randint(0,7)
y_bandit = r.randint(0,7)
if board[x_bandit][y_bandit] == 'O':
board[x_bandit][y_bandit] = 'B'
added_bandits = added_bandits + 1
def treasures(board):
added_treasure = 0
while added_treasure < 10:
x_treasure = r.randint(0,7)
y_treasure = r.randint(0,7)
if board[x_treasure][y_treasure] == 'O':
board[x_treasure][y_treasure] = 'X'
added_treasure = added_treasure + 1
I would create a class Player, where you store this information and that manage the adding/removing of the coins of the player.
class Player(object):
def __init__(self, name):
self.playername = name
self.total_coins = 0
def add_coins(self, number):
self.total_coins += number
def remove_coins(self, number):
self.total_coins -= number
def move(self, move_data):
#implement here the players's move semantic
def print_total_coins(self):
print("Total coins %d" % (self.total_coins))
That way you can get the total coins score like this:
player1 = Player("Player 1")
player1.print_total_coins()
I would further encapsulate the bandits and the treasures in classes too.

Making simple game of Battleship

I am trying to implement a simple Battleship game. It is a one player game versus the computer. So far I am only able to input the positions of my ship without my program breaking lol. I am trying to generate random coordinates for the computer, but I can not figure out the logic to place them beside each other (vertical or horizontal) without overlapping them.
I still need conditions for sunken ships and when the game is over, but I don't know how to go about it. My best (and only) process was to loop through the elements of each of the players and computers hit boards (the hits recorded for both computer and player) and count if there is 5 'A', 3 'C', and 2 'D' on the board. If there is, then that player wins.
from random import random, randrange
def emptyBoard():
empBoard = [ ['*','*','*','*','*','*','*'],
['*','*','*','*','*','*','*'],
['*','*','*','*','*','*','*'],
['*','*','*','*','*','*','*'],
['*','*','*','*','*','*','*'],
['*','*','*','*','*','*','*'],
['*','*','*','*','*','*','*']]
return empBoard
def placeMyShips(myBoard):
for a in range(5):
x,y = eval(input('Enter coordinate of Aircarrier: '))
myBoard [x][y] = 'A'
for c in range(3):
x1,y1 = eval(input('Enter coordinate of Cruiser: '))
myBoard [x1][y1] = 'C'
for d in range(2):
x2,y2 = eval(input('Enter coordinate of Destroyer: '))
myBoard [x2][y2] = 'D'
print ('\tMy Fleet')
for i in myBoard:
print (i)
return myBoard
def placeCompShips(compBoard):
for a in range (5):
x= randrange(0,5)
y= x+1
compBoard[x][y]= 'A'
for c in range (3):
x1= randrange(0,5)
y1= x1+1
if compBoard [x1][y1] == '*':
compBoard[x1][y1]= 'C'
for d in range (2):
x2= randrange(0,5)
y2= x2+1
if compBoard [x2][y2] =='*':
compBoard[x2][y2] = 'D'
return compBoard
def myMoves(compBoard,myHitBoard):
x,y = eval(input('Enter your move as coordinate: '))
if compBoard[x][y] == 'A':
myHitBoard[x][y] =='A'
print('Computer: You hit my Aircarrier')
elif compBoard [x][y] == 'C':
myHitBoard[x][y] =='C'
print('Computer: You hit my Cruiser')
elif compBoard [x][y] == 'D':
myHitBoard[x][y] =='D'
print('Computer: You hit my Destroyer')
else:
myHitBoard [x][y] = 'M'
print('Computer: Shot was a miss')
print ('My hits on the computer')
for i in myHitBoard:
print (i)
return myHitBoard
def compMoves(myBoard,compHitBoard):
x,y = eval(input('Enter your move as coordinate '))
if myBoard[x][y] == 'A':
compHitBoard [x][y] = 'A'
print('Player: You hit my Aircarrier')
elif myBoard [x][y] == 'C':
compHitBoard[x][y] =='C'
print('Player: You hit my Cruiser')
elif myBoard [x][y] == 'D':
compHitBoard[x][y] =='D'
print('Player: You hit my Destroyer')
else:
compHitBoard [x][y] = 'M'
print('Player: Shot was a miss')
return compHitBoard
def intro():
print('BATTLESHIP')
print('This is a one player game versus the computer')
def main():
intro()
placeMyShips(emptyBoard())
placeCompShips(emptyBoard())
main()
I think it's unlikely that you're going to get a good answer to this question because of its breadth, however what I THINK you're trying to do with your parameter issue is more like:
def main():
intro()
my_board = placeMyShips(emptyBoard())
my_hit_board = emptyBoard()
comp_board = placeCompShips(emptyBoard())
comp_hit_board = emptyBoard()
myMoves(comp_board, my_hit_board)
Note also my variable names. Functions shouldn't use mixedCase names except where it's already established in that project (e.g. this new project and every other should use lowercase_names) as per PEP8

Categories

Resources