How to delete lines of output, python? - python-3.x

So here is my code:
Krotos = [100, 25]
Sephiroth = [100, 25]
endGame = 0
def checkHealth():
global endGame
if Krotos[0] == 0:
print("Game Over")
endGame = 1
if Sephiroth[0] == 0:
print("You Win")
endGame = 1
def krotosAttack():
Sephiroth[0] -= Krotos[1]
def printHealth():
print("Krotos:", Krotos[0])
print("Sephiroth:", Sephiroth[0])
def sephirothAttack():
Krotos[0] -= Sephiroth[1]
def checkInput():
print("Click 1 for attack\nClick 2 for shield")
x = int(input(":"))
if x == 1:
krotosAttack()
while endGame == 0:
checkInput()
checkHealth()
if endGame == 0:
sephirothAttack()
checkHealth()
printHealth()
My output is:
Click 1 for attack
Click 2 for shield
:1
Krotos: 75
Sephiroth: 75
Click 1 for attack
Click 2 for shield
:
How can I get rid of the first three lines so it only shows the newest information? Any new ideas would be useful. I have tried using google but I can't find anything.

Try this below :
Krotos = [100, 25]
Sephiroth = [100, 25]
endGame = 0
def clear():
import os
os.system("clear") # Linux
os.system("cls") # Windows
def checkHealth():
global endGame
if Krotos[0] == 0:
print("Game Over")
endGame = 1
if Sephiroth[0] == 0:
print("You Win")
endGame = 1
def krotosAttack():
Sephiroth[0] -= Krotos[1]
def printHealth():
print("Krotos:", Krotos[0])
print("Sephiroth:", Sephiroth[0])
def sephirothAttack():
Krotos[0] -= Sephiroth[1]
def checkInput():
print("Click 1 for attack\nClick 2 for shield")
x = int(input(":"))
if x == 1:
krotosAttack()
clear() # -------------> Call clear function after your input
while endGame == 0:
checkInput()
checkHealth()
if endGame == 0:
sephirothAttack()
checkHealth()
printHealth()

You can clear the console after every attack:
import os
os.system("cls") #windows
os.system("clear") #linux

Related

I've tried running the code but it says list index is out of range

from typing import List
# You are given an integer n, denoting the no of people who needs to be seated, and a list of m integer seats, where 0 represents a vacant seat. Find whether all people can be seated, provided that no two people can sit together
When I run this code in geeks for geeks for submission I get a error that List index is out of range.
but seems to work fine when I run it as a script.
class Solution:
def is_possible_to_get_seats(self, n: int, m: int, seats: List[int]) -> bool:
vacant_seats = 0
if len(seats) == 2:
if seats[0] or seats[1] == 1:
print(seats)
return False
else:
print(seats)
return True
else:
for x in range(len(seats)):
if x == 0:
if seats[x] == 0 and seats[x+1] == 0:
seats[x] = 1
vacant_seats += 1
elif x == len(seats)-1:
if seats[x] == 0 and seats[x-1] == 0:
seats[x] = 1
vacant_seats += 1
else:
if seats[x] == 0:
if seats[x+1] == 0 and seats[x-1] == 0:
seats[x] = 1
vacant_seats += 1
if vacant_seats < n:
return False
else:
return True
# {
# Driver Code Starts
class IntArray:
def __init__(self) -> None:
pass
def Input(self, n):
arr = [int(i) for i in input().strip().split()] # array input
return arr
def Print(self, arr):
for i in arr:
print(i, end=" ")
print()
if __name__ == "__main__":
t = int(input())
for _ in range(t):
n = int(input())
m = int(input())
seats = IntArray().Input(m)
obj = Solution()
res = obj.is_possible_to_get_seats(n, m, seats)
result_val = "Yes" if res else "No"
print(result_val)
# } Driver Code Ends

My boolean flag isn't triggering when it's supposed to

