Variables has the same value, pygame - python

I'm trying to make a game in pygame, but for some reason actor and inp has the same value.
I tried to have them as arrays instead of classes, but it didn't solve the problem.
import pygame, sys
from pygame.locals import *
pygame.init()
screen=pygame.display.set_mode((640,360),0,32)
a=pygame.image.load('a.png')
class xy:
x=0
y=0
jump=0
actor=xy
inp=xy
def events():
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
return
elif event.type == KEYDOWN:
if event.key==K_LEFT:
inp.x=-1
elif event.key==K_RIGHT:
inp.x=1
elif event.key==K_UP:
inp.y=-1
elif event.key==K_DOWN:
inp.y=1
elif event.key==K_SPACE:
inp.jump=True
elif event.type==KEYUP:
if event.key==K_LEFT:
inp.x=0
elif event.key==K_RIGHT:
inp.x=0
elif event.key==K_UP:
inp.y=0
elif event.key==K_DOWN:
inp.y=0
elif event.key==K_SPACE:
inp.jump=False
return
def controller():
if inp.x<0:
actor.x-=1
elif inp.x>0:
actor.x+=1
if inp.y<0:
actor.y-=1
elif inp.y>0:
actor.y+=1
## actor.x+=inp.x
## actor.y+=inp.y
return
def screen_update():
pygame.draw.rect(screen, 0x006633, ((0,0),(640,360)),0)
screen.blit(a, (actor.x,actor.y))
pygame.display.update()
if __name__ == '__main__':
while True:
events()
print 'inp='+str(inp.x)+','+str(inp.y)
print 'actor='+str(actor.x)+','+str(inp.y)
controller()
screen_update()
Why can't the things I make work properly? :(

To put it simply, you're doing classes completely wrong.
class xy:
def __init__(self):
self.x = 0
self.y = 0
self.jump = 0
actor = xy()
inp = xy()

Related

Scrolling infinite background in Pygame [duplicate]

This question already has answers here:
Making the background move sideways in pygame
(2 answers)
How to scroll the background surface in PyGame?
(1 answer)
Why is my pygame application loop not working properly?
(1 answer)
Closed 2 years ago.
Hi I am trying to render out the menu_background in my menu screen with my menu options showing. When I run my code all I get is the image scrolling but my menu options and audio do not play and show. Anyone can help write code that makes it work where the audio plays and my menu options show up?
import pygame, sys, random, time, os, math
from pygame.locals import *
fps = pygame.time.Clock()
global screen
screen = pygame.display.set_mode((WIDTH, HEIGHT),pygame.FULLSCREEN)
display = pygame.Surface((400,250))
def menu_background():
menu_bg = pygame.image.load("assets/images/menu_bg.png").convert()
x = 0
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
rel_x = x % menu_bg.get_rect().width
screen.blit(menu_bg, (rel_x - menu_bg.get_rect().width, 0))
if rel_x < WIDTH:
screen.blit(menu_bg, (rel_x, 0))
x -= 1
pygame.display.update()
fps.tick(120)
def menu():
bg = menu_background()
menu_options = ['Play','Controls','Highscores','Settings','Credits','Quit']
menu_choice = 0
in_menu = True
pygame.mixer.music.load('assets/audio/mainmenu.wav')
while in_menu:
bg(display)
n = 0
for option in menu_options:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == K_UP:
menu_choice -= 1
if menu_choice < 0:
menu_choice = len(menu_options)-1
if event.key == K_DOWN:
menu_choice += 1
if menu_choice >= len(menu_options):
menu_choice = 0
if event.key == K_SPACE:
choice = menu_options[menu_choice]
if choice == 'Play':
play()
if choice == 'Controls':
controls()
screen.blit(pygame.transform.scale(display,(WIDTH,HEIGHT)),(0,0))
pygame.display.update()
fps.tick(60)
The major issue is that you have implemented 2 main application loops. The loops are executed one after the other.
(By the way, the first of this loops never terminates)
Put all the implementation in one loop. The application loop has to
handle the events and change states
draw the background
draw the scene and menu
update the display
e.g.:
def menu():
x = 0
menu_bg = pygame.image.load("assets/images/menu_bg.png").convert()
menu_options = ['Play','Controls','Highscores','Settings','Credits','Quit']
menu_choice = 0
in_menu = True
# load and play music
pygame.mixer.music.load('assets/audio/mainmenu.wav')
pygame.mixer.music.play()
while in_menu:
fps.tick(120)
# handle events
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == K_UP:
menu_choice -= 1
if menu_choice < 0:
menu_choice = len(menu_options)-1
if event.key == K_DOWN:
menu_choice += 1
if menu_choice >= len(menu_options):
menu_choice = 0
if event.key == K_SPACE:
choice = menu_options[menu_choice]
if choice == 'Play':
play()
if choice == 'Controls':
controls()
# draw background
rel_x = x % menu_bg.get_rect().width
screen.blit(menu_bg, (rel_x - menu_bg.get_rect().width, 0))
if rel_x < WIDTH:
screen.blit(menu_bg, (rel_x, 0))
x -= 1
# draw menu
#n = 0
#for option in menu_options:
# [...]
# update disaplay
pygame.display.update()
menu()

