I'm starting out with python, I only know the basics and I want to create a top-down type of game to the one I have currently.
I've tried some solutions on the internet and sadly, none of them has worked for me.
As I said, I can't find a working solution as of right now but I've tried a few, including this one
How can I make the player “look” to the mouse direction? (Pygame / 2D).
I'm also using pygame, forgot to mention that. I also have pgzero if you need to know.
This code works and it just places a new actor when you click on it, but I want to have a type of 'character' with a weapon that can move around and 'look' at the mouse.
import pgzrun
from random import randint
apple = Actor("apple")
score = 0
def draw():
screen.clear()
apple.draw()
def place_apple():
apple.x = randint(10, 800)
apple.y = randint(10, 600)
def on_mouse_down(pos):
global score
if apple.collidepoint(pos):
print("Good Shot!")
place_apple()
score = score + 1
print(score)
else:
print("You Missed!")
quit()
pgzrun.go()
I just need to know how to make the picture 'look' at the cursor and then what each bit does to I know hot to do it for next time.
The first time I tried with the link given above, It returned a positional argument and I can't figure it out.
I may have messed something up when I put in the fixed code but I don't know, I was kind of tired.
I am not sure what exactly you mean with "aim at the mouse" but I guess you want to change the drawn image according to some program logic.
You do this simply setting the image property of the Actor to another picture, eg. when you click on the image, see my modified version of your
def on_mouse_down(pos):
global score
if apple.collidepoint(pos):
print("Good Shot!")
place_apple()
score = score + 1
apple.image = "cactus" # ADDED: Change the image if your click hit the Actor
print(score)
else:
print("You Missed!")
quit()
You can find the documentation of the complete API (function calls and properties) here:
https://pygame-zero.readthedocs.io/en/stable/builtins.html
Related
I create a simple script to find image on the desktop ,and type 'I found it ' ,and if I hide the image the script type 'I am unable to found it'.
the problem when I add another action ,which is I want the mouse move to the position of the image. the script works good ,but when I hide the image the mouse still move to the position ,and still type I found it. But normally the code should show me I am unable to found it.
the script still working on if instead to move to else.
my code is:
import pyautogui
import time
location = pyautogui.locateOnScreen('image.png', confidence = 0.6)
while 1:
if location:
print("I found it ")
time.sleep(2)
print(pyautogui.moveTo(location))
else:
print("I am unable to found it")
you store pyautogui.locateOnScreen('image.png', confidence = 0.6) in the variable location. Then you check the condition (if/else). But then you never recheck for pyautogui.locateOnScreen('image.png', confidence = 0.6). I am still not sure what you are trying to achieve here, but at least the check needs to go into the while:
while 1:
location = pyautogui.locateOnScreen('image.png', confidence = 0.6)
if location:
print("I found it ")
time.sleep(2)
print(pyautogui.moveTo(location))
else:
print("I am unable to find it")
I have the following code:
answer = "ABC"
flag.goto(-999, -999)
while (answer.lower != 'y' or answer.lower != 'n'):
print("You got the flag! Free play(y/n)?")
answer = input("")
if answer.lower == 'y':
pass
if answer.lower == 'n':
return None
I am trying to remove the turtle called flag, through adding it to a list then deleting it with del(testlist[0]), but it didn't work.
The output is:
You got the flag! Free play(y/n)?
y
You got the flag! Free play(y/n)?
n
You got the flag! Free play(y/n)?
Your question is confusing as the title and text ask one thing, while your example code and output show something completely different.
Let's address this question:
Is there a way to remove a turtle from the screen?
Generally turtle.hideturtle() will do what you want. The only way to dispose of turtles once created is via a screen.clear() which will destroy all of them.
(The variable turtle above needs to be set to an instance of Turtle() and the variable screen needs to be set to the singular instance of Screen().
You can get a better view on the Visibility of turtles from this documentation.
Basically, you can use either turtle.hideturtle() or turtle.ht() to make a turtle invisible. But, that does not mean that the turtle is removed, and so it still takes up memory.
You can call turtle.Screen.clear(), but that resets everything, even the things you might want to keep.
If I were in a situation where I want to delete turtles instead of hiding them because doing that over and over again will take up too much memory, I'd simply hide the turtle, and when the program need another turtle, instead of creating another one, simply unhide the hidden turtle to be used again.
I am trying to make a text based rpg game in python. I just started and this is what my code looks so far:
class Game:
def __init__(self):
self.map = [[" " for i in range(50)]for i in range(30)]
def draw_map(self):
for i in range(len(self.map)):
print(self.map[i])
def add_stuff(self, thing, x, y):
self.map[y][x] = thing
game = Game()
class Player:
def __init__(self):
self.x = 1
self.y = 1
self.player = "ME"
def draw(self):
game.add_stuff(self.player, self.x, self.y)
def move(self):
pass
player = Player()
player.draw()
game.draw_map()
I was trying to find a way to implement a game loop in some way. To do this i was thinking of running the draw_map() and clearing the screen right away and printing the map again, a bit like real game loops. However i am having problems doing this. Based on other answers to other similar questions, i managed to produce the following code(it just shows the main loop and subprocess is imported as sp).
while True:
game.draw_map()
sp.call("cls", shell = True)
However this is not working for me. It simply dosent do anything. I also tried using clear function from clear_screen` module in a similar way and i cant figure out why this wouldnt work. Thanks for any help
so based on your previous comments you want to clear the screen in a Python interpreter. There is no "command" to clear the screen just like this. But you can use a loop to print some new lines until your screen is blank again.
def clear(lines):
for l in range(lines):
print()
while True:
game.draw_map()
clear(35)
time.sleep(0.05)
You may need to increase or decrease the amount of lines cleared. I hope this works for you. P.S.: I would use a normal console.
https://en.wikipedia.org/wiki/Interpreter_(computing)#Efficiency:
Efficiency:
The main disadvantage of interpreters is that an interpreted program typically runs slower than if it had been compiled. The difference in speeds could be tiny or great; often an order of magnitude and sometimes more. It generally takes longer to run a program under an interpreter than to run the compiled code but it can take less time to interpret it than the total time required to compile and run it. This is especially important when prototyping and testing code when an edit-interpret-debug cycle can often be much shorter than an edit-compile-run-debug cycle.
If your problem is clearing the console window, you can just use
import os
os.system('cls')
in place of
sp.call("cls", shell = True)
(Assuming you are working on windows)
EDIT for clarity:
This is the new loop after the change:
while True:
game.draw_map()
os.system('cls')
I'm making my own game with Python2.7 through the pygame libraby.
It's a 1v1 combat game where players use the same keyboard.
The game works in a main loop that is repeated 60times per second, every time the loop is executed, it calculates lots of things e.g the position, problem is that I have 2 players, so I have to write the lines two times.
Example here:
if p1direction == 'right' and p1XS < p1Attributes[1]: p1XS +=
p1Attributes[0]
and:
if p2direction == 'right' and p2XS < p2Attributes[1]: p2XS +=
p2Attributes[0]
See the differences p1 and p2, they are variables that belongs to Player 1 and Player 2 respectively.
I just want to find a solution to not write every time the same lines just for p2. I was thinking about the for function so I can even add players easly but I don't know how to do it in this case...
Can someone help me ? :) Please
Create a class player.
Then add the attributes of each player to the class.
Instantiate your class with player 1 and 2.
class Player():
direction = "right"
etc.
def shoot(self):
if self.direction == "right"
shoot_right()
playerOne = Player()
playerTwo = Player()
direction = playerOne.direction
If you haven't used classes yet, I wouldn't recommend using them though. Inheritance can get pretty nasty...
Hope that helped,
Narusan
EDIT:
If you haven't used classes in Python yet, I recommend catching up there first and then continuing your game development. I have programmed several games in pygame as well, and classes come in very hand. In fact, it is almost impossible to create pygame games without using proper classes (or endless if-clauses and for-loops that will make everything super slow).
Wish you all the best of luck
How about storing your variables(for example p1direction and p2direction) in a vector(player_directions) indexed by the player number and using a loop access it, for example:
number_of_players = 2
playersXS = function_that_fills_playersXS() # return a vector containing your p1XS and p2XS variables in a vector
for player_number in xrange(number_of_players):
if player_directions[player_number]=='right' and playersXS[player_number]< Attributes[player_number][1]:
playersXS[player_number]+=Attributes[player_number][0]
I have been working on this game, but I have a question when it comes to collision detection. Can I check for collision and have it return True:
example:
def collide(self, EnemyTank):
tank_collision = pygame.sprite.collide_rect(self.rect, EnemyTank.rect)
if tank_collision == True:
return True
And then make it perform an action like this:
if player.collide == True:
e_tank_x += 0
I am new to programming so please bear with me, I am trying as hard as I can and any comments or suggestions would also be very appreciated.
I'm not an expert of pygame, but it sound perfectly legitimate. I would just take away the middle man in your initial function:
def collide(self, EnemyTank):
return pygame.sprite.collide_rect(self.rect, EnemyTank.rect)
And you need to adjust the test you use, as you want to actually check the collision, while as you wrote it it just test if the function collide exist ;)
You can also use the implicit testing, removing some unnecessary character (best abith are best learned early)
if player.collide(EnemyTank):
do your action here
good luck with your game!