At the play_again input, whenever I input "n" to end the loop, python seems to ignore it and prints :
Your cards: [x, x], current score: xx
Computers first card: x.
Would you like to draw another card? Press 'y' to draw or 'n' to stand.
Even though I have set end_game back to True.
What gives?
import random
from art import logo
from replit import clear
def deal_card():
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
card = random.choice(cards)
return card
def calculate_score(card_list):
if len(card_list) == 2 and sum(card_list) == 21:
return 0
if 11 in card_list and sum(card_list) > 21:
card_list.remove(11)
card_list.append(1)
return sum(card_list)
def compare(user, computer):
if user == computer:
return "I'ts a draw!"
elif user == 0:
return "You win with a BlackJack!"
elif computer == 0:
return "Computer wins with a BlackJack!"
elif computer > 21:
return "You win! Computer busts."
elif user > 21:
return "Computer wins, you bust!"
elif user > computer:
return "You win!"
else:
return "You lose!"
def main_loop():
print(logo)
user_cards = []
computer_cards = []
game_end = False
for _ in range(2):
user_cards.append(deal_card())
computer_cards.append(deal_card())
while not game_end:
user_score = calculate_score(user_cards)
computer_score = calculate_score(computer_cards)
print(f"Your cards: {user_cards}, current score: {user_score}")
print(f"Computers first card: {computer_cards[0]}.")
if user_score == 0 or computer_score == 0 or user_score > 21:
game_end = True
else:
play_again = input("Would you like to draw another card? Press 'y' to draw or 'n' to stand.")
if play_again == "y":
user_cards.append(deal_card())
else:
end_game = True
while computer_score != 0 and computer_score < 17:
computer_cards.append(deal_card())
computer_score = calculate_score(computer_cards)
print(f"Your final hand: {user_cards}, Your final score{user_score}.")
print(f"Computers final hand: {computer_cards}, Computers final score {computer_score}." )
print(compare(user_score, computer_score))
while input("Would you like to play a game of BlackJack?: ") == 'y':
clear()
main_loop()
else:
print('Goodbye!')
quit()
Please check your variable name game_end in "while not game_end:" loop,
if user_score == 0 or computer_score == 0 or user_score > 21:
game_end = True
else:
play_again = input("Would you like to draw another card? Press 'y' to draw
or 'n' to stand.")
if play_again == "y":
user_cards.append(deal_card())
else:
end_game = True
I think it's "game_end" in else: , you put end_game , please change it, other function working fine.

python program error while combine two program

i have wrote two program, one is tic tac toe,one is guest number, and it is fine when run separately and when i combine them( my aim is when to people win in the guest number game, the people can pick a box in tic tac toe)
It work normally and when it start to select to second box, the error occur
it is show asz follow
Traceback (most recent call last):
File "C:\Users\User\Desktop\try3.py", line 207, in
winner = single_game(options[choice-1])
File "C:\Users\User\Desktop\try3.py", line 125, in single_game
player_pos[cur_player].append(move)
KeyError: <main.Player object at 0x000001D6C01CC730>
can anyone see what wrong with my program. Thanks
import random
from random import randint
class Player():
def __init__(self, player_name):
self.name = player_name
self.score = 0
self.guess = 0
def enterGuess(self,rand, play):
if play == True:
self.guess = int(input(self.name+ " enter a guess 1-100:"))
if self.guess == rand:
print ("Correct Guess")
play = False
self.score = self.score + 1
elif self.guess < rand:
print ("Too low")
else:
print ("Too high")
return play
def playGame():
player1.score = 0
player1.guess = 0
player2.score = 0
player2.guess = 0
randNum = randint(1,100)
play = True
print ("\nNew game")
while play:
play=player1.enterGuess(randNum, play)
play=player2.enterGuess(randNum, play)
def coinToss():
flip = random.randint(0, 1)
if (flip == 0):
return("Head")
else:
return("Tail")
print(coinToss)
def print_tic_tac_toe(values):
print("\n")
print("\t | |")
print("\t {} | {} | {}".format(values[0], values[1], values[2]))
print('\t_____|_____|_____')
print("\t | |")
print("\t {} | {} | {}".format(values[3], values[4], values[5]))
print('\t_____|_____|_____')
print("\t | |")
print("\t {} | {} | {}".format(values[6], values[7], values[8]))
print("\t | |")
print("\n")
def print_scoreboard(score_board):
print("\t--------------------------------")
print("\t SCOREBOARD ")
print("\t--------------------------------")
players = list(score_board.keys())
print("\t ", players[0], "\t ", score_board[players[0]])
print("\t ", players[1], "\t ", score_board[players[1]])
print("\t--------------------------------\n")
def check_win(player_pos, cur_player):
soln = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]]
for x in soln:
if all(y in player_pos[cur_player] for y in x):
return True
return False
def check_draw(player_pos):
if len(player_pos['X']) + len(player_pos['O']) == 9:
return True
return False
def single_game(cur_player):
values = [' ' for x in range(9)]
player_pos = {'X':[], 'O':[]}
while True:
print_tic_tac_toe(values)
try:
print("The player ", cur_player, " turn. Which box? : ", end="")
move = int(input())
except ValueError:
print("Wrong Input!!! Try Again")
continue
if move < 1 or move > 9:
print("Wrong Input!!! Try Again")
continue
if values[move-1] != ' ':
print("Place already filled. Try again!!")
continue
values[move-1] = cur_player
player_pos[cur_player].append(move)
if check_win(player_pos, cur_player):
print_tic_tac_toe(values)
print( cur_player, " has won the game!!")
print("\n")
return cur_player
if check_draw(player_pos):
print_tic_tac_toe(values)
print("Game Drawn")
print("\n")
return 'D'
playGame()
if int(player1.score)>int(player2.score):
cur_player = player1
else:
cur_player = player2
if __name__ == "__main__":
print ("Player 1")
player1=Player(input("Enter name:"))
print ("Player 2")
player2=Player(input("Enter name:"))
playGame()
if int(player1.score)>int(player2.score):
cur_player = player1
else:
cur_player = player2
player_choice = {'X' : "", 'O' : ""}
options = ['X', 'O']
score_board = {player1: 0, player2: 0}
print_scoreboard(score_board)
while True:
print("Turn to choose for", cur_player)
print("Enter 1 for X")
print("Enter 2 for O")
print("Enter 3 to Quit")
try:
choice = int(input())
except ValueError:
print("Wrong Input!!! Try Again\n")
continue
if choice == 1:
player_choice['X'] = cur_player
if cur_player == player1:
player_choice['O'] = player2
else:
player_choice['O'] = player1
elif choice == 2:
player_choice['O'] = cur_player
if cur_player == player1:
player_choice['X'] = player2
else:
player_choice['X'] = player1
elif choice == 3:
print("Final Scores")
print_scoreboard(score_board)
break
else:
print("Wrong Choice!!!! Try Again\n")
winner = single_game(options[choice-1])
if winner != 'D' :
player_won = player_choice[winner]
score_board[player_won] = score_board[player_won] + 1
print_scoreboard(score_board)