How to make multi-keystroke function in Python

I'm using Python 3.5 and I want to make multi-keystroke function. I want to make a function that notices Ctrl+Q but my program didn't notice it.
Here's my code:
import threading, pygame
from pygame.locals import *
from time import sleep
pygame.init()
screen = pygame.display.set_mode((1160, 640), 0, 0)
screen.fill((255, 255, 255))
pygame.display.flip()
def background():
number = 0
while True:
if number < 10:
number = number + 1
print(number)
sleep(1)
else:
print("10 seconds are over!")
break
def foreground():
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.key.get_mods() & pygame.KMOD_CTRL and pygame.K_q:
print('HELLO_WORLD')
b = threading.Thread(name='background', target=background)
f = threading.Thread(name='foreground', target=foreground)
b.start()
f.start()
I also changed
def foreground():
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.key.get_mods() & pygame.KMOD_CTRL and pygame.K_q:
print('HELLO_WORLD')
to
def foreground():
while True:
key = pygame.key.get_pressed()
if key[pygame.key.get_mods() & pygame.KMOD_CTRL and pygame.K_q]:
print('HELLO_WORLD')
but it didn't notice Ctrl+Q.
How can I make it?
Here's a possible fix for your code:
import threading
import pygame
from pygame.locals import *
from time import sleep
import sys
pygame.init()
screen = pygame.display.set_mode((1160, 640), 0, 0)
screen.fill((255, 255, 255))
pygame.display.flip()
def background():
number = 0
while True:
if number < 10:
number = number + 1
print(number)
sleep(1)
else:
print("10 seconds are over!")
break
def foreground():
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if pygame.key.get_mods() & pygame.KMOD_CTRL and event.key == pygame.K_q:
print('HELLO_WORLD')
pygame.display.update()
b = threading.Thread(name='background', target=background)
b.start()
foreground()

Pausing a game using pygame by pressing two keys simultaneously - tamagotchi project

I'm trying to implement a pause function in my tamagotchi clone (I'm practising for my controlled assessment next year) and I can't get the left and up keys to work simultaneously as a pause button. If possible I want to stay as true to the original game as possible so I would prefer not to use on-screen buttons. Thanks!
import pygame
import time
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
size =(200, 200)
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Tama v4.5')
screen.fill(WHITE)
pygame.init()
clock = pygame.time.Clock()
sprites = ['AdultSpriteAAA.png']
up_pressed = False
left_pressed = False
right_pressed = False
def main():
controls()
if up_pressed == True and left_pressed == True:
time.sleep(2)
pause()
player_position = pygame.mouse.get_pos()
x = player_position[0]
y = player_position[1]
screen.blit(background, [0,0])
screen.blit(sprite, [x, y])
pygame.display.flip()
clock.tick(60)
def controls():
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
print(animate())
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
global up_pressed
right_pressed = True
if event.key == pygame.K_LEFT:
global left_pressed
left_pressed = True
if event.key == pygame.K_RIGHT:
global right_pressed
right_pressed = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
global up_pressed
right_pressed = False
if event.key == pygame.K_LEFT:
global left_pressed
left_pressed = False
if event.key == pygame.K_RIGHT:
global right_pressed
right_pressed = False
def info():
return 0
def food():
return 1
def toilet():
return 2
def game():
return 3
def connect():
return 4
def talk():
return 5
def medic():
return 6
def post():
return 7
def history():
return 8
def animate():
return 9
def pause():
time.sleep(2)
while True:
controls()
if up_pressed == True and left_pressed == True:
time.sleep(2)
break
sprite = pygame.image.load(sprites[0]).convert()
background = pygame.image.load('Background 200x200.png').convert()
sprite.set_colorkey(BLACK)
while True:
main()
A way to make it pause when both left iey and up key are pressed is this:
import pygame
from pygame.locals import *
#game code
…
def pause():
keyspressed = pygame.keys.get_pressed()
if keyspressed[K_LEFT] and keyspressed[K_UP]:
#pause code
…
This code should be correct, but if you find any weird things, try to research the pygame key module. Keep in note that K_LEFT and K_UP are from pygame.locals, which is imported seperately from pygame
Here is a method that I have found really useful when writing games in PyGame:
if event.type == pygame.KEYDOWN
if event.key == (pygame.K_RIGHT and pygame.K_LEFT):
while True: # Infinite loop that will be broken when the user press the space bar again
event = pygame.event.wait()
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: # decid how to unpause?
break #Exit infinite loop
An interesting tid-bit I only recently discovered is that pygame.key.get_pressed() returns a tuple of 1s and 0s representing all of the keys on the keyboard, and these can be used as booleans or indexed to get the effective "value" of a key. Some great tuts at http://programarcadegames.com/

