2014-10-09 71 views
1

如何編寫代碼以便使用pygame在python中通過鼠標移動來控制圖像?使用pygame在Python中進行遊戲編碼

如果能夠幫助編寫代碼,我將不勝感激,因爲我完全不知道如何去做。

我已經嘗試這樣的:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

import pygame 
import random 

pygame.init() 
size=[800,600] 
screen=pygame.display.set_mode(size) 
pygame.display.set_caption("Sub Dice") 

background_position=[0,0] 
background_image=pygame.image.load('C:\Users\SHIVANGI\Desktop\shivangi project\program\star.png').convert() 
card=pygame.image.load('C:\Users\SHIVANGI\Desktop\shivangi project\program\lappy.png').convert_alpha() 
card=pygame.transform.smoothscale(card,(130,182)) 
closeDeckShirt=pygame.image.load('C:\Users\SHIVANGI\Desktop\shivangi project\program\star.png').convert_alpha() 

SETFPS=30 
zx=0 
zy=0 

done=False 
clock=pygame.time.Clock() 

while done==False: 
    clock.tick(SETFPS) 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      done=True 

     if event.type == pygame.MOUSEBUTTONDOWN: 
      print('a') 


     screen.blit(background_image, background_position) 
     screen.blit(card,[zx,zy]) 
     zx=zx+2 
     zy=zy+2 
     pygame.display.flip() 

pygame.quit() 

然而,當我移動鼠標的運動,而不考慮的僅限於一個方向。我希望圖像向前移動,並通過鼠標的運動控制橫向運動。

此外,我的目標是創建一個像在orisinal上的水上機翼一樣的遊戲。

+0

與Pygame無關的一件事 - 字符串內的文件路徑應該使用雙''s或使用正斜槓('/'),否則它們可能會被破壞 - 因爲'\'是Python字符串內的scape字符。 – jsbueno 2014-10-09 17:16:16

回答

0

你非常接近做這項工作。 我做了一些小的修改。

所以,你的程序有2個問題。首先,無論事件如何,您的程序都會在每一個pygame.event上移動圖像 - 您會通過點擊一個鍵,單擊鼠標等來看到這一點。第二個問題是您要以固定的方向移動圖像。

唯一令我改變是你while循環:

while done==False: 
    clock.tick(SETFPS) 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      done=True 
    if event.type == pygame.MOUSEBUTTONDOWN: 
     print('a') 
    if event.type == pygame.MOUSEMOTION: # We only want to move the image when the mouse is moved. 
     mouse_position = pygame.mouse.get_pos() # Where is the mouse at? 
     screen.blit(background_image, background_position) 
     screen.blit(card,[zx,zy]) 
     zx=mouse_position[0] # mouse_position is in the form [x,y], we only want the x part 
     zy=mouse_position[1] 
    pygame.display.flip() 

正如你所看到的,Pygame的具有mouse.get_pos()功能,實際上在屏幕上得到您的鼠標的位置。這只是一個(x,y)座標。

+0

thanx很多。這是很多的幫助。 – nerd0711 2014-10-14 18:16:54