Coding an Interactive Game in Python Using Turtle: Hopper [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'd like to know how to code a certain portion of my game, Hopper. In this interactive python game using import turtle, I would like to create a turtle the user can control. I would like this turtle to jump when the spacebar is used, for the purpose of the user being able to jump over objects that should consistently move towards the player's turtle from the right side of the screen.
My question is, how to I make a circle shaped turtle jump when I hit the space bar and fall back to the ground, so that it can jump again when the next obstacle comes?
How do I create a code for obstacles, AKA, rectanglular shaped turtles, to move towards the player's circle turtle for the player's circle turtle to jump over? Thank you so so much for your time and help, will upvote.
If possible, I would love to know how to display a "Game Over" message if the player is unsuccessful in jumping over one of the rectangle obstacle turtles with the circle turtle.
Thank you again!

This is a common problem in Software Engineering. But let's take a step back. How do you cook breakfast? Well what's breakfast - let's say "boiled egg". What's an egg? What is it to "boil"? What sort of egg? Where does it come from? How big is it? Is it an Emu egg? How long do you boil it for? Etc. Etc. Etctera.
A big question like "How to Make Hopper" is really a huge list of tiny tiny problems. How do you draw on the screen, how to you read a key press, how do you move the turtle, how do I make that "sproinggg" sound when it jumps...
So. Start at the beginning, ignore the "noise" of what you can't do, and concentrate on what you can do. What's the simplest starting point? Write down some notes, draw some screen-layouts. Think about how it's all going to work. What are the first steps now?
Here's some simple code that opens a window and reads the keyboard. Take this code, and adapt it to handle the user-input according to your design.
import pygame
# Window size
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 400
WINDOW_SURFACE = pygame.HWSURFACE|pygame.DOUBLEBUF
WINDOW_MAX_FPS = 60
BACK_COLOUR = ( 3, 5, 54)
### initialisation
pygame.init()
pygame.mixer.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ), WINDOW_SURFACE )
pygame.display.set_caption("Hopper")
### Main Loop
clock = pygame.time.Clock()
done = False
while not done:
# Handle Window & Keyboard Events
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
done = True
elif ( event.type == pygame.KEYDOWN ):
if ( event.key == pygame.K_SPACE ):
print( 'Space-key pushed' )
elif ( event.key == pygame.K_j ):
print( 'j pushed' )
# Handle Key-states
keys = pygame.key.get_pressed()
if ( keys[pygame.K_UP] ):
print("up")
elif ( keys[pygame.K_UP] ):
print("down")
# Update the window
window.fill( BACK_COLOUR )
pygame.display.flip()
clock.tick( WINDOW_MAX_FPS )
pygame.quit()
Next start with simple graphics - you don't need a graphic-artist drawn turtle-avatar at this stage, just a box. Once you have this drawing, work on making it move, then make it move according to user-input. Keep chipping away at the program, but heading towards your design.
Plenty of beginners here get stuck trying to implement a beautiful 50-frame player-walking animation as a first step, and get lost and disillusioned when it's not easy (or perfect). Keep it simple, and actually finish your project.

Related

How can I make the movement faster if I press the key?

I'm making a Tetris game now. I want to implement it so that if I press the down key , the block falls quickly, and if I press the left and right keys, the block moves quickly. Pressing the key used the pygame.key.get_pressed() function and used pygame.time.set_timer() function to make speed change. The game speed was set to 600 for the interval of pygame.time.set_timer(), but if I press the down key, the block drops quickly because the interval was set to 150 to speed up the game so that the block drops quickly. The problem is to implement the function on the left and right direction keys. It is also possible to move the left and right keys quickly if I change the interval. The problem is that the pygame.time.set_timer() function changes the speed of the entire game, so the block falls quickly as well as the left and right movements of the block. Is there a way to speed up left and right movements without touching the speed of other things? I'd appreciate it if you let me know, thanks!
code
elif start:
for event in pygame.event.get():
attack_stack = 0
pos = pygame.mouse.get_pos()
if event.type == QUIT:
done = True
elif event.type == USEREVENT:
# Set speed
if not game_over:
keys_pressed = pygame.key.get_pressed()
# Soft drop
if keys_pressed[K_DOWN]:
pygame.time.set_timer(pygame.USEREVENT, 100)
elif keys_pressed[K_RIGHT]:
pygame.time.set_timer(pygame.USEREVENT, 100)
if not is_rightedge1(dx, dy, mino_en, rotation, matrix):
ui_variables.move_sound.play()
dx += 1
elif keys_pressed[K_LEFT]:
pygame.time.set_timer(pygame.USEREVENT, 100)
if not is_leftedge1(dx, dy, mino_en, rotation, matrix):
ui_variables.move_sound.play()
dx -= 1
else:
pygame.time.set_timer(pygame.USEREVENT, 600)
Waiting a long time (100 ms is already long) before reacting to user input feels bad, so you don’t want to wait a full piece-movement time before checking for input again just because there is none at the moment you check. Instead, poll for input at a steady pace of (say) 30 Hz; for simplicity, the usual approach is to just run the whole game at that frequency even if nothing needs to change on the screen for some (or even most) frames. (This technique also naturally allows smooth animations of or between piece movements.)
The usual implementation of “nothing” on a frame is to adjust the piece’s position every frame but integer-divide that position by some constant before using it for anything other than keeping track of its progress toward the next movement (like drawing it or checking for collisions). You might use pixels as the “invisible unit” when movement must be by whole tiles; games where sprites can be drawn at any pixel divide each into some convenient number of subpixels in the same fashion.
It looks to me that the reason your piece is dropping faster when you press a button is because if the user doesn't press a button the timer is set to 600ms. If they do press a button then the timer is set to 100ms.
As for how to fix this, you'll need to decouple the downward piece movement and user-input movement. I'd suggest making another event that only handles downward movement.
DROPEVENT = pygame.USEREVENT + 1
elif event.Type == DROPEVENT:
pygame.time.set_timer(DROPEVENT, 600)
# Your piece drop logic.
This snippet is not complete nor tested at all, but I hope it get the idea across. You don't seem to have posted the logic that handles dropping the piece, but you would need to move this into the new event.