Why won't my Movement code work?

I am trying to make a character move around.
My problem is that when I run the program it immediately stops responding so I don't even know what the problem is.
Here is my code.
import pygame, sys
from pygame.locals import*
pygame.init()
DISPLAYSURF = pygame.display.set_mode((780, 500), 0, 32)
FPS = 30
fpsClock = pygame.time.Clock()
sprite = pygame.image.load('CharacterFront.png')
spritex = 50
spritey = 50
charLeft = False
charRight = False
charUp = False
charDown = False
while True:
DISPLAYSURF.blit(sprite,(spritex,spritey))
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if (event.key == K_LEFT):
charLeft = True
elif (event.key == K_d):
charRight = True
elif (event.key == K_w):
charUp = True
elif (event.key == K_s):
charDown = True
if event.type == KEYUP:
if (event.key == K_LEFT):
charLeft = False
elif (event.key == K_d):
charRight = False
elif (event.key == K_w):
charUp = False
elif (event.key == K_s):
charDown = False
while charLeft == True:
spritex -= 10
sprite=pygame.image.load('CharacterLeft.png')
while charRight == True:
spritex += 10
sprite=pygame.image.load('CharacterRight.png')
while charUp == True:
spritey -= 10
sprite=pygame.image.load('CharacterBack.png')
while charDown == True:
spritey += 10
sprite=pygame.image.load('CharacterFront.png')
pygame.display.update()
fpsClock.tick(FPS)
I have already tried many different ways to do this but the closest I got caused the character to get pasted over and over and I had to spam the directions to actually move more than 10 pixels.
Your while char.. loops never end. You are already looping (while True: at the top). Just make one move (e.g. spritey -= 10) and allow the outer loop to keep running.
For ideas on how to keep your character moving while a key is held, see this question.
Apart from what jonrsharpe said, you should not load the sprite every time a keypress is done.
Instead load all your images before, and just blit them when necessary.
So your code will look like this:
sprite_back = pygame.image.load('CharacterBack.png')
sprite_front = pygame.image.load('CharacterFront.png')
sprite_right = pygame.image.load('CharacterRight.png')
sprite_left = pygame.image.load('CharacterLeft.png')
sprite = sprite_front
while True:
DISPLAYSURF.blit(sprite,(spritex,spritey))
if charLeft == True:
spritex -= 10
elif charRight == True:
spritex += 10
elif charUp == True:
spritey -= 10
elif charDown == True:
spritey += 10
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if (event.key == K_LEFT):
charLeft = True
sprite=sprite_left
elif (event.key == K_d):
charRight = True
sprite=sprite_right
elif (event.key == K_w):
charUp = True
sprite=sprite_back
elif (event.key == K_s):
charDown = True
sprite=sprite_front
if event.type == KEYUP:
if (event.key == K_LEFT):
charLeft = False
elif (event.key == K_d):
charRight = False
elif (event.key == K_w):
charUp = False
elif (event.key == K_s):
charDown = False

Python-Pygame always crashing and Not Responding when running a module in IDLE