Can't break the while loop in python

I am building a tic-tac-toe. I have almost finished it but I cannot break the while loop in the end. I have turned win into True. But the if statement in the while loop is not working.
board = [[1,2,3],[4,"X",6],[7,8,9]]
win = False
def DisplayBoard(board):
def printborder():
print("+-------+-------+-------+")
def printline():
print("| | | |")
def printitem(board,row):
print("| ",board[row][0]," | ",board[row][1]," | ",board[row][2]," |", sep="")
printborder()
printline()
printitem(board,0)
printline()
printborder()
printline()
printitem(board,1)
printline()
printborder()
printline()
printitem(board,2)
printline()
printborder()
def EnterMove(board):
while True:
move = int(input("Enter your move: "))
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j]==move:
board[i][j]="O"
return None
def MakeListOfFreeFields(board):
freefield = []
for i in range(len(board)):
for j in range(len(board[i])):
for k in range(1,10):
if board[i][j] == k:
freefield.insert(0,k)
return freefield
def VictoryFor(board, sign):
def whowin(sign):
if sign == "O":
print("Player wins.")
win = True
elif sign == "X":
print("Computer wins.")
win = True
def checkvertical(board):
for i in range(3):
if board[0][i]==board[1][i]==board[2][i]:
whowin(sign)
def checkhorizontal(board):
for i in range(3):
if board[i][0]==board[i][1]==board[i][2]:
whowin(sign)
def checkdiagonal(board):
if board[0][0]==board[1][1]==board[2][2] or board[0][2]==board[1][1]==board[2][0]:
whowin(sign)
checkvertical(board)
checkhorizontal(board)
checkdiagonal(board)
def DrawMove(board):
from random import randrange
while True:
ran = randrange(1,10)
if ran in MakeListOfFreeFields(board):
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j]==ran:
board[i][j]="X"
return None
DisplayBoard(board)
while True:
EnterMove(board)
DisplayBoard(board)
VictoryFor(board, "O")
if win==True:
break
DrawMove(board)
DisplayBoard(board)
VictoryFor(board, "X")
if win==True:
break
print("ended")
fhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh fhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh fhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh fhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
In your whowin function (inside of VictoryFor) you simply create a local win variable. If you want to refer to the global one, you need to tell Python to do so:
def whowin(sign):
global win # <---- add this
if sign == "O":
print("Player wins.")
win = True
elif sign == "X":
print("Computer wins.")
win = True

it shows"line 42, in <module> if input_ !='no': NameError: name 'input_' is not defined" when i giv no in first line.How can i correct it?