Pygame moving multiple sprites not working as expected [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am making space invaders in pygame, I am relatively new to python and this is my first project in pygame. I am trying to make my aliens move down when reaching the edge of the screen on either side. However, it is not quite working as expected. I am adding a link to a GitHub page so that anyone willing to help can view my code.
Basically what's happening is I have set the aliens to move down 1 pixel when touching the sides because when there are a lot of aliens, this moves them down quite a bit. Obviously, as the aliens start getting killed off, they move down less. However, that is not the strange part. The strange part is the fact that sometimes they will move down 1 px on the one side, but many on the other side. I'm not quite sure what I am doing wrong.
https://github.com/Kris-Stoltz/space_invaders
Add break statements so you don't call update multiple times (if an even number of aliens hit the wall, you end up traveling the same direction!)
You have to increase the y advance in update too:
for alien in aliens:
if alien.rect.right >= WIDTH:
aliens.update()
break
elif alien.rect.left <= 0:
aliens.update()
break
and:
def update(self):
self.direction *= -1
self.rect.y += 10
The code looks pretty cool though!
I changed that code to
for alien in aliens:
if alien.rect.right >= WIDTH-1:
aliens.update()
elif alien.rect.left <= 1:
aliens.update()
But I see if enemies too less they don't move down
def update(self):
print("x",self.rect.y)
self.rect.y += 1
print("y",self.rect.y)
self.direction *= -1
That peace of code looks like incorrect

Indefinitely move Python turtle while allowing input

I've just started working on a version of Snake using Turtle, and I've encountered an issue. I want the snake to move indefinitely, but also to allow the user to move the snake with the keyboard. I got the snake to move from user input, but I can't figure out how to get the snake to keep moving in the same direction while there is no input, whilst preventing it from ignoring user input:
while True:
win.onkey(up,"Up")
win.onkey(right,"Right")
win.onkey(down,"Down")
win.onkey(left,"Left")
win.listen()
#moves the snake one unit in the same direction it is currently facing
movesnake()
I'm new to Turtle, and this is my guess at how to solve this issue - which obviously doesn't work. Any help would be appreciated. I'm conscious Pygame might make this easier but since I've already started with Turtle, I would prefer to get a Turtle solution, if possible.
An event-driven environment like turtle should never have while True: as it potentially blocks out events (e.g. keyboard). Use an ontimer() event instead.
Generally, onkey() and listen() don't belong in a loop -- for most programs they only need to be called once.
Here's a skeletal example of an autonomous turtle being redirected by user input:
from turtle import Screen, Turtle
def right():
snake.setheading(0)
def up():
snake.setheading(90)
def left():
snake.setheading(180)
def down():
snake.setheading(270)
def movesnake():
snake.forward(1)
screen.ontimer(movesnake, 100)
snake = Turtle("turtle")
screen = Screen()
screen.onkey(right, "Right")
screen.onkey(up, "Up")
screen.onkey(left, "Left")
screen.onkey(down, "Down")
screen.listen()
movesnake()
screen.mainloop()

Pygame, the window becomes irresponsive when I try to click it

I'm working on a game with Pygame and it was going well...until it decided to not respond. Here's my code:(sorry if the formatting doesn't work im new to stackoverflow)
#MODULES USED (use from to make calling functions easier)
from random import *
from pygame import *
import pygame
from pygame.locals import *
pygame.init()
from time import *
#INITIALISE THE PYGAME WINDOW
pygame.event.pump()
screen = display.set_mode([500, 500])
blue = [230, 242, 255]
screen.fill(blue)
pygame.display.update()
default = pygame.image.load("default.jpg")
screen.blit(default, (0,0))
pygame.display.update()
click = pygame.mouse.get_pressed()
#BASIC HEXAPAWN
#ALL POSSIBLE COMPUTER'S MOVE BOARDS AS ARRAY HERE
#TThe moves from the board images are left to right
class Board:
def __init__(self, board, moves):
self.board = board
self.moves = moves
boards1 = [pygame.image.load("a1.jpg"), pygame.image.load("a2.jpg"), pygame.image.load("a3.jpg")] #move1 boards
#irrelevant stuff removed, just initialising the other boards.
#GAME MAIN LOOP
while True:
#START GAME - 1st move
print("You play as O, computer is X")
currentboard = "O O O\n# # #\nX X X"
print(currentboard)
#PLAYER MOVE 1
screen.blit(boards1[0], (0, 250))
pygame.display.update()
if boards1[0].get_rect().collidepoint(pygame.mouse.get_pos()) and click:
screen.blit(boards1[0], (0,0))
pmove = 0
#note: I haven't added the other board options yet.
currentboard = boards1[pmove]
#[insert more unnecessary code here]
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
break
pygame.quit()
Basically whenever I run the code, the Pygame window looks alright, but when I try to click on the image it just stops responding. Also the window is always stuck on a loading cursor, idk why.
I've tried everything I could find but, nope, not working.
If anyone can help then I'd appreciate it.
Thanks :)
Eleeza
edit:i didnt know others could edit my posts too
Clearing some stuff up, when I ran my code, there were no errors, no Traceback the only problem is the unresponsive thing.
Also sorry im really bad at explaining things :/
There are a few things going on, but the main one is that you have you click variable set only once when the program starts.
Move click = pygame.mouse.get_pressed() inside of the main loop.
If you do that and it still hangs, you should show the rest of your code.
Also, the full code is not there, so I can't be 100% sure, but I don't think that break should be there.

Why Does PyGame Trail the Image? [duplicate]

This question already has answers here:
Pygame how to fix 'trailing pixels'?
(4 answers)
Closed 5 years ago.
I'm trying to develop a simple game in python using pygame and IDLE. I have, since yesterday, looked through a variety of sources in order to learn about the language (and programming in general), even so I have encountered some problems and misunderstandings of how it all works. So, if anyone could please advise me on how to proceed (or point me in the direction of some good learning material) then I would appreciate it greatly.
So far, I've got a small bit of code that forms the basis of my game idea, so I will post it here and list some of my problems.
import pygame
def main():
pygame.init()
logo = pygame.image.load("coolblack.jpg")
pygame.display.set_icon(logo)
pygame.display.set_caption("Battleship")
screenWidth = 800
screenHeight = 600
screen = pygame.display.set_mode((screenWidth, screenHeight))
bgd_image = pygame.image.load("grid.png")
#--------------------------------------------------------------------
#the image named 'image' should be above 'bgd_image' but below 'cv9'
#in fact, everything should be above bgd_image, especially 'cv9'
#--------------------------------------------------------------------
image = pygame.image.load("coolblack.jpg")
cv9 = pygame.image.load("ussessexcv9.gif").convert_alpha()
xposCv9 = 400
yposCv9 = 510
step_xCv9 = 1
step_yCv9 = 1
screen.blit(bgd_image, (0,0))
screen.blit(image, (400,300))
screen.blit(cv9, (xposCv9, yposCv9))
pygame.display.flip()
clock = pygame.time.Clock()
running = True
#---------------------------------------------
#I've got a pretty good idea (sort of) about
#what is happening in the section
#below this point, however it seems that
#the image 'cv9' creates a trail of itself
#every time it moves, so how could I make it
#so that it doesn't do so?
#---------------------------------------------
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
running = False
if xposCv9>screenWidth-64 or xposCv9<0:
step_xCv9 = -step_xCv9
if yposCv9>screenHeight-64 or yposCv9<0:
step_yCv9 = -step_yCv9
xposCv9 += step_xCv9
yposCv9 += step_yCv9
screen.blit(cv9, (xposCv9, yposCv9))
pygame.display.flip()
clock.tick(60)
if __name__=="__main__":
main()
The way that pygame works is that it has internally a representation of the screen which you are updating. So, it starts entirely black, then you do your first "blit". This will update the internal representation. Then when you call "pygame.display.flip" it shows that representation on the screen. However, this will not automatically "clear" the representation for you back to all black for your next frame. So, on the next frame, you blit again (slightly to the left, say), and the first blit remains, creating your "trail".
Therefore, for what you're doing, the best thing would be to in your loop, clear the internal representation of the screen before you start drawing the next frame. You can "clear" the screen by filling it with a single color, like so...
BLACK = (0,0,0)
....
screen.blit(cv9, (xposCv9, yposCv9))
pygame.display.flip()
clock.tick(60)
screen.fill(BLACK) # Add this to "clear" the screen.
Note that if you chose to go this route, this means you will need to redraw ALL of the elements every single frame (not just the ones that changed since the last frame).
BTW, in case you are wondering, there is a good reason for why the frame is not automatically cleared at the end. In some cases, it might be faster to only update the parts of the screen that update. This can cause performance speedups in some applications. However, it's probably best to start with clearing the screen as the example shows above.

Categories

Resources