I'm quite new to Pygame or even Python, but i know that when something in the isn't right, it displays some text in the Python Shell telling you that there was some error. I've actually encountered many of them and this time, it finally runs and displays the window, but it does not respond. I know there might be some mistakes in my whole code so please feel free to correct me (and please, kindly explain since I'm still new to this stuff).
The code is below, but if it can help, if you'd ask for it, i'll see if i could post the file as well. Anyway, here's the codes:
#import Modules
import os, sys
import pygame
from pygame.locals import *
background_img="C:/Users/JM/Documents/Python/Pygame_Alpha/background_img.jpg"
cursor_img="C:/Users/JM/Documents/Python/Pygame_Alpha/pygameCursor.png"
def load_image(img_file, colorkey=None):
file_pathname = os.path.join("\Users\JM\Documents\Python\Pygame_Alpha",img_file)
try:
image = pygame.image.load(file_pathname).convert_alpha()
except pygame.error, message:
print "Can't load image:", file_pathname
raise SystemExit, message
image = image.convert()
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, RLEACCEL)
return image, image.get_rect()
#Main character's position and movements
char_x,char_y = 0,0
char_go_x,char_go_y = 0,0
#Main char class
class char(pygame.sprite.Sprite):
"""Main Character"""
def __init__(self):
pygame.sprite.Sprite.__init__(self)#call Sprite initializer
self.image, self.rect = load_image("char_img.png", -1)
self.jumping = 0
def update(self):
self.rect.midtop = char_x,char_y
if self.jumping == 1:
self.rect.move_ip(-35,-3)
def char_no_jump(self):
self.jumping = 0
pygame.init()
pygame.display.set_caption("pygame_Alpha")
screen = pygame.display.set_mode((800,480),0,32)
background = pygame.image.load(background_img).convert()
cursor = pygame.image.load(cursor_img).convert_alpha()
char = char()
clock = pygame.time.Clock()
millisec = clock.tick()
sec = millisec/1000.0
char_fall = sec*25
jump = sec*50
#blit the background
screen.blit(background,(0,0))
#Main Loop
while 1:
#Tell pygame not to exceed 60 FPS
clock.tick(60)
#Events
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
#Events triggered when a key/s is/are pressed
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
elif event.key == K_UP or event.key == K_w:
char.jumping = 1
elif event.key == K_DOWN or event.key == K_s:
char_go_y += 1
elif event.key == K_LEFT or event.key == K_a:
char_go_x -= 0.5
elif event.key == K_RIGHT or event.key == K_d:
char_go_x += 0.75
if char_x > 800:
char_x = 0
#Events triggered when a key/s is/are released
if event.type == KEYUP:
if event.key == K_UP or event.key == K_w:
char_go_y += 1
elif event.key == K_DOWN or event.key == K_s:
char_go_y = 0
elif event.key == K_LEFT or event.key == K_a:
char_go_x = 0
if char_x < 0:
char_x = 0
elif event.key == K_RIGHT or event.key == K_d:
char_go_x = 0
if char_x > 700:
char_x = 0
char.update()
while char_y < 200:
char_go_y += char_fall
if char_y > 200:
char_y = 200
#Update values of position of Main Char
char_x += char_go_x
char_y += char_go_y
#Position Variables of Cursor Image, setting its values equal to cursor pos, and blit it to screen
cursor_x,cursor_y = pygame.mouse.get_pos()
cursor_x -= cursor.get_width()/2
cursor_y -= cursor.get_height()/2
screen.blit(cursor,(cursor_x,cursor_y))
pygame.display.update()
Hmm...
while char_y < 200:
char_go_y += char_fall
Unless you have some interesting aliasing I'm not seeing, if char_y < 200 (which it should be at start, it will always be since you're updating char_go_y.
If that's not the issue, would still suggest adding some prints to figure out if it's getting through the loop or not.
is there any error message in idle when you run it? whenever the screen freezes you have something wrong, but its hard to pinpoint what without knowing the error messages. maybe it is trouble opening the picture, you should try putting .convert() at the end of your picture file name, but that is just a guess.
Calling pygame.quit and sys.exit are probably causing issues. Normally you'd never need them in pygame.
Instead of:
#Main Loop
while 1:
#Tell pygame not to exceed 60 FPS
clock.tick(60)
#Events
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
Do this
#Main Loop
done = False
while not done:
clock.tick(60)
for event in pygame.event.get():
if event.type == QUIT:
done = True
if event.type == KEYDOWN:
if event.key == K_ESC:
done = True

Categories