Its showing"line 42, in
if input_ !='no':
NameError: name 'input_' is not defined" error when i input 'no'
The code is :
def rock_paper_scissors():
comp_score = your_score = 0
y,z="This is a rockpaper scissors game. ","Do you wish to play"
x= ["rock","paper","scissors"]
input_=input(y+z+"?")
if input_ == "no":
return
rock_paper_scissors()
if input_ !='no':
a=input("Do you wanna play again?")
How can i rectify it? (this is just a small part of the entire program but i think this should do...)
Variable input_ is initialised inside function rock_paper_scissors() which means outside of it (function scope) is undefined. So we need to put it inside function or make input_ global.
def rock_paper_scissors():
comp_score = your_score = 0
y, z = "This is a rock paper scissors game. ", "Do you wish to play"
x= ["rock", "paper", "scissors"]
input_=input(y + z + "?")
if input_ == "no":
return
else: # no need for: if input_ != "no"
a = input("Do you wanna play again?")
rock_paper_scissors()
Hope this helps.
Here is my take on it, still needs some work, it functional...
# Tested via Python 3.7.4 - 64bit, Windows 10
# Author: Dean Van Greunen
# License: I dont care, do what you want
####################################
# Some Defines
####################################
# imports
import random
# global vars
comp_score = 0
your_score = 0
input_ = ''
ai_input = ''
# strings
string_1 = 'This is a rockpaper scissors game.'
question_1 = 'Do you wish to play? '
question_2 = 'Enter your move: '
question_3 = 'Do you wanna play again? '
string_4 = 'Valid Moves: '
string_5 = 'Thank you for playing!'
string_6 = 'Scores: Player {0} V.S. AI {1}'
yes = 'yes'
no = 'no'
# vaild moves
moves = ["rock","paper","scissors"]
####################################
# Code Setup
####################################
def displayWinner(player_move_str, ai_move_str):
# Vars
winner = ''
tie = False
# Winner Logic
if player_move_str == ai_move_str:
tie = True
elif player_move_str == 'paper' and ai_move_str == 'rock':
winner = 'Player'
elif player_move_str == 'scissor' and ai_move_str == 'rock':
winner = 'AI'
elif player_move_str == 'rock' and ai_move_str == 'paper':
winner = 'AI'
elif player_move_str == 'scissor' and ai_move_str == 'paper':
winner = 'Player'
elif player_move_str == 'rock' and ai_move_str == 'scissor':
winner = 'Player'
elif player_move_str == 'paper' and ai_move_str == 'scissor':
winner = 'AI'
# display Logic
if tie:
print('It Was A Tie!')
else:
global your_score
global comp_score
if winner == 'AI':
comp_score = comp_score + 1
elif winner == 'Player':
your_score = your_score + 1
print(winner + ' Won!')
def start():
global your_score
global comp_score
print(string_1)
print(string_6.format(your_score, comp_score))
input_ = input(question_1)
if input_ == yes:
print(string_4)
[print(x) for x in moves]# make sure input is valid.
input_ = input(question_2)
ai_input = random.choice(moves) # let AI pick move
print('AI Picked: ' + ai_input)
displayWinner(input_, ai_input)
input_ = input(question_3) # Play Again?
if input_ == yes:
start() # Restart Game (Recursive Call)
else:
print(string_5) # Thank you Message
####################################
# Game/Script Entry Point/Function
####################################
start()
Thanks yall. Fixed my program. Now it goes like:
import time
import random
input_ =""
def rock_paper_scissors():
comp_score = your_score = 0
y,z="This is a rockpaper scissors game. ","Do you wish to play"
x= ["rock","paper","scissors"]
global input_
input_=input(y+z+"?")
if input_ == "no":
return
max_score=("Enter max score : ")
while True:
input_=input("Enter your choice among rock, paper and scissors ('stop' to
quit):")
if input_ not in x and input_!='stop'and input_ != 'enough':
print("Invalid answer. Are you blind? Pick one from the 3.")
continue
n = random.randint(0,2)
k=x[n]
if n<2:
if input_==x[n+1]:
your_score+=1
elif input_==k:
pass
else:
comp_score+=1
else:
if input_=="paper":
comp_score+=1
elif input_=="rock":
your_score+=1
elif input_=="scissors":
pass
else:
pass
if input_!="stop" and input_ != "enough":
print(3)
time.sleep(1.5)
print(2)
time.sleep(1.5)
print(1)
time.sleep(1.5)
print("Your choice : "+input_ +"\nComputers move : "+k)
elif input_=="stop" and input_=="enough":
input_=input("Play again?")
if (your_score == max_score or comp_score==max_score) or (input_=="stop"
or input_=="enough"):
print("Your score is : ",your_score)
print("AI's score is : ",comp_score)
break
rock_paper_scissors()
if input_ !='no':
a=input("Do you wanna play again?")
if a =="yes":
rock_paper_scissors()
print("k.bye! \n :(")

